<?php

namespace addons\webman\controller;

use addons\webman\Admin;
use addons\webman\model\AdminUser;
use addons\webman\model\ChannelRechargeMethod;
use addons\webman\model\ChannelRechargeMethodLang;
use addons\webman\model\ChannelRechargeSetting;
use addons\webman\model\SepayRecharge;
use addons\webman\model\SystemSetting;
use ExAdmin\ui\component\common\Button;
use ExAdmin\ui\component\common\Html;
use ExAdmin\ui\component\form\field\Switches;
use ExAdmin\ui\component\form\Form;
use ExAdmin\ui\component\grid\grid\Actions;
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\layout\Divider;
use ExAdmin\ui\support\Arr;
use ExAdmin\ui\support\Container;
use Illuminate\Database\Eloquent\Builder;
use support\Db;

/**
 * 充值渠道
 * @group channel
 */
class ChannelRechargeController
{
    protected $model;
    protected $method;
    protected $sepay_model;

    public function __construct()
    {
        $this->model = plugin()->webman->config('database.channel_recharge_setting_model');
        $this->method = plugin()->webman->config('database.channel_recharge_method_model');
        $this->sepay_model = plugin()->webman->config('database.sepay_recharge_model');
    }

    /**
     * 充值账号
     * @group channel
     * @auth true
     */
    public function index(): Grid
    {
        return Grid::create(new $this->model, function (Grid $grid) {
            $lang = Container::getInstance()->translator->getLocale();
            $channelRechargeMethods = ChannelRechargeMethod::query()
                ->where('status', 1)
                ->select(['id', 'account', 'currency'])
                ->with(['methodLang' => function ($query) use ($lang) {
                    $query->where('lang', $lang);
                }])
                ->get()->toArray();
            foreach ($channelRechargeMethods as &$item) {
                $item['name'] = $item['method_lang'][0]['name'] ?? '';
            }
            $grid->sidebar('method_id', $channelRechargeMethods)
                ->setForm($this->methodForm());
            $grid->title(admin_trans('channel_recharge_setting.title'));
            $grid->model()->with(['channel_recharge_method'])->whereHas('channel_recharge_method', function ($query) {
                $query->whereNull('deleted_at');
            });
            $grid->autoHeight();
            $grid->bordered(true);
            $lang = Container::getInstance()->translator->getLocale();
            $grid->tools([
                Button::create(admin_trans('channel_recharge_setting.first_recharge_setting'))
                    ->danger()
                    ->drawer($this->rechargeSetting())
            ]);
            $grid->column('id', admin_trans('channel_recharge_setting.fields.id'))->align('center');
            $grid->column('title', admin_trans('channel_recharge_setting.fields.title'))->align('center');
            $grid->column('method_name', admin_trans('channel_recharge_setting.fields.method_name'))
                ->display(function ($val, ChannelRechargeSetting $data) use ($lang) {
                    /** @var ChannelRechargeMethodLang $methodLang */
                    $methodLang = $data->channel_recharge_method->methodLang->where('lang', $lang)->first();
                    return $methodLang->name ?? '';
                })
                ->align('center')
                ->ellipsis(true);
            $grid->column('type', admin_trans('player_delivery_record.fields.type'))
                ->display(function ($value) {
                    switch ($value) {
                        case ChannelRechargeSetting::TYPE_REGULAR:
                            $tag = Tag::create(admin_trans('channel_recharge_setting.type.' . ChannelRechargeSetting::TYPE_REGULAR))->color('#2db7f5');
                            break;
                        case ChannelRechargeSetting::TYPE_ACTIVITY:
                            $tag = Tag::create(admin_trans('channel_recharge_setting.type.' . ChannelRechargeSetting::TYPE_ACTIVITY))->color('#3C87C9');
                            break;
                        default:
                            $tag = '';
                    }
                    return Html::create()->content([
                        $tag
                    ]);
                })->align('center')->sortable();
            $grid->column('chip_multiple', admin_trans('channel_recharge_setting.fields.chip_multiple'))->align('center');
            $grid->column('coins_num', admin_trans('channel_recharge_setting.fields.coins_num'))->align('center');
            $grid->column('gift_coins', admin_trans('channel_recharge_setting.fields.gift_coins'))->align('center');
            $grid->column('money', admin_trans('channel_recharge_setting.fields.money'))->align('center');
            $grid->column('user_name', admin_trans('channel_recharge_setting.fields.user_name'))->align('center');
            $grid->column('status', admin_trans('channel_recharge_setting.fields.status'))->switch()->align('center');
            $grid->filter(function (Filter $filter) {
                $filter->eq()->number('coins_num')->placeholder(admin_trans('channel_recharge_setting.fields.coins_num'));
                $filter->eq()->number('money')->placeholder(admin_trans('channel_recharge_setting.fields.money'));
            });
            $grid->quickSearch(function (Builder $builder, $quickSearch) {
                $builder->whereHas('channel_recharge_method.methodLang', function ($query) use ($quickSearch) {
                    $query->where([
                        ['name', 'like', '%' . $quickSearch . '%', 'or'],
                        ['bank_name', 'like', '%' . $quickSearch . '%', 'or'],
                        ['sub_bank', 'like', '%' . $quickSearch . '%', 'or'],
                        ['account', 'like', '%' . $quickSearch . '%', 'or'],
                        ['owner', 'like', '%' . $quickSearch . '%', 'or'],
                    ]);
                });
            });
            $grid->hideDelete();
            $grid->hideSelection();
            $grid->hideDeleteSelection();
            $grid->hideTrashed();
            $grid->addButton()->drawer($this->form());
            $grid->setForm()->drawer($this->form());
            $grid->actions(function (Actions $actions) {
                $actions->hideEdit();
            });
        });
    }

    /**
     * 充值账号配置
     * @auth true
     * @group channel
     * @return Form
     */
    public function form(): Form
    {
        /** @var ChannelRechargeMethod $channelRechargeMethod */
        $channelRechargeMethod = ChannelRechargeMethod::query()
            ->where('department_id', Admin::user()->department_id)
            ->where('type', 2)
            ->first();
        if (!$channelRechargeMethod) {
            $channelRechargeMethod = [
                'id' => '',
                'wallet_address' => '',
                'qr_code' => '',
                'rate' => '',
                'status' => '',
            ];
        }
        return Form::create($channelRechargeMethod, function (Form $form) use ($channelRechargeMethod) {
            $form->text('wallet_address', admin_trans('channel_recharge_setting.fields.wallet_address'))
                ->value($channelRechargeMethod['wallet_address'])
                ->required()
                ->maxlength(250);
            $form->file('qr_code', admin_trans('channel_recharge_setting.fields.qr_code'))
                ->ext('jpg,png,jpeg')
                ->value($channelRechargeMethod['qr_code'])
                ->type('image')
                ->fileSize('1m')
                ->required()
                ->hideFinder()
                ->paste();
            $form->number('rate', admin_trans('channel_recharge_setting.fields.rate'))
                ->min(0)
                ->max(100)
                ->value($channelRechargeMethod['rate'])
                ->span(24)
                ->style(['width' => '50%'])
                ->required()
                ->precision(2);
            $form->switch('status', admin_trans('channel_recharge_method.fields.status'))
                ->value($channelRechargeMethod['status'])->required()->span(11);
            $form->colon(false);
            $form->removeAttr('labelCol');
            $form->actions()->hideResetButton();
            $form->actions()->submitButton()->content(admin_trans('form.submit'));
            $form->layout('vertical');
            $form->saving(function (Form $form) use ($channelRechargeMethod) {
                try {
                    DB::beginTransaction();
                    if (!$channelRechargeMethod['id']) {
                        $channelRechargeMethod = new ChannelRechargeMethod();
                        $channelRechargeMethod->type = 2;
                        $channelRechargeMethod->currency = Admin::user()->department->channel->currency;
                        $channelRechargeMethod->department_id = Admin::user()->department_id;
                        $channelRechargeMethod->user_id = Admin::id();
                        $channelRechargeMethod->user_name = !empty(Admin::user()) ? Admin::user()->username : '';
                    }
                    $channelRechargeMethod->qr_code = $form->input('qr_code');
                    $channelRechargeMethod->wallet_address = $form->input('wallet_address');
                    $channelRechargeMethod->status = $form->input('status');
                    $channelRechargeMethod->rate = $form->input('rate');
                    $channelRechargeMethod->save();
                    DB::commit();
                } catch (\Exception $exception) {
                    DB::rollBack();
                    return message_error(admin_trans('form.save_error') . $exception->getMessage());
                }
                return message_success(admin_trans('form.save_success'));
            });
        });
    }

    /**
     * 获取充值方式
     * @return array
     */
    public function getRechargeMethod(): array
    {
        $options = [];
        $lang = Container::getInstance()->translator->getLocale();
        $methodList = ChannelRechargeMethod::query()->get();
        /** @var ChannelRechargeMethod $item */
        foreach ($methodList as $item) {
            /** @var ChannelRechargeMethodLang $methodLang */
            $methodLang = $item->methodLang->where('lang', $lang)->first();
            $options[$item->id] = $methodLang->name ?? '';
        }

        return $options;
    }

    /**
     * 充值方式
     * @auth true
     * @group channel
     * @return Form
     */
    public function methodForm(): Form
    {
        /** @var ChannelRechargeMethod $channelRechargeMethod */
        $channelRechargeMethod = ChannelRechargeMethod::query()
            ->where('department_id', Admin::user()->department_id)
            ->where('type', 1)
            ->first();
        if (!$channelRechargeMethod) {
            $channelRechargeMethod = [
                'id' => '',
                'account' => '',
                'status' => '',
            ];
        }
        return Form::create($channelRechargeMethod, function (Form $form) use ($channelRechargeMethod) {
            $form->row(function (Form $form) use ($channelRechargeMethod) {
                $form->text('account', admin_trans('channel_recharge_method.fields.account'))
                    ->maxlength(100)
                    ->value($channelRechargeMethod['account'])
                    ->required()
                    ->span(11);
                $form->push(Divider::create()->content(' ')->style(['margin-left' => '11px']));
                $form->switch('status', admin_trans('channel_recharge_method.fields.status'))
                    ->value($channelRechargeMethod['status'])->required()->span(11);
            });
            $langList = plugin()->webman->config('ui.lang.list');
            $tabs = $form->tabs()->destroyInactiveTabPane();
            $contents = [];
            if ($channelRechargeMethod['id']) {
                $channelRechargeMethodLang = ChannelRechargeMethodLang::query()->where('method_id', $channelRechargeMethod['id'])->get();
                /** @var ChannelRechargeMethodLang $content */
                foreach ($channelRechargeMethodLang as $content) {
                    $contents[$content->lang] = [
                        'name' => $content->name,
                        'bank_name' => $content->bank_name,
                        'sub_bank' => $content->sub_bank,
                        'owner' => $content->owner,
                        'id' => $content->id,
                    ];
                }
            }
            foreach ($langList as $k => $v) {
                $tabs->pane($v, function (Form $form) use ($k, $contents) {
                    $form->row(function (Form $form) use ($k, $contents) {
                        $form->text("content." . $k . ".name", admin_trans('channel_recharge_method.fields.method_name'))
                            ->maxlength(120)
                            ->value($contents[$k]['name'] ?? '')
                            ->required()
                            ->span(11);
                        $form->push(Divider::create()->content(' ')->style(['margin-left' => '11px']));
                        $form->text("content." . $k . ".bank_name", admin_trans('channel_recharge_method.fields.bank_name'))
                            ->value($contents[$k]['bank_name'] ?? '')
                            ->maxlength(100)
                            ->required()
                            ->span(11);
                    })->style(['width' => '100 % ', 'margin - left' => '1px']);
                    $form->row(function (Form $form) use ($k, $contents) {
                        $form->text("content." . $k . ".sub_bank", admin_trans('channel_recharge_method.fields.sub_bank'))
                            ->value($contents[$k]['sub_bank'] ?? '')
                            ->maxlength(100)
                            ->required()
                            ->span(11);
                        $form->push(Divider::create()->content(' ')->style(['margin-left' => '11px']));
                        $form->text("content." . $k . ".owner", admin_trans('channel_recharge_method.fields.owner'))
                            ->value($contents[$k]['owner'] ?? '')
                            ->maxlength(100)
                            ->required()
                            ->span(11);
                    })->style(['width' => '100 % ', 'margin - left' => '1px']);
                });
            }
            $form->colon(false);
            $form->removeAttr('labelCol');
            $form->actions()->hideResetButton();
            $form->actions()->submitButton()->content(admin_trans('form.submit'));
            $form->layout('vertical');
            $form->saving(function (Form $form) use ($channelRechargeMethod) {
                try {
                    DB::beginTransaction();
                    if ($channelRechargeMethod['id']) {
                        $channelRechargeMethod->account = $form->input('account');
                        $channelRechargeMethod->currency = Admin::user()->department->channel->currency;
                    } else {
                        $channelRechargeMethod = new ChannelRechargeMethod();
                        $channelRechargeMethod->account = $form->input('account');
                        $channelRechargeMethod->currency = Admin::user()->department->channel->currency;
                        $channelRechargeMethod->department_id = Admin::user()->department_id;
                        $channelRechargeMethod->user_id = Admin::id();
                        $channelRechargeMethod->user_name = !empty(Admin::user()) ? Admin::user()->username : '';
                    }
                    $channelRechargeMethod->status = $form->input('status');
                    $channelRechargeMethod->save();
                    $contents = $form->input('content');
                    foreach ($contents as $key => $content) {
                        if (empty($content['name'])) {
                            continue;
                        }
                        ChannelRechargeMethodLang::query()->updateOrCreate(
                            [
                                'lang' => $key,
                                'method_id' => $channelRechargeMethod->id,
                            ],
                            [
                                'name' => $content['name'],
                                'bank_name' => $content['bank_name'] ?? '',
                                'sub_bank' => $content['sub_bank'] ?? '',
                                'owner' => $content['owner'] ?? ''
                            ]
                        );
                    }
                    DB::commit();
                } catch (\Exception $exception) {
                    DB::rollBack();
                    return message_error(admin_trans('form.save_error') . $exception->getMessage());
                }
                return message_success(admin_trans('form.save_success'));
            });
        });
    }

    /**
     * @return Form
     */
    public function rechargeSetting(): Form
    {
        /** @var SystemSetting $systemSetting */
        $systemSetting = SystemSetting::query()
            ->where('department_id', Admin::user()->department_id)
            ->where('feature', 'first_recharge_setting')
            ->first();
        return Form::create($systemSetting ? [
            'id' => $systemSetting->id,
            'department_id' => $systemSetting->department_id,
            'feature' => $systemSetting->feature,
            'content' => json_decode($systemSetting->content, true),
            'status' => $systemSetting->status,
        ] : [], function (Form $form) use ($systemSetting) {
            $form->push(
                Switches::create('status')
                    ->options([[1 => admin_trans('admin.open')], [0 => admin_trans('admin.close')]])
                    ->field('status')
                    ->title('状态')
                    ->url('ex-admin/addons-webman-controller-ActivityController/changeStatus')
                    ->params([
                        'id' => $systemSetting->id,
                    ])->style(['margin-bottom' => '14px'])
            );
            $form->hasMany('content', '', function (Form $form) {
                $form->row(function (Form $form) {
                    $form->radio('model', admin_trans('first_recharge_setting.fields.model'))
                        ->button()
                        ->required()
                        ->default(SystemSetting::FIRST_RECHARGE_MODEL_ONE)
                        ->bindAttr('buttonStyle', $form->getBindField('buttonStyle'))
                        ->options([
                            SystemSetting::FIRST_RECHARGE_MODEL_ONE => admin_trans('first_recharge_setting.model.' . SystemSetting::FIRST_RECHARGE_MODEL_ONE),
                            SystemSetting::FIRST_RECHARGE_MODEL_ADD => admin_trans('first_recharge_setting.model.' . SystemSetting::FIRST_RECHARGE_MODEL_ADD),
                        ])->when(SystemSetting::FIRST_RECHARGE_MODEL_ADD, function (Form $form) {
                            $form->text('add_number', admin_trans('first_recharge_setting.fields.add_number'))
                                ->rule([
                                    'integer' => admin_trans('validator.integer'),
                                    'max:100000' => admin_trans('validator.max', null, ['{max}' => 100000000]),
                                    'min:1' => admin_trans('validator.min', null, ['{min}' => 1]),
                                ])
                                ->span(24)
                                ->required();
                        })->span(24);
                    $form->radio('type', admin_trans('first_recharge_setting.fields.type'))
                        ->button()
                        ->required()
                        ->default(SystemSetting::FIRST_RECHARGE_TYPE_VALUE)
                        ->bindAttr('buttonStyle', $form->getBindField('buttonStyle'))
                        ->options([
                            SystemSetting::FIRST_RECHARGE_TYPE_VALUE => admin_trans('first_recharge_setting.type.' . SystemSetting::FIRST_RECHARGE_TYPE_VALUE),
                            SystemSetting::FIRST_RECHARGE_TYPE_PERCENT => admin_trans('first_recharge_setting.type.' . SystemSetting::FIRST_RECHARGE_TYPE_PERCENT),
                        ])
                        ->when(SystemSetting::FIRST_RECHARGE_TYPE_VALUE, function (Form $form) {
                            $form->text('number', admin_trans('first_recharge_setting.fields.number'))
                                ->rule([
                                    'integer' => admin_trans('validator.integer'),
                                    'max:100000' => admin_trans('validator.max', null, ['{max}' => 100000000]),
                                    'min:1' => admin_trans('validator.min', null, ['{min}' => 1]),
                                ])
                                ->required()
                                ->span(24)
                                ->suffix('coin');
                        })
                        ->when(SystemSetting::FIRST_RECHARGE_TYPE_PERCENT, function (Form $form) {
                            $form->text('number', admin_trans('first_recharge_setting.fields.number_percent'))
                                ->rule([
                                    'integer' => admin_trans('validator.integer'),
                                    'max:100000' => admin_trans('validator.max', null, ['{max}' => 100000000]),
                                    'min:1' => admin_trans('validator.min', null, ['{min}' => 1]),
                                ])
                                ->required()
                                ->span(24)
                                ->suffix('%');
                        });
                    $form->number('chip_multiple', admin_trans('first_recharge_setting.fields.chip_amount'))
                        ->min(0)
                        ->max(100000000)
                        ->span(24)
                        ->style(['width' => '100%'])
                        ->required()
                        ->precision(2);
                })->class(['activity-phase-has-many']);
            })->sortField('sort')->defaultRow(1);
            $form->layout('vertical');
            $form->saving(function (Form $form) {
                $content = $form->input('content');
                $settingContent = [];
                foreach ($content as $item) {
                    $settingContent[] = [
                        'model' => $item['model'],
                        'type' => $item['type'],
                        'add_number' => $item['add_number'] ?? 0,
                        'chip_multiple' => $item['chip_multiple'],
                        'number' => $item['number'],
                    ];
                }
                if (!SystemSetting::updateOrCreate(
                    [
                        'department_id' => Admin::user()->department_id,
                        'feature' => 'first_recharge_setting',
                    ],
                    [
                        'content' => json_encode($settingContent)
                    ]
                )) {
                    return message_error(admin_trans('form.save_error'));
                }
                return message_success(admin_trans('form.save_success'));
            });
        });
    }

    /**
     * 在线充值
     * @group channel
     * @auth true
     */
    public function speedPayList(): Grid
    {
        return Grid::create(new $this->sepay_model(), function (Grid $grid) {
            $grid->autoHeight();
            $grid->bordered(true);
            $grid->tools([
                Button::create(admin_trans('channel_recharge_setting.manual_recharge_setting'))
                    ->danger()
                    ->drawer($this->methodForm()),
                Button::create(admin_trans('channel_recharge_setting.usdt_recharge_setting'))
                    ->danger()
                    ->drawer($this->form())
            ]);
            $grid->model()->where('department_id', Admin::user()->department_id)->orderBy('money');
            $grid->column('id', admin_trans('channel_recharge_setting.fields.id'))->align('center');
            $grid->column('title', admin_trans('channel_recharge_setting.fields.title'))->align('center');
            $grid->column('coins_num', admin_trans('channel_recharge_setting.fields.coins_num'))->align('center');
            $grid->column('first_coins', admin_trans('channel_recharge_setting.fields.first_coins'))->align('center');
            $grid->column('money', admin_trans('channel_recharge_setting.fields.money'))->align('center');
            $grid->column('admin_id', admin_trans('channel_recharge_setting.fields.user_name'))->display(function ($val) {
                return AdminUser::query()->find($val)->username;
            })
                ->align('center');
            $grid->column('status', admin_trans('channel_recharge_setting.fields.status'))->switch()->align('center');
            $grid->column('created_at', admin_trans('qrcode.qrcode_batch.created_at'))->align('center')->fixed(true);
            $grid->hideDelete();
            $grid->hideSelection();
            $grid->hideDeleteSelection();
            $grid->hideTrashed();
            $grid->addButton()->drawer($this->addSpeedPay());
            $grid->actions(function (Actions $actions) {
                $actions->hideEdit();
            });
        });
    }

    /**
     * 在线充值配置
     * @auth true
     * @group channel
     * @return Form
     */
    public function addSpeedPay(): Form
    {
        return Form::create(new $this->sepay_model(), function (Form $form) {
            $form->text('title', admin_trans('channel_recharge_setting.fields.title'))->maxlength(30)->required();
            $form->number('coins_num', admin_trans('channel_recharge_setting.fields.coins_num'))
                ->style(['width' => '100%'])
                ->min(1)
                ->max(100000000)
                ->precision(2)
                ->required()
                ->rule([
                    'required' => admin_trans('channel_recharge_setting.rul.coins_num'),
                    'min:1' => admin_trans('channel_recharge_setting.rul.coins_num_1'),
                    'max:100000000' => admin_trans('channel_recharge_setting.rul.coins_num_max_100000000'),
                ])
                ->placeholder(admin_trans('channel_recharge_setting.placeholder_coins_num'));
            $form->number('first_coins', admin_trans('channel_recharge_setting.fields.first_coins'))
                ->style(['width' => '100%'])
                ->min(0)
                ->max(100000000)
                ->precision(2)
                ->rule([
                    'required' => admin_trans('channel_recharge_setting.rul.first_coins'),
                    'min:0' => admin_trans('channel_recharge_setting.rul.gift_coins_1'),
                    'max:100000000' => admin_trans('channel_recharge_setting.rul.gift_coins_max_100000000'),
                ])
                ->placeholder(admin_trans('channel_recharge_setting.placeholder_coins_num'));
            $form->number('money', admin_trans('channel_recharge_setting.fields.money'))
                ->style(['width' => '100%'])
                ->min(5)
                ->max(20000)
                ->precision(2)
                ->required()
                ->placeholder(admin_trans('channel_recharge_setting.placeholder_money'));
            $form->layout('vertical');
            $form->saving(function (Form $form) {
                try {
                    $setting = new SepayRecharge();
                    $setting->department_id = Admin::user()->department_id;
                    $setting->title = $form->input('title');
                    $setting->coins_num = $form->input('coins_num');
                    $setting->first_coins = $form->input('first_coins');
                    $setting->money = $form->input('money');
                    $setting->admin_id = Admin::id();
                    $setting->save();
                } catch (\Exception $exception) {
                    return message_error(admin_trans('form.save_error'));
                }
                return message_success(admin_trans('form.save_success'));
            });
        });
    }

}
