<?php

namespace addons\webman\controller;

use addons\webman\Admin;
use addons\webman\model\Channel;
use addons\webman\model\ChannelFinancialRecord;
use addons\webman\model\Notice;
use addons\webman\model\PlayerRechargeRecord;
use addons\webman\model\PlayerWithdrawRecord;
use app\service\OnePayServices;
use app\service\SePayServices;
use app\service\SklPayServices;
use ExAdmin\ui\component\common\Button;
use ExAdmin\ui\component\common\Html;
use ExAdmin\ui\component\common\Icon;
use ExAdmin\ui\component\form\Form;
use ExAdmin\ui\component\grid\avatar\Avatar;
use ExAdmin\ui\component\grid\badge\Badge;
use ExAdmin\ui\component\grid\card\Card;
use ExAdmin\ui\component\grid\grid\Actions;
use ExAdmin\ui\component\grid\grid\Editable;
use ExAdmin\ui\component\grid\grid\Filter;
use ExAdmin\ui\component\grid\grid\Grid;
use ExAdmin\ui\component\grid\image\Image;
use ExAdmin\ui\component\grid\statistic\Statistic;
use ExAdmin\ui\component\grid\tag\Tag;
use ExAdmin\ui\component\grid\ToolTip;
use ExAdmin\ui\component\layout\layout\Layout;
use ExAdmin\ui\component\layout\Row;
use ExAdmin\ui\component\navigation\dropdown\Dropdown;
use ExAdmin\ui\response\Msg;
use ExAdmin\ui\support\Request;
use Illuminate\Support\Str;

/**
 * 提现记录
 * @group channel
 */
class ChannelWithdrawRecordController
{
    protected $model;
    protected $rechargeModel;

    public function __construct()
    {
        $this->model = plugin()->webman->config('database.player_withdraw_record_model');
        $this->rechargeModel = plugin()->webman->config('database.player_recharge_record_model');
    }

    /**
     * 提现审核
     * @group channel
     * @auth true
     */
    public function examineList(): Grid
    {
        return Grid::create(new $this->model(), function (Grid $grid) {
            $grid->title(admin_trans('player_withdraw_record.examine_title'));
            $grid->bordered(true);
            $grid->autoHeight();
            $tradeno = Request::input('tradeno', []);
            if (!empty($tradeno)) {
                $grid->model()->where('tradeno', $tradeno);
            }
            $grid->model()->with(['player'])
                ->where('type', PlayerWithdrawRecord::TYPE_SELF)
                ->orWhere('status',PlayerWithdrawRecord::STATUS_WAIT)
                ->orderBy('created_at', 'desc')
                ->orderBy('status', 'asc');
            $exAdminFilter = Request::input('ex_admin_filter', []);
            if (!empty($exAdminFilter)) {
                if (isset($exAdminFilter['created_at_start']) && !empty($exAdminFilter['created_at_start'])) {
                    $grid->model()->where('created_at', '>=', $exAdminFilter['created_at_start']);
                }
                if (isset($exAdminFilter['created_at_end']) && !empty($exAdminFilter['created_at_end'])) {
                    $grid->model()->where('created_at', '<=', $exAdminFilter['created_at_end']);
                }
            }
            $grid->column('id', admin_trans('player_withdraw_record.fields.id'))->align('center');
            $grid->column('tradeno', admin_trans('player_withdraw_record.fields.tradeno'))->copy();
            $grid->column('player.uuid', admin_trans('player.fields.uuid'))->copy();
            $grid->column('player.name', admin_trans('player_withdraw_record.fields.player'))->display(function ($val, PlayerWithdrawRecord $data) {
                if (!empty($data->player)) {
                    $image = isset($data->player->avatar) && !empty($data->player->avatar) ? Avatar::create()->src($data->player->avatar) : Avatar::create()->icon(Icon::create('UserOutlined'));
                    return Html::create()->content([
                        $image,
                        Html::div()->content($val)
                    ]);
                }
                return '';
            })->align('center');
            $grid->column('money', admin_trans('player_withdraw_record.fields.money'))->display(function ($val, PlayerWithdrawRecord $data) {
                return bcdiv($val,$data->rate, 2) . ' ' . ($data->currency == 'TALK' ? 'Q币' : $data->currency);
            })->align('center');
            $grid->column('coins', admin_trans('player_withdraw_record.fields.coins'))->align('center');
            $grid->column('type', admin_trans('player_withdraw_record.fields.type'))->display(function ($val) {
                switch ($val) {
                    case PlayerWithdrawRecord::TYPE_SELF:
                        return Tag::create(admin_trans('player_withdraw_record.type.' . $val))
                            ->color('#3b5999');
                    default:
                        return '';
                }
            })->align('center');
            $grid->column('withdraw_setting_info',
                admin_trans('player_withdraw_record.player_bank'))->display(function (
                $val,
                PlayerWithdrawRecord $data
            ) {
                $info = [];
                switch ($data->type) {
                    case PlayerWithdrawRecord::TYPE_USDT:
                        $info[] = Html::markdown('- ' . admin_trans('channel_recharge_setting.fields.wallet_address') . ': ' . $data->wallet_address);
                        $info[] = Html::div()->content(Image::create()
                            ->width(40)
                            ->src($data->qr_code));
                        break;
                    case PlayerWithdrawRecord::TYPE_SELF:
                        $info[] = Html::markdown('- ' . admin_trans('player_withdraw_record.fields.account_name') . ': ' . $data->account_name);
                        $info[] = Html::markdown('- ' . admin_trans('player_withdraw_record.fields.bank_name') . ': ' . $data->bank_name);
                        $info[] = Html::markdown('- ' . admin_trans('player_withdraw_record.fields.account') . ': ' . $data->account);
                        break;
                }
                return Html::create()->content($info);
            })->align('left');
            $grid->column('status', admin_trans('player_withdraw_record.fields.status'))
                ->display(function ($value, PlayerWithdrawRecord $data) {
                    $rejectReason = $data->reject_reason;
                    switch ($value) {
                        case PlayerWithdrawRecord::STATUS_SUCCESS:
                            $tag = Tag::create(admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_SUCCESS))->color('#87d068');
                            break;
                        case PlayerWithdrawRecord::STATUS_WAIT:
                            $tag = Tag::create(admin_trans('player_withdraw_record.status_wait'))->color('#108ee9');
                            break;
                        case PlayerWithdrawRecord::STATUS_FAIL:
                            $tag = Tag::create(admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_FAIL))->color('#f50');
                            break;
                        case PlayerWithdrawRecord::STATUS_PENDING_REJECT:
                            $tag = Tag::create(admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_PENDING_REJECT))->color('#cd201f');
                            break;
                        case PlayerWithdrawRecord::STATUS_PENDING_PAYMENT:
                            $tag = Tag::create(admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_PENDING_PAYMENT))->color('#3b5999');
                            break;
                        case PlayerWithdrawRecord::STATUS_CANCEL:
                        case PlayerWithdrawRecord::STATUS_SYSTEM_CANCEL:
                            $tag = Tag::create(admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_CANCEL))->color('#2db7f5');
                            break;
                        default:
                            $tag = '';
                    }
                    if (!empty($rejectReason)) {
                        return ToolTip::create(Badge::create(
                            $tag
                        )->count('!')->title(''))->title($rejectReason)->color('orange');
                    } else {
                        return $tag;
                    }
                })->align('center')->sortable();
            $grid->column('created_at', admin_trans('player_withdraw_record.fields.created_at'))->sortable()->align('center');
            $grid->column('remark', admin_trans('player_withdraw_record.fields.remark'))->display(function ($value) {
                return Str::of($value)->limit(20, ' (...)');
            })->editable(
                (new Editable)->textarea('remark')
                    ->showCount()
                    ->rows(5)
                    ->rule(['max:255' => admin_trans('player_withdraw_record.fields.remark')])
            )->width('150px')->align('center');
            $grid->hideDelete();
            $grid->hideSelection();
            $grid->expandFilter();
            $grid->actions(function (Actions $actions, PlayerWithdrawRecord $data) {
                $actions->hideDel();
                $actions->hideEdit();
                $dropdown = Dropdown::create(
                    Button::create([
                        admin_trans('player_withdraw_record.btn.action'), Icon::create('DownOutlined')->style(['marginRight' => '5px'])
                    ]))->trigger(['click']);

                $dropdown->item(admin_trans('player_withdraw_record.btn.view_channel_recharge_list'), 'AppstoreAddOutlined')
                    ->modal($this->viewRechargeList($data->player_id))->width('70%');

                $dropdown->item(admin_trans('player_withdraw_record.btn.examine_pass'), 'SafetyCertificateOutlined')
                    ->confirm(admin_trans('player_withdraw_record.btn.examine_pass_confirm'), [$this, 'pass'], ['id' => $data->id])->gridRefresh();

                $dropdown->item(admin_trans('player_withdraw_record.btn.examine_reject'), 'WarningFilled')
                    ->modal([$this, 'reject'], ['id' => $data->id]);
                $actions->prepend(
                    $dropdown
                );
            });
            $grid->filter(function (Filter $filter) {
                $filter->like()->text('player.uuid')->placeholder(admin_trans('player.fields.uuid'));
                $filter->like()->text('player.name')->placeholder(admin_trans('player.fields.name'));
                $filter->eq()->select('status')
                    ->showSearch()
                    ->style(['width' => '200px'])
                    ->dropdownMatchSelectWidth()
                    ->placeholder(admin_trans('player_withdraw_record.fields.status'))
                    ->options([
                        PlayerWithdrawRecord::STATUS_WAIT => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_WAIT),
                        PlayerWithdrawRecord::STATUS_SUCCESS => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_SUCCESS),
                        PlayerWithdrawRecord::STATUS_FAIL => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_FAIL),
                        PlayerWithdrawRecord::STATUS_PENDING_PAYMENT => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_PENDING_PAYMENT),
                        PlayerWithdrawRecord::STATUS_PENDING_REJECT => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_PENDING_REJECT),
                        PlayerWithdrawRecord::STATUS_CANCEL => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_CANCEL),
                        PlayerWithdrawRecord::STATUS_SYSTEM_CANCEL => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_SYSTEM_CANCEL),
                    ]);
                $filter->like()->text('tradeno')->placeholder(admin_trans('player_withdraw_record.fields.tradeno'));
                $filter->eq()->number('money')->precision(2)->style(['width' => '150px'])->placeholder(admin_trans('player_withdraw_record.fields.money'));
                $filter->form()->hidden('created_at_start');
                $filter->form()->hidden('created_at_end');
                $filter->form()->dateTimeRange('created_at_start', 'created_at_end', '')->placeholder([admin_trans('player_withdraw_record.fields.created_at'), admin_trans('player_withdraw_record.fields.created_at')]);
            });
        });
    }

    /**
     * 提现打款
     * @group channel
     * @auth true
     */
    public function paymentList(): Grid
    {
        return Grid::create(new $this->model(), function (Grid $grid) {
            $grid->title(admin_trans('player_withdraw_record.payment_title'));
            $grid->bordered(true);
            $grid->autoHeight();
            $grid->model()->with(['player'])
                ->Where('status', PlayerWithdrawRecord::STATUS_PENDING_PAYMENT)
                ->orderBy('created_at', 'desc');
            $exAdminFilter = Request::input('ex_admin_filter', []);
            if (!empty($exAdminFilter)) {
                if (isset($exAdminFilter['created_at_start']) && !empty($exAdminFilter['created_at_start'])) {
                    $grid->model()->where('created_at', '>=', $exAdminFilter['created_at_start']);
                }
                if (isset($exAdminFilter['created_at_end']) && !empty($exAdminFilter['created_at_end'])) {
                    $grid->model()->where('created_at', '<=', $exAdminFilter['created_at_end']);
                }
            }
            $grid->column('id', admin_trans('player_withdraw_record.fields.id'))->align('center');
            $grid->column('tradeno', admin_trans('player_withdraw_record.fields.tradeno'))->copy();
            $grid->column('player.uuid', admin_trans('player.fields.uuid'))->copy();
            $grid->column('player.name', admin_trans('player_withdraw_record.fields.player'))->display(function ($val, PlayerWithdrawRecord $data) {
                if (!empty($data->player)) {
                    $image = isset($data->player->avatar) && !empty($data->player->avatar) ? Avatar::create()->src($data->player->avatar) : Avatar::create()->icon(Icon::create('UserOutlined'));
                    return Html::create()->content([
                        $image,
                        Html::div()->content($val)
                    ]);
                }
                return '';
            })->align('center');
            $grid->column('money', admin_trans('player_withdraw_record.fields.money'))->display(function ($val, PlayerWithdrawRecord $data) {
                return bcdiv($val,$data->rate, 2) . ' ' . ( $data->currency);
            })->align('center')->sortable();
            $grid->column('coins', admin_trans('player_withdraw_record.fields.coins'))->align('center');
            $grid->column('type', admin_trans('player_withdraw_record.fields.type'))->display(function ($val) {
                return Tag::create(admin_trans('player_withdraw_record.type.' . $val))
                    ->color('#3b5999');
            })->align('center');
            $grid->column('withdraw_setting_info',
                admin_trans('player_withdraw_record.player_bank'))->display(function (
                $val,
                PlayerWithdrawRecord $data
            ) {
                $info = [];
                switch ($data->type) {
                    case PlayerWithdrawRecord::TYPE_USDT:
                        $info[] = Html::markdown('- ' . admin_trans('channel_recharge_setting.fields.wallet_address') . ': ' . $data->wallet_address);
                        $info[] = Html::div()->content(Image::create()
                            ->width(40)
                            ->src($data->qr_code));
                        break;
                    case PlayerWithdrawRecord::TYPE_SELF:
                        $info[] = Html::markdown('- ' . admin_trans('player_withdraw_record.fields.account_name') . ': ' . $data->account_name);
                        $info[] = Html::markdown('- ' . admin_trans('player_withdraw_record.fields.bank_name') . ': ' . $data->bank_name);
                        $info[] = Html::markdown('- ' . admin_trans('player_withdraw_record.fields.account') . ': ' . $data->account);
                        break;
                }
                return Html::create()->content($info);
            })->align('left');
            $grid->column('status', admin_trans('player_withdraw_record.fields.status'))
                ->display(function () {
                    return Html::create()->content([
                        Tag::create(admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_PENDING_PAYMENT))->color('#3b5999')
                    ]);
                })->sortable();
            $grid->column('created_at', admin_trans('player_withdraw_record.fields.created_at'))->sortable()->align('center');
            $grid->column('remark', admin_trans('player_withdraw_record.fields.remark'))->display(function ($value) {
                return Str::of($value)->limit(20, ' (...)');
            })->tip()->width('150px')->align('center');
            $grid->hideDelete();
            $grid->hideSelection();
            $grid->expandFilter();
            $grid->actions(function (Actions $actions, PlayerWithdrawRecord $data) {
                $actions->hideDel();
                $actions->hideEdit();
                $actions->prepend(
                    Button::create(admin_trans('player_withdraw_record.btn.complete_payment'))
                        ->type('danger')
                        ->modal($this->payment($data->id))
                );
            });
            $grid->filter(function (Filter $filter) {
                $filter->like()->text('player.uuid')->placeholder(admin_trans('player.fields.uuid'));
                $filter->like()->text('player.name')->placeholder(admin_trans('player.fields.name'));
                $filter->like()->text('tradeno')->placeholder(admin_trans('player_withdraw_record.fields.tradeno'));
                $filter->eq()->number('money')->precision(2)->style(['width' => '150px'])->placeholder(admin_trans('player_withdraw_record.fields.money'));
                $filter->form()->hidden('created_at_start');
                $filter->form()->hidden('created_at_end');
                $filter->form()->dateTimeRange('created_at_start', 'created_at_end', '')->placeholder([admin_trans('player_withdraw_record.fields.created_at'), admin_trans('player_withdraw_record.fields.created_at')]);
            });
        });
    }

    /**
     * 提交打款凭证
     * @auth true
     * @group channel
     * @param $id
     * @return Form
     */
    public function payment($id): Form
    {
        return Form::create(new $this->model(), function (Form $form) use ($id) {
            $form->file('certificate')
                ->ext('jpg,png,jpeg')
                ->type('image')
                ->fileSize('2m')
                ->hideFinder()
                ->paste()
                ->style(['margin-left' => '35%', 'margin-bottom' => '16px'])
                ->help(Html::create()->content(admin_trans('player_withdraw_record.certificate_help'))->style([
                    'margin-left' => '135px',
                    'display' => 'block',
                    'width' => '235px'
                ]));
            $form->saving(function (Form $form) use ($id) {
                if (empty($form->input('certificate'))) {
                    return message_warning(admin_trans('player_withdraw_record.certificate_required'));
                }
                /** @var PlayerWithdrawRecord $playerWithdrawRecord */
                $playerWithdrawRecord = $this->model::find($id);
                if (empty($playerWithdrawRecord)) {
                    return message_error(admin_trans('player_withdraw_record.not_fount'));
                }
                switch ($playerWithdrawRecord->status) {
                    case PlayerWithdrawRecord::STATUS_WAIT:
                        return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_not_examine'));
                    case PlayerWithdrawRecord::STATUS_SUCCESS:
                        return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_complete'));
                    case PlayerWithdrawRecord::STATUS_FAIL:
                        return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_fail'));
                    case PlayerWithdrawRecord::STATUS_CANCEL:
                        return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_cancel'));
                    case PlayerWithdrawRecord::STATUS_PENDING_REJECT:
                        return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_reject'));
                    case PlayerWithdrawRecord::STATUS_SYSTEM_CANCEL:
                        return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_system_cancel'));
                }
                if ($playerWithdrawRecord->status != PlayerWithdrawRecord::STATUS_PENDING_PAYMENT) {
                    return message_error(admin_trans('player_withdraw_record.withdraw_record_status_error'));
                }
                /** @var Channel $channel */
                $channel = Channel::where('department_id', Admin::user()->department_id)->first();
                if (empty($channel)) {
                    return message_error(admin_trans('channel.not_fount'));
                }
                try {
                    // 更新订单
                    $playerWithdrawRecord->certificate = $form->input('certificate');
                    $playerWithdrawRecord->status = PlayerWithdrawRecord::STATUS_SUCCESS;
                    $playerWithdrawRecord->finish_time = date('Y-m-d H:i:s');
                    if ($playerWithdrawRecord->save()) {
                        saveChannelFinancialRecord($playerWithdrawRecord, ChannelFinancialRecord::ACTION_WITHDRAW_PAYMENT);
                        // 更新渠道数据
                        $channel->withdraw_amount = bcadd($channel->withdraw_amount, $playerWithdrawRecord->coins, 2);
                        $channel->save();
                    }
                } catch (\Exception $e) {
                    return message_error(admin_trans('player_recharge_record.action_error'));
                }

                return message_success(admin_trans('player_withdraw_record.action_success'));
            });
        });
    }

    /**
     * 查看充值
     * @group channel
     * @auth true
     */
    public function viewRechargeList($playerId): Grid
    {
        return Grid::create(new $this->rechargeModel(), function (Grid $grid) use ($playerId) {
            $grid->title(admin_trans('player_recharge_record.title'));
            $grid->model()->where('status', PlayerRechargeRecord::STATUS_RECHARGED_SUCCESS)->where('player_id', $playerId)->orderBy('created_at', 'desc');
            $exAdminFilter = Request::input('ex_admin_filter', []);
            if (!empty($exAdminFilter)) {
                if (isset($exAdminFilter['created_at_start']) && !empty($exAdminFilter['created_at_start'])) {
                    $grid->model()->where('created_at', '>=', $exAdminFilter['created_at_start']);
                }
                if (isset($exAdminFilter['created_at_end']) && !empty($exAdminFilter['created_at_end'])) {
                    $grid->model()->where('created_at', '<=', $exAdminFilter['created_at_end']);
                }
                if (isset($exAdminFilter['finish_time_start']) && !empty($exAdminFilter['finish_time_start'])) {
                    $grid->model()->where('finish_time', '>=', $exAdminFilter['finish_time_start']);
                }
                if (isset($exAdminFilter['finish_time_end']) && !empty($exAdminFilter['finish_time_end'])) {
                    $grid->model()->where('finish_time', '<=', $exAdminFilter['finish_time_end']);
                }
            }
            $grid->column('tradeno', admin_trans('player_recharge_record.fields.tradeno'))->align('center');
            $grid->column('player.uuid', admin_trans('player.fields.uuid'))->align('center');
            $grid->column('player.name', admin_trans('player_recharge_record.fields.player'))->display(function ($val, PlayerRechargeRecord $data) {
                if (!empty($data->player)) {
                    $image = isset($data->player->avatar) && !empty($data->player->avatar) ? Avatar::create()->src($data->player->avatar) : Avatar::create()->icon(Icon::create('UserOutlined'));
                    return Html::create()->content([
                        $image,
                        Html::div()->content($val)
                    ]);
                }
                return '';
            })->align('center');
            $grid->column('money', admin_trans('player_recharge_record.fields.money'))->display(function ($val, PlayerRechargeRecord $data) {
                return $val . ' ' . ($data->currency == 'TALK' ? admin_trans('player_recharge_record.talk_currency') : $data->currency);
            })->align('center');
            $grid->column('coins', admin_trans('player_recharge_record.fields.coins'))->align('center');
            $grid->column('status', admin_trans('player_recharge_record.fields.status'))->display(function ($val) {
                switch ($val) {
                    case PlayerRechargeRecord::STATUS_WAIT:
                        return Tag::create(admin_trans('player_recharge_record.status.' . $val))
                            ->color('#108ee9');
                    case PlayerRechargeRecord::STATUS_RECHARGING:
                        return Tag::create(admin_trans('player_recharge_record.status.' . $val))
                            ->color('#3b5999');
                    case PlayerRechargeRecord::STATUS_RECHARGED_SUCCESS:
                        return Tag::create(admin_trans('player_recharge_record.status.' . $val))
                            ->color('#87d068');
                    case PlayerRechargeRecord::STATUS_RECHARGED_FAIL:
                        return Tag::create(admin_trans('player_recharge_record.status.' . $val))
                            ->color('#f50');
                    case PlayerRechargeRecord::STATUS_RECHARGED_CANCEL:
                        return Tag::create(admin_trans('player_recharge_record.status.' . $val))
                            ->color('#2db7f5');
                    default:
                        return '';
                }
            })->align('center');
            $grid->column('remark', admin_trans('player_recharge_record.fields.remark'))->display(function ($value) {
                return Str::of($value)->limit(20, ' (...)');
            })->editable(
                (new Editable)->textarea('remark')
                    ->showCount()
                    ->rows(5)
                    ->rule(['max:255' => admin_trans('player_recharge_record.fields.remark')])
            )->width('150px')->align('center');
            $grid->column('user_name', admin_trans('player_recharge_record.fields.user_name'))->align('center');
            $grid->column('finish_time', admin_trans('player_recharge_record.fields.finish_time'))->sortable()->align('center');
            $grid->column('created_at', admin_trans('player_recharge_record.fields.created_at'))->sortable()->align('center');
            $grid->hideDelete();
            $grid->hideSelection();
            $grid->actions(function (Actions $actions) {
                $actions->hideDel();
                $actions->hideEdit();
            });
            $grid->filter(function (Filter $filter) {
                $filter->like()->text('tradeno')->placeholder(admin_trans('player_recharge_record.fields.tradeno'));
                $filter->eq()->number('money')->precision(2)->style(['width' => '150px'])->placeholder(admin_trans('player_recharge_record.fields.money'));
                $filter->form()->hidden('created_at_start');
                $filter->form()->hidden('created_at_end');
                $filter->form()->dateTimeRange('created_at_start', 'created_at_end', '')->placeholder([admin_trans('public_msg.created_at_start'), admin_trans('public_msg.created_at_end')]);
                $filter->form()->hidden('finish_time_start');
                $filter->form()->hidden('finish_time_end');
                $filter->form()->dateTimeRange('finish_time_start', 'finish_time_end', '')->placeholder([admin_trans('player_recharge_record.fields.finish_time'), admin_trans('player_recharge_record.fields.finish_time')]);
            });
            $grid->expandFilter();
        });
    }

    /**
     * 提现订单审核拒绝
     * @auth true
     * @group channel
     * @param $id
     * @return Form
     */
    public function reject($id): Form
    {
        return Form::create(new $this->model(), function (Form $form) use ($id) {
            $form->textarea('reject_reason')->rows(5)->required();
            $form->saving(function (Form $form) use ($id) {
                /** @var PlayerWithdrawRecord $playerWithdrawRecord */
                $playerWithdrawRecord = $this->model::find($id);
                if (empty($playerWithdrawRecord)) {
                    return message_error(admin_trans('player_withdraw_record.not_fount'));
                }
                switch ($playerWithdrawRecord->status) {
                    case PlayerWithdrawRecord::STATUS_SUCCESS:
                        return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_complete'));
                    case PlayerWithdrawRecord::STATUS_FAIL:
                        return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_fail'));
                    case PlayerWithdrawRecord::STATUS_CANCEL:
                        return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_cancel'));
                    case PlayerWithdrawRecord::STATUS_PENDING_REJECT:
                        return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_reject'));
                    case PlayerWithdrawRecord::STATUS_SYSTEM_CANCEL:
                        return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_system_cancel'));
                    case PlayerWithdrawRecord::STATUS_PENDING_PAYMENT:
                        return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_pass'));
                }
                if ($playerWithdrawRecord->status != PlayerWithdrawRecord::STATUS_WAIT) {
                    return message_error(admin_trans('player_withdraw_record.withdraw_record_status_error'));
                }
                try {
                    if (withdrawBack($playerWithdrawRecord, $form->input('reject_reason'))) {
                        saveChannelFinancialRecord($playerWithdrawRecord, ChannelFinancialRecord::ACTION_WITHDRAW_REJECT);
                    }
                } catch (\Exception $e) {
                    return message_error(admin_trans('player_withdraw_record.action_error'));
                }
                return message_success(admin_trans('player_withdraw_record.action_success'));
            });
        });
    }

    /**
     * 提现订单审核通过
     * @param $id
     * @auth true
     * @group channel
     * @return Msg
     */
    public function pass($id): Msg
    {
        /** @var PlayerWithdrawRecord $playerWithdrawRecord */
        $playerWithdrawRecord = $this->model::find($id);
        if (empty($playerWithdrawRecord)) {
            return message_error(admin_trans('player_withdraw_record.not_fount'));
        }

        switch ($playerWithdrawRecord->status) {
            case PlayerWithdrawRecord::STATUS_SUCCESS:
                return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_complete'));
            case PlayerWithdrawRecord::STATUS_FAIL:
                return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_fail'));
            case PlayerWithdrawRecord::STATUS_CANCEL:
                return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_cancel'));
            case PlayerWithdrawRecord::STATUS_PENDING_REJECT:
                return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_reject'));
            case PlayerWithdrawRecord::STATUS_SYSTEM_CANCEL:
                return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_system_cancel'));
            case PlayerWithdrawRecord::STATUS_PENDING_PAYMENT:
                return message_warning(admin_trans('player_withdraw_record.withdraw_record_has_pass'));
        }
        if ($playerWithdrawRecord->status != PlayerWithdrawRecord::STATUS_WAIT) {
            return message_error(admin_trans('player_withdraw_record.withdraw_record_status_error'));
        }
        try {
            if ($playerWithdrawRecord->type == PlayerWithdrawRecord::TYPE_SKLPAYOUT) {
                $params = [
                    'amount' => $playerWithdrawRecord->coins,
                    'bankCode' => $playerWithdrawRecord->bank_code,
                    'bankAccountNo' => $playerWithdrawRecord->account,
                    'bankAccountName' => $playerWithdrawRecord->account_name,
                    'orderNo' => $playerWithdrawRecord->tradeno,
                ];
                $res = (new SklPayServices())->payout($params);
                if ($res['code'] == 'success') {
                    // 更新订单
                    $playerWithdrawRecord->user_id = Admin::id() ?? 0;
                    $playerWithdrawRecord->user_name = !empty(Admin::user()) ? Admin::user()->username : '';
                    $notice = new Notice();
                    $notice->department_id = $playerWithdrawRecord->player->department_id;
                    $notice->player_id = $playerWithdrawRecord->player_id;
                    $notice->source_id = $playerWithdrawRecord->id;
                    $notice->type = Notice::TYPE_WITHDRAW;
                    $notice->receiver = Notice::RECEIVER_PLAYER;
                    $notice->is_private = 1;
                    $notice->title = '下分成功';
                    $notice->content = '本次申请已成功处理，下分 ' . $playerWithdrawRecord->money . ' ，请查收。 ';
                    $notice->save();
                    if ($playerWithdrawRecord->save()) {
                        saveChannelFinancialRecord($playerWithdrawRecord, ChannelFinancialRecord::ACTION_WITHDRAW_PASS);
                    }
                } else {
                    return message_error($res['message']);
                }
            } elseif (in_array($playerWithdrawRecord->type, [PlayerWithdrawRecord::TYPE_SELF, PlayerWithdrawRecord::TYPE_USDT])) {
                $playerWithdrawRecord->status = PlayerWithdrawRecord::STATUS_PENDING_PAYMENT;
                $playerWithdrawRecord->user_id = Admin::id() ?? 0;
                $playerWithdrawRecord->user_name = !empty(Admin::user()) ? Admin::user()->username : '';
                if ($playerWithdrawRecord->save()) {
                    saveChannelFinancialRecord($playerWithdrawRecord, ChannelFinancialRecord::ACTION_WITHDRAW_PASS);
                }
            }

        } catch (\Exception $e) {
            return message_error(admin_trans('player_withdraw_record.action_error'));
        }
        return message_success(admin_trans('player_withdraw_record.action_success'));
    }

    /**
     * 提现
     * @group channel
     * @auth true
     */
    public function index(): Grid
    {
        return Grid::create(new $this->model(), function (Grid $grid) {
            $grid->title(admin_trans('player_withdraw_record.payment_title'));
            $grid->model()->with(['player'])->orderBy('created_at', 'desc');
            $exAdminFilter = Request::input('ex_admin_filter', []);
            if (!empty($exAdminFilter)) {
                if (isset($exAdminFilter['created_at_start']) && !empty($exAdminFilter['created_at_start'])) {
                    $grid->model()->where('created_at', '>=', $exAdminFilter['created_at_start']);
                }
                if (isset($exAdminFilter['created_at_end']) && !empty($exAdminFilter['created_at_end'])) {
                    $grid->model()->where('created_at', '<=', $exAdminFilter['created_at_end']);
                }
                if (isset($exAdminFilter['finish_time_start']) && !empty($exAdminFilter['finish_time_start'])) {
                    $grid->model()->where('finish_time', '>=', $exAdminFilter['finish_time_start']);
                }
                if (isset($exAdminFilter['finish_time_end']) && !empty($exAdminFilter['finish_time_end'])) {
                    $grid->model()->where('finish_time', '<=', $exAdminFilter['finish_time_end']);
                }
                if (!empty($exAdminFilter['player']['uuid'])) {
                    $grid->model()->whereHas('player', function ($query) use ($exAdminFilter) {
                        $query->where('uuid', 'like', '%' . $exAdminFilter['player']['uuid'] . '%');
                    });
                }
                if (!empty($exAdminFilter['player']['name'])) {
                    $grid->model()->whereHas('player', function ($query) use ($exAdminFilter) {
                        $query->where('name', 'like', '%' . $exAdminFilter['player']['name'] . '%');
                    });
                }
                if (!empty($exAdminFilter['type'])) {
                    $grid->model()->where('type', $exAdminFilter['type']);
                }
                if (!empty($exAdminFilter['status'])) {
                    $grid->model()->where('status', $exAdminFilter['status']);
                }
                if (!empty($exAdminFilter['tradeno'])) {
                    $grid->model()->where('tradeno', $exAdminFilter['tradeno']);
                }
            }
            $query = clone $grid->model();
            $totalData = $query->selectRaw(
                'ifNull(sum(money), 0) as total_money,
                           ifNull(sum(IF(type = 6, money,0)), 0) as total_skl_money'
            )->first();
            $layout = Layout::create();
            $layout->row(function (Row $row) use ($totalData) {
                $row->gutter([10, 0]);
                $row->column(
                    Card::create([
                        Row::create()->column(Statistic::create()->title(admin_trans('player_withdraw_record.total_money'))
                            ->value($totalData['total_money'])
                            ->style([
                                'font-size' => '15px',
                                'text-align' => 'center'
                            ])),
                    ])->bodyStyle([
                        'display' => 'flex',
                        'align-items' => 'center',
                        'height' => '72px'
                    ])->hoverable()->headStyle(['height' => '0px', 'border-bottom' => '0px', 'min-height' => '0px'])
                    , 8);
                $row->column(
                    Card::create([
                        Row::create()->column(Statistic::create()->title(admin_trans('player_withdraw_record.total_inmoney'))
                            ->value(bcadd(bcsub($totalData['total_money'], $totalData['total_skl_money'], 3), bcmul($totalData['total_skl_money'], 1.008, 3), 3))
                            ->style([
                                'font-size' => '15px',
                                'text-align' => 'center'
                            ])),
                    ])->bodyStyle([
                        'display' => 'flex',
                        'align-items' => 'center',
                        'height' => '72px'
                    ])->hoverable()->headStyle(['height' => '0px', 'border-bottom' => '0px', 'min-height' => '0px'])
                    , 8);
            })->style(['background' => '#fff']);
            $grid->header($layout);
            $grid->bordered(true);
            $grid->autoHeight();
            $grid->column('id', admin_trans('player_withdraw_record.fields.id'))->align('center')->fixed(true);
            $grid->column('tradeno', admin_trans('player_withdraw_record.fields.tradeno'))->copy()->fixed(true);
            $grid->column('player.uuid', admin_trans('player.fields.uuid'))->copy()->fixed(true);
            $grid->column('player.name', admin_trans('player_withdraw_record.fields.player'))->display(function ($val, PlayerWithdrawRecord $data) {
                if (!empty($data->player)) {
                    $image = isset($data->player->avatar) && !empty($data->player->avatar) ? Avatar::create()->src($data->player->avatar) : Avatar::create()->icon(Icon::create('UserOutlined'));
                    return Html::create()->content([
                        $image,
                        Html::div()->content($val)
                    ]);
                }
                return '';
            })->align('center');
            $grid->column('money', admin_trans('player_withdraw_record.fields.money'))->display(function ($val, PlayerWithdrawRecord $data) {
                return bcdiv($val,$data->rate, 2) . ' ' . ($data->currency == 'TALK' ? 'Q币' : $data->currency);
            })->align('center')->sortable();
            $grid->column('inmoney', admin_trans('player_recharge_record.fields.inmoney'))->display(function ($val, PlayerWithdrawRecord $data) {
                if ($data->type == PlayerWithdrawRecord::TYPE_ESPAYOUT) {
                    $ratio = 1.005;
                } elseif ($data->type == PlayerWithdrawRecord::TYPE_ONEPAYOUT){
                    $ratio = 1.008;
                } elseif ($data->type == PlayerWithdrawRecord::TYPE_SKLPAYOUT){
                    $ratio = 1.008;
                } else {
                    $ratio = 1;
                }
                if ($data->currency == 'USDT') {
                    return bcdiv($val,$data->rate, 2) . ' ' . ($data->currency);
                }
                return $data->money * $ratio . ' ' . ($data->currency);
            })->align('center');
            $grid->column('coins', admin_trans('player_withdraw_record.fields.coins'))->align('center');
            $grid->column('type', admin_trans('player_withdraw_record.fields.type'))->display(function ($val) {
                switch ($val) {
                    case PlayerWithdrawRecord::TYPE_SELF:
                        return Tag::create(admin_trans('player_withdraw_record.type.' . $val))
                            ->color('#3b5999');
                    case PlayerWithdrawRecord::TYPE_ARTIFICIAL:
                        return Tag::create(admin_trans('player_withdraw_record.type.' . $val))
                            ->color('#cd201f');
                    case PlayerWithdrawRecord::TYPE_USDT:
                        return Tag::create(admin_trans('player_withdraw_record.type.' . $val))
                            ->color('#2db7f5');
                    case PlayerWithdrawRecord::TYPE_SKLPAYOUT:
                        return Tag::create(admin_trans('player_withdraw_record.type.' . $val))
                            ->color('#108ee9');
                    default:
                        return '';
                }
            })->align('center');
            $grid->column('withdraw_setting_info',
                admin_trans('player_withdraw_record.player_bank'))->display(function (
                $val,
                PlayerWithdrawRecord $data
            ) {
                $info = [];
                switch ($data->type) {
                    case PlayerWithdrawRecord::TYPE_USDT:
                        $info[] = Html::markdown('- ' . admin_trans('channel_recharge_setting.fields.wallet_address') . ': ' . $data->wallet_address);
                        $info[] = Html::div()->content(Image::create()
                            ->width(40)
                            ->src($data->qr_code));
                        break;
                    case PlayerWithdrawRecord::TYPE_SELF:
                        $info[] = Html::markdown('- ' . admin_trans('player_withdraw_record.fields.account_name') . ': ' . $data->account_name);
                        $info[] = Html::markdown('- ' . admin_trans('player_withdraw_record.fields.bank_name') . ': ' . $data->bank_name);
                        $info[] = Html::markdown('- ' . admin_trans('player_withdraw_record.fields.account') . ': ' . $data->account);
                        break;
                }
                return Html::create()->content($info);
            })->align('left');
            $grid->column('status', admin_trans('player_withdraw_record.fields.status'))
                ->display(function ($value, PlayerWithdrawRecord $data) {
                    $rejectReason = $data->reject_reason;
                    switch ($value) {
                        case PlayerWithdrawRecord::STATUS_SUCCESS:
                            $tag = Tag::create(admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_SUCCESS))->color('#87d068');
                            break;
                        case PlayerWithdrawRecord::STATUS_WAIT:
                            $tag = Tag::create(admin_trans('player_withdraw_record.status_wait'))->color('#108ee9');
                            break;
                        case PlayerWithdrawRecord::STATUS_FAIL:
                            $tag = Tag::create(admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_FAIL))->color('#f50');
                            break;
                        case PlayerWithdrawRecord::STATUS_PENDING_REJECT:
                            $tag = Tag::create(admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_PENDING_REJECT))->color('#cd201f');
                            break;
                        case PlayerWithdrawRecord::STATUS_PENDING_PAYMENT:
                            $tag = Tag::create(admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_PENDING_PAYMENT))->color('#3b5999');
                            break;
                        case PlayerWithdrawRecord::STATUS_CANCEL:
                        case PlayerWithdrawRecord::STATUS_SYSTEM_CANCEL:
                            $tag = Tag::create(admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_CANCEL))->color('#2db7f5');
                            break;
                        default:
                            $tag = '';
                    }
                    if (!empty($rejectReason)) {
                        return ToolTip::create(Badge::create(
                            $tag
                        )->count('!')->title(''))->title($rejectReason)->color('orange');
                    } else {
                        return $tag;
                    }
                })->align('center')->sortable();
            $grid->column('finish_time', admin_trans('player_withdraw_record.fields.finish_time'))->sortable()->align('center');
            $grid->column('created_at', admin_trans('player_withdraw_record.fields.created_at'))->sortable()->align('center');
            $grid->column('remark', admin_trans('player_withdraw_record.fields.remark'))->display(function ($value) {
                return Str::of($value)->limit(20, ' (...)');
            })->tip()->width('150px')->align('center');
            $grid->hideDelete();
            $grid->hideSelection();
            $grid->expandFilter();
            $grid->actions(function (Actions $actions) {
                $actions->hideDel();
                $actions->hideEdit();
            });
            $grid->filter(function (Filter $filter) {
                $filter->like()->text('player.uuid')->placeholder(admin_trans('player.fields.uuid'));
                $filter->like()->text('player.name')->placeholder(admin_trans('player.fields.name'));
                $filter->eq()->select('status')
                    ->showSearch()
                    ->style(['width' => '200px'])
                    ->dropdownMatchSelectWidth()
                    ->placeholder(admin_trans('player_withdraw_record.fields.status'))
                    ->options([
                        PlayerWithdrawRecord::STATUS_WAIT => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_WAIT),
                        PlayerWithdrawRecord::STATUS_SUCCESS => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_SUCCESS),
                        PlayerWithdrawRecord::STATUS_FAIL => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_FAIL),
                        PlayerWithdrawRecord::STATUS_PENDING_PAYMENT => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_PENDING_PAYMENT),
                        PlayerWithdrawRecord::STATUS_PENDING_REJECT => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_PENDING_REJECT),
                        PlayerWithdrawRecord::STATUS_CANCEL => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_CANCEL),
                        PlayerWithdrawRecord::STATUS_SYSTEM_CANCEL => admin_trans('player_withdraw_record.status.' . PlayerWithdrawRecord::STATUS_SYSTEM_CANCEL),
                    ]);
                $filter->eq()->select('type')
                    ->showSearch()
                    ->style(['width' => '200px'])
                    ->dropdownMatchSelectWidth()
                    ->placeholder(admin_trans('player_withdraw_record.fields.type'))
                    ->options([
                        PlayerWithdrawRecord::TYPE_ESPAYOUT => admin_trans('player_withdraw_record.type.' . PlayerWithdrawRecord::TYPE_ESPAYOUT),
                        PlayerWithdrawRecord::TYPE_ONEPAYOUT => admin_trans('player_withdraw_record.type.' . PlayerWithdrawRecord::TYPE_ONEPAYOUT),
                        PlayerWithdrawRecord::TYPE_SKLPAYOUT => admin_trans('player_withdraw_record.type.' . PlayerWithdrawRecord::TYPE_SKLPAYOUT),
                        PlayerWithdrawRecord::TYPE_ARTIFICIAL => admin_trans('player_withdraw_record.type.' . PlayerWithdrawRecord::TYPE_ARTIFICIAL),
                    ]);
                $filter->like()->text('tradeno')->placeholder(admin_trans('player_withdraw_record.fields.tradeno'));
                $filter->form()->hidden('created_at_start');
                $filter->form()->hidden('created_at_end');
                $filter->form()->dateTimeRange('created_at_start', 'created_at_end', '')->placeholder([admin_trans('player_withdraw_record.fields.created_at'), admin_trans('player_withdraw_record.fields.created_at')]);
                $filter->form()->hidden('finish_time_start');
                $filter->form()->hidden('finish_time_end');
                $filter->form()->dateTimeRange('finish_time_start', 'finish_time_end', '')->placeholder([admin_trans('player_withdraw_record.fields.finish_time'), admin_trans('player_withdraw_record.fields.finish_time')]);
            });
        });
    }
}
