<?php

namespace addons\webman\controller;

use addons\webman\model\AdminDepartment;
use addons\webman\model\AdminRole;
use addons\webman\model\AdminRoleUsers;
use addons\webman\model\AdminUser;
use addons\webman\model\Channel;
use ExAdmin\ui\component\common\Copy;
use ExAdmin\ui\component\common\Html;
use ExAdmin\ui\component\form\Form;
use ExAdmin\ui\component\grid\grid\Filter;
use ExAdmin\ui\component\grid\grid\Grid;
use ExAdmin\ui\component\grid\tag\Tag;
use ExAdmin\ui\component\grid\ToolTip;
use ExAdmin\ui\response\Response;
use ExAdmin\ui\support\Arr;
use ExAdmin\ui\support\Request;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use support\Db;

/**
 * 渠道管理
 */
class ChannelController
{
    protected $model;

    public function __construct()
    {
        $this->model = plugin()->webman->config('database.channel_model');

    }

    /**
     * 渠道
     * @auth true
     */
    public function index(): Grid
    {
        return Grid::create(new $this->model, function (Grid $grid) {
            $grid->title(admin_trans('channel.title'));
            $grid->model()->with(['department'])->orderBy('created_at', 'desc');
            $grid->autoHeight();
            $grid->bordered(true);
            $grid->column('department_id', admin_trans('channel.fields.id'))->align('center')->fixed(true);
            $grid->column('name', admin_trans('channel.fields.name'))->align('center')->fixed(true);
            $grid->column('department.leader', admin_trans('channel.fields.leader'))->align('center')->copy()->fixed(true);
            $grid->column('department.phone', admin_trans('channel.fields.phone'))->align('center')->copy();
            $grid->column('player_num', admin_trans('channel.fields.player_num'))->display(function ($val, Channel $data) {
                return $data->player->count();
            })->align('center');
            $grid->column('created_at', admin_trans('channel.fields.create_at'))->align('center');
            $grid->column('status', admin_trans('channel.fields.status'))->switch();
            $grid->column('lang', admin_trans('channel.fields.lang'))->display(function ($val) {
                return Html::create()->content([
                    admin_config('ui.lang.list')[$val] ?? ''
                ]);
            })->align('center');
            $grid->column('currency', admin_trans('channel.fields.currency'))->align('center');
            $grid->column('pay_type', admin_trans('channel.fields.pay_type'))->display(function ($val) {
                return Html::create()->content([
                    admin_trans('channel.pay_type.'.$val)
                ]);
            })->align('center')->align('center');
            $grid->column('game_id', admin_trans('channel.fields.game_id'))->display(function ($val) {
                return Html::create()->content([
                    admin_trans('channel.game.'.$val)
                ]);
            })->align('center')->align('center');
            $grid->column('channel_function', admin_trans('channel.fields.channel_function'))->display(function ($value, Channel $channel) {
                $channelFunction = [];
                if ($channel->web_login_status == 1) {
                    $channelFunction[] = 'web_login_status';
                }
                if ($channel->recharge_status == 1) {
                    $channelFunction[] = 'recharge_status';
                }
                if ($channel->withdraw_status == 1) {
                    $channelFunction[] = 'withdraw_status';
                }
                if ($channel->wallet_action_status == 1) {
                    $channelFunction[] = 'wallet_action_status';
                }
                if ($channel->promotion_status == 1) {
                    $channelFunction[] = 'promotion_status';
                }
                $html = Html::create();
                foreach ($channelFunction as $option) {
                    $html->content(
                        Tag::create(admin_trans('channel.fields.' . $option))
                            ->color('success')
                    );
                }
                return $html;
            })->align('center');
            $grid->column('player_total_amount', admin_trans('channel.fields.player_total_amount'))->display(function ($val, Channel $data) {
                return $data->wallet()->sum('money');
            })->align('center');
            $grid->column('domain', admin_trans('channel.fields.domain'))->display(function ($value) {
                return ToolTip::create(Str::of($value)->limit(30, ' (...)'))->title($value);
            })->width('150px')->align('center')->ellipsis(true)->copy();
            $grid->column('telegram_url', admin_trans('channel.fields.whats_app'))->display(function ($value) {
                return ToolTip::create(Str::of($value)->limit(30, ' (...)'))->title($value);
            })->width('150px')->align('center')->ellipsis(true)->copy();
            $grid->column('package_url', admin_trans('channel.fields.package_url'))->display(function ($value) {
                return ToolTip::create(Str::of($value)->limit(30, ' (...)'))->title($value);
            })->width('150px')->align('center')->ellipsis(true)->copy();
            $grid->hideDelete();
            $grid->setForm()->drawer($this->form());
            $grid->filter(function (Filter $filter) {
                $filter->eq()->text('id')->placeholder(admin_trans('channel.fields.id'));
                $filter->like()->text('name')->placeholder(admin_trans('channel.fields.name'));
                $filter->like()->text('phone')->placeholder(admin_trans('channel.fields.phone'));
                $filter->like()->text('leader')->placeholder(admin_trans('channel.fields.leader'));
                $filter->eq()->select('status')
                    ->placeholder(admin_trans('channel.fields.status'))
                    ->showSearch()
                    ->style(['width' => '200px'])
                    ->dropdownMatchSelectWidth()
                    ->options([
                        1 => admin_trans('channel.normal'),
                        0 => admin_trans('channel.disable')
                    ]);
            });
            $grid->quickSearch(function (Builder $builder, $quickSearch) {
                $builder->whereHas('department', function ($query) use ($quickSearch) {
                    $query->where([
                        ['leader', 'like', '%' . $quickSearch . '%', 'or'],
                        ['phone', 'like', '%' . $quickSearch . '%', 'or'],
                    ]);
                })->orWhere('id', $quickSearch)
                    ->orWhere('name', $quickSearch)
                    ->orWhere('domain', $quickSearch);
            });
            $grid->deleted(function ($ids) {
                DB::beginTransaction();
                try {
                    $departmentIds = Arr::pluck(Channel::select('department_id')->whereIn('id', $ids)->withTrashed()->get()->toArray(), 'department_id');
                    AdminDepartment::whereIn('id', $departmentIds)->delete();
                    AdminUser::whereIn('department_id', $departmentIds)->delete();
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                }
            });
        });
    }

    /**
     * 渠道
     * @auth true
     */
    public function form(): Form
    {
        return Form::create(new $this->model, function (Form $form) {
            $form->title(admin_trans('channel.title'));
            $form->row(function (Form $form) {
                $form->text('name', admin_trans('channel.fields.name'))
                    ->ruleChsDash()
                    ->rule([
                        (string)Rule::unique(plugin()->webman->config('database.channel_model'))->ignore($form->input('id')) => admin_trans('channel.name_exist'),
                    ])
                    ->required();
                $form->text('domain', admin_trans('channel.fields.domain'))
                    ->ruleUrl()
                    ->rule([
                        (string)Rule::unique(plugin()->webman->config('database.channel_model'))->ignore($form->input('id')) => admin_trans('channel.channel_exist'),
                    ])
                    ->required()->style(['margin-left' => '10px']);
            });
            $form->row(function (Form $form) {
                $form->text('department.phone', admin_trans('channel.fields.phone'))->ruleNumber();
                $form->text('department.leader', admin_trans('channel.fields.leader'))->style(['margin-left' => '10px']);
            });
            $form->text('telegram_url', admin_trans('channel.fields.whats_app'))
                ->ruleUrl()
                ->rule([
                    (string)Rule::unique(plugin()->webman->config('database.channel_model'))->ignore($form->input('id')) => admin_trans('channel.telegram_url_exist'),
                ])
                ->required();
            $form->text('package_url', admin_trans('channel.fields.package_url'))
                ->ruleUrl()
                ->rule([
                    (string)Rule::unique(plugin()->webman->config('database.channel_model'))->ignore($form->input('id')) => admin_trans('channel.package_url_exist'),
                ])
                ->required();
            $form->radio('currency', admin_trans('channel.fields.currency'))
                ->button()
                ->options(plugin()->webman->config('currency'))
                ->required();
            $form->radio('lang', admin_trans('channel.fields.lang'))
                ->button()
                ->options(admin_config('ui.lang.list'))
                ->required();
            $form->radio('game_id', admin_trans('channel.fields.game_id'))
                ->button()
                ->options(plugin()->webman->config('game'))
                ->required();
            $form->row(function (Form $form) {
                if (!$form->isEdit()) {
                    $form->text('user.username', admin_trans('channel.fields.username'))
                        ->ruleChsDash()
                        ->rule([
                            (string)Rule::unique(plugin()->webman->config('database.user_model'), 'username')->ignore($form->input('id')) => admin_trans('admin.username_exist'),
                        ])
                        ->required()
                        ->addonAfter(Copy::create($form->input('user.username')))
                        ->disabled($form->isEdit());
                    $form->password('user.password', admin_trans('channel.fields.password'))
                        ->default(123456)
                        ->help(admin_trans('admin.pass_help'))
                        ->required();
                } else {
                    $form->text('user.username', admin_trans('channel.fields.username'))
                        ->ruleChsDash()
                        ->addonAfter(Copy::create($form->input('user.username')))
                        ->disabled($form->isEdit());
                }
            });
            $channelFunction = [];
            if ($form->isEdit()) {
                $id = $form->driver()->get('id');
                /** @var Channel $channel */
                $channel = Channel::find($id);
                if ($channel->recharge_status == 1) {
                    $channelFunction[] = 'recharge_status';
                }
                if ($channel->withdraw_status == 1) {
                    $channelFunction[] = 'withdraw_status';
                }
                if ($channel->web_login_status == 1) {
                    $channelFunction[] = 'web_login_status';
                }
                if ($channel->wallet_action_status == 1) {
                    $channelFunction[] = 'wallet_action_status';
                }
                if ($channel->promotion_status == 1) {
                    $channelFunction[] = 'promotion_status';
                }
            }
            $form->row(function (Form $form) use ($channelFunction) {
                $form->checkbox('channel_function', admin_trans('channel.fields.channel_function'))
                    ->value($channelFunction)
                    ->options([
                        'web_login_status' => admin_trans('channel.fields.web_login_status'),
                        'recharge_status' => admin_trans('channel.fields.recharge_status'),
                        'withdraw_status' => admin_trans('channel.fields.withdraw_status'),
                        'wallet_action_status' => admin_trans('channel.fields.wallet_action_status'),
                        'promotion_status' => admin_trans('channel.fields.promotion_status'),
                    ]);
            });
            $form->layout('vertical');
            $form->saving(function (Form $form) {
                $channelFunction = $form->input('channel_function');
                if (!empty($channelFunction)) {
                    $artificial = collect(['recharge_status', 'withdraw_status']);
                    $intersectArtificial = $artificial->intersect($channelFunction)->toArray();
                    if (!empty($intersectArtificial) && !empty($intersectQTalk)) {
                        return message_error(admin_trans('channel.channel_function_help'));
                    }
                }
                if (!$form->isEdit()) {
                    DB::beginTransaction();
                    try {
                        $adminDepartment = new AdminDepartment();
                        $adminDepartment->name = $form->input('name');
                        $adminDepartment->leader = $form->input('department.leader');
                        $adminDepartment->phone = $form->input('department.phone');
                        $adminDepartment->type = AdminDepartment::TYPE_CHANNEL;
                        $adminDepartment->save();

                        $adminUser = new AdminUser();
                        $adminUser->username = $form->input('user.username');
                        $adminUser->password = $form->input('user.password');
                        $adminUser->nickname = $form->input('name');
                        $adminUser->department_id = $adminDepartment->id;
                        $adminUser->type = AdminDepartment::TYPE_CHANNEL;
                        $adminUser->is_super = 1;
                        $adminUser->save();

                        $adminRole = new AdminRoleUsers();
                        $adminRole->role_id = AdminRole::ROLE_CHANNEL;
                        $adminRole->user_id = $adminUser->id;
                        $adminRole->save();

                        $channel = new Channel();
                        $channel->name = $form->input('name');
                        $channel->domain = $form->input('domain');
                        $channel->telegram_url = $form->input('telegram_url');
                        $channel->package_url = $form->input('package_url');
                        $channel->lang = $form->input('lang');
                        $channel->game_id = $form->input('game_id');
                        $channel->currency = $form->input('currency');
                        $channel->pay_type = $form->input('pay_type') ?? 4;
                        $channel->department_id = $adminDepartment->id;
                        $channel->user_id = $adminUser->id;
                        $channel->site_id = gen_uuid(); // 站点标识
                        $channel->recharge_status = in_array('recharge_status', $channelFunction);
                        $channel->withdraw_status = in_array('withdraw_status', $channelFunction);
                        $channel->web_login_status = in_array('web_login_status', $channelFunction);
                        $channel->wallet_action_status = in_array('wallet_action_status', $channelFunction);
                        $channel->promotion_status = in_array('promotion_status', $channelFunction);
                        $channel->save();

                        DB::commit();
                    } catch (\Exception $e) {
                        DB::rollBack();
                        return message_error($e->getMessage());
                    }
                    $adminDepartment->path = $adminDepartment->id;
                    $adminDepartment->save();
                    return message_success(admin_trans('channel.save_success'));
                } else {
                    $orgData = $form->driver()->get();
                    /** @var Channel $channel */
                    $channel = Channel::find($orgData['id']);
                    if (empty($channel)) {
                        return message_error(admin_trans('channel.not_fount'));
                    }
                    DB::beginTransaction();
                    try {
                        $channel->name = $form->input('name');
                        $channel->domain = $form->input('domain');
                        $channel->telegram_url = $form->input('telegram_url');
                        $channel->package_url = $form->input('package_url');
                        $channel->lang = $form->input('lang');
                        $channel->game_id = $form->input('game_id');
                        $channel->currency = $form->input('currency');
                        $channel->pay_type = $form->input('pay_type') ?? 4;
                        $channel->recharge_status = in_array('recharge_status', $channelFunction);
                        $channel->withdraw_status = in_array('withdraw_status', $channelFunction);
                        $channel->web_login_status = in_array('web_login_status', $channelFunction);
                        $channel->wallet_action_status = in_array('wallet_action_status', $channelFunction);
                        $channel->status = $form->input('status');
                        $channel->promotion_status = in_array('promotion_status', $channelFunction);
                        $channel->save();
                        /** @var AdminDepartment $adminDepartment */
                        $adminDepartment = AdminDepartment::find($channel->department_id);
                        $adminDepartment->name = $form->input('name');
                        $adminDepartment->leader = $form->input('department.leader');
                        $adminDepartment->phone = $form->input('department.phone');
                        $adminDepartment->save();
                        DB::commit();
                    } catch (\Exception $e) {
                        DB::rollBack();
                        return message_error(admin_trans('channel.save_error'));
                    }
                    return message_success(admin_trans('channel.save_success'));
                }
            });
        });
    }

    /**
     * 筛选部门/渠道
     * @return mixed
     */
    public function getDepartmentOptions()
    {
        $request = Request::input();
        $channel = Channel::orderBy('created_at', 'desc');
        if (!empty($request['search'])) {
            $channel->where('name', 'like', '%' . $request['search'] . '%');
        }
        $channelList = $channel->get();
        $data = [];
        /** @var Channel $channel */
        foreach ($channelList as $channel) {
            $data[] = [
                'value' => $channel->department_id,
                'label' => $channel->name,
            ];
        }
        return Response::success($data);
    }
}
