<?php

namespace addons\webman\controller;

use addons\webman\Admin;
use addons\webman\model\Channel;
use addons\webman\model\ChannelFinancialRecord;
use addons\webman\model\ChannelRechargeMethodLang;
use addons\webman\model\ChannelRechargeSetting;
use addons\webman\model\CommissionRecord;
use addons\webman\model\Player;
use addons\webman\model\PlayerChipRecord;
use addons\webman\model\PlayerDeliveryRecord;
use addons\webman\model\PlayerLevel;
use addons\webman\model\PlayerRechargeRecord;
use addons\webman\model\SystemSetting;
use ExAdmin\ui\component\common\Button;
use ExAdmin\ui\component\common\Html;
use ExAdmin\ui\component\common\Icon;
use ExAdmin\ui\component\detail\Detail;
use ExAdmin\ui\component\form\Form;
use ExAdmin\ui\component\grid\avatar\Avatar;
use ExAdmin\ui\component\grid\card\Card;
use ExAdmin\ui\component\grid\EmptyStatus;
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\layout\layout\Layout;
use ExAdmin\ui\component\layout\Row;
use ExAdmin\ui\component\navigation\dropdown\Dropdown;
use ExAdmin\ui\response\Msg;
use ExAdmin\ui\response\Response;
use ExAdmin\ui\support\Container;
use ExAdmin\ui\support\Request;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
use support\Db;
use support\Log;

/**
 * 充值记录
 * @group channel
 */
class ChannelRechargeRecordController
{
    protected $model;

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

    /**
     * 渠道充值
     * @group channel
     * @auth true
     */
    public function index(): Grid
    {
        return Grid::create(new $this->model(), function (Grid $grid) {
            $grid->title(admin_trans('player_recharge_record.title'));
            $grid->model()->with(['player', 'channel_recharge_setting'])->whereIn('type', [PlayerRechargeRecord::TYPE_REGULAR, PlayerRechargeRecord::TYPE_ARTIFICIAL, PlayerRechargeRecord::TYPE_ACTIVITY])->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 (isset($exAdminFilter['status']) && (!empty($exAdminFilter['status']) || $exAdminFilter['status'] === 0)) {
                    $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(IF(type = 4, money,0)), 0) as total_artificial_money,
                           ifNull(sum(IF(type = 1, money,0)), 0) as total_espay_money,
                           ifNull(sum(IF(payment_method = 'DUITNOWP2P', money,0)), 0) as total_espay_duitnow_money,
                           ifNull(sum(IF(payment_method = 'P2PDEPOSIT', money,0)), 0) as total_espay_deposit_money,
                           ifNull(sum(IF(payment_method = 'duitnowqr', money,0)), 0) as total_onepay_duitnow_money,
                           ifNull(sum(IF(payment_method = 'online_banking', money,0)), 0) as total_onepay_deposit_money,
                           ifNull(sum(IF(payment_method = 'QR', money,0)), 0) as total_skl_duitnow_money,
                           ifNull(sum(IF(payment_method = 'P2P', money,0)), 0) as total_skl_deposit_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_recharge_record.total_data.total_artificial_money'))
                            ->value(!empty($totalData['total_artificial_money']) ? floatval($totalData['total_artificial_money']) : 0)->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_recharge_record.total_data.total_espay_money'))
                            ->value(!empty($totalData['total_espay_money']) ? floatval($totalData['total_espay_money']) : 0)->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_recharge_record.total_data.total_espay_inmoney'))
                            ->value(bcadd(bcadd(
                                bcadd(bcmul($totalData['total_espay_duitnow_money'], 0.97, 3), bcmul($totalData['total_espay_deposit_money'], 0.985, 3), 3),
                                bcadd(bcmul($totalData['total_onepay_duitnow_money'], 0.984, 3), bcmul($totalData['total_onepay_deposit_money'], 0.986, 3), 3),
                            3), bcadd(bcmul($totalData['total_skl_duitnow_money'], 0.987, 3), bcmul($totalData['total_skl_deposit_money'], 0.989, 3), 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_recharge_record.fields.id'))->align('center')->fixed(true);
            $grid->column('tradeno', admin_trans('player_recharge_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.fields.name'))->display(function ($val, PlayerRechargeRecord $data) {
                $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)
                ]);
            })->align('center');
            $grid->column('money', admin_trans('player_recharge_record.fields.money'))->display(function ($val, PlayerRechargeRecord $data) {
                return bcdiv($val,$data->rate, 2) . ' ' . ($data->currency);
            })->align('center');
            $grid->column('inmoney', admin_trans('player_recharge_record.fields.inmoney'))->display(function ($val, PlayerRechargeRecord $data) {
                if ($data->payment_method == 'DUITNOWP2P') {
                    $ratio = 0.97;
                } elseif ($data->payment_method == 'P2PDEPOSIT') {
                    $ratio = 0.985;
                } elseif ($data->payment_method == 'duitnowqr') {
                    $ratio = 0.984;
                } elseif ($data->payment_method == 'online_banking') {
                    $ratio = 0.986;
                } elseif ($data->payment_method == 'P2P') {
                    $ratio = 0.989;
                } elseif ($data->payment_method == 'QR') {
                    $ratio = 0.987;
                } 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_recharge_record.fields.coins'))->align('center')->sortable();
            $grid->column('gift_coins', admin_trans('player_recharge_record.fields.gift_coins'))->align('center');
            $grid->column('type', admin_trans('player_recharge_record.fields.type'))->display(function ($val) {
                switch ($val) {
                    case PlayerRechargeRecord::TYPE_REGULAR:
                        return Tag::create(admin_trans('player_recharge_record.type.' . $val))
                            ->color('#55acee');
                    case PlayerRechargeRecord::TYPE_ACTIVITY:
                        return Tag::create(admin_trans('player_recharge_record.type.' . $val))
                            ->color('#3b5999');
                    case PlayerRechargeRecord::TYPE_ARTIFICIAL:
                        return Tag::create(admin_trans('player_recharge_record.type.' . $val))
                            ->color('#cd201f');
                    default:
                        return '';
                }
            })->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_wait'))
                            ->color('#108ee9');
                    case PlayerRechargeRecord::STATUS_RECHARGING:
                        return Tag::create(admin_trans('player_recharge_record.status_examine'))
                            ->color('#3b5999');
                    case PlayerRechargeRecord::STATUS_RECHARGED_SUCCESS:
                        return Tag::create(admin_trans('player_recharge_record.status_success'))
                            ->color('#87d068');
                    case PlayerRechargeRecord::STATUS_RECHARGED_FAIL:
                        return Tag::create(admin_trans('player_recharge_record.status_fail'))
                            ->color('#f50');
                    case PlayerRechargeRecord::STATUS_RECHARGED_CANCEL:
                        return Tag::create(admin_trans('player_recharge_record.status_cancel'))
                            ->color('#2db7f5');
                    case PlayerRechargeRecord::STATUS_RECHARGED_REJECT:
                        return Tag::create(admin_trans('player_recharge_record.status_reject'))
                            ->color('#2db7f5');
                    case PlayerRechargeRecord::STATUS_RECHARGED_SYSTEM_CANCEL:
                        return Tag::create(admin_trans('player_recharge_record.status_system_cancel'))
                            ->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')->fixed('right');
            $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('type')
                    ->showSearch()
                    ->style(['width' => '200px'])
                    ->dropdownMatchSelectWidth()
                    ->placeholder(admin_trans('player_recharge_record.fields.type'))
                    ->options([
                        PlayerRechargeRecord::TYPE_REGULAR => admin_trans('player_recharge_record.type.' . PlayerRechargeRecord::TYPE_REGULAR),
                        PlayerRechargeRecord::TYPE_ARTIFICIAL => admin_trans('player_recharge_record.type.' . PlayerRechargeRecord::TYPE_ARTIFICIAL),
                    ]);
                $filter->eq()->select('status')
                    ->showSearch()
                    ->style(['width' => '200px'])
                    ->dropdownMatchSelectWidth()
                    ->placeholder(admin_trans('player_recharge_record.fields.status'))
                    ->options([
                        PlayerRechargeRecord::STATUS_WAIT => admin_trans('player_recharge_record.status.' . PlayerRechargeRecord::STATUS_WAIT),
                        PlayerRechargeRecord::STATUS_RECHARGING => admin_trans('player_recharge_record.status.' . PlayerRechargeRecord::STATUS_RECHARGING),
                        PlayerRechargeRecord::STATUS_RECHARGED_SUCCESS => admin_trans('player_recharge_record.status.' . PlayerRechargeRecord::STATUS_RECHARGED_SUCCESS),
                        PlayerRechargeRecord::STATUS_RECHARGED_FAIL => admin_trans('player_recharge_record.status.' . PlayerRechargeRecord::STATUS_RECHARGED_FAIL),
                        PlayerRechargeRecord::STATUS_RECHARGED_CANCEL => admin_trans('player_recharge_record.status.' . PlayerRechargeRecord::STATUS_RECHARGED_CANCEL),
                        PlayerRechargeRecord::STATUS_RECHARGED_REJECT => admin_trans('player_recharge_record.status.' . PlayerRechargeRecord::STATUS_RECHARGED_REJECT),
                        PlayerRechargeRecord::STATUS_RECHARGED_SYSTEM_CANCEL => admin_trans('player_recharge_record.status.' . PlayerRechargeRecord::STATUS_RECHARGED_SYSTEM_CANCEL),
                    ]);
                $filter->like()->text('tradeno')->placeholder(admin_trans('player_recharge_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('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')]);

            });
        });
    }

    /**
     * 充值审核
     * @group channel
     * @auth true
     */
    public function examineList(): Grid
    {
        return Grid::create(new $this->model(), function (Grid $grid) {
            $grid->title(admin_trans('player_recharge_record.examine_title'));
            $grid->bordered(true);
            $grid->autoHeight();
            $requestFilter = Request::input('ex_admin_filter', []);
            $tradeno = Request::input('tradeno', []);
            if (!empty($tradeno)) {
                $grid->model()->where('tradeno', $tradeno);
            }
            $grid->model()->with(['player', 'channel_recharge_setting'])->whereIn('type', [PlayerRechargeRecord::TYPE_REGULAR, PlayerRechargeRecord::TYPE_ACTIVITY])
                ->whereIn('status', [PlayerRechargeRecord::STATUS_RECHARGING, PlayerRechargeRecord::STATUS_WAIT, PlayerRechargeRecord::STATUS_RECHARGED_SUCCESS, PlayerRechargeRecord::STATUS_RECHARGED_REJECT, PlayerRechargeRecord::STATUS_RECHARGED_SYSTEM_CANCEL])
                ->whereNull('payment_method')
                ->orderBy('created_at', 'desc');
            if (isset($requestFilter['created_at_start']) && !empty($requestFilter['created_at_start'])) {
                $grid->model()->where('created_at', '>=', $requestFilter['created_at_start']);
            }
            if (isset($requestFilter['created_at_end']) && !empty($requestFilter['created_at_end'])) {
                $grid->model()->where('created_at', '<=', $requestFilter['created_at_end']);
            }
            $grid->column('id', admin_trans('player_recharge_record.fields.id'))->align('center');
            $grid->column('tradeno', admin_trans('player_recharge_record.fields.tradeno'))->copy();
            $grid->column('player.uuid', admin_trans('player.fields.uuid'))->copy();
            $grid->column('player.name', admin_trans('player.fields.name'))->display(function ($val, PlayerRechargeRecord $data) {
                $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)
                ]);
            })->align('center');
            $grid->column('money', admin_trans('player_recharge_record.fields.money'))->display(function ($val, PlayerRechargeRecord $data) {
                return bcdiv($val,$data->rate, 2) . ' ' . $data->currency;
            })->align('center');
            $grid->column('coins', admin_trans('player_recharge_record.fields.coins'))->align('center');
            $grid->column('gift_coins', admin_trans('player_recharge_record.fields.gift_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_wait'))
                            ->color('#108ee9');
                    case PlayerRechargeRecord::STATUS_RECHARGING:
                        return Tag::create(admin_trans('player_recharge_record.status_examine'))
                            ->color('#3b5999');
                    case PlayerRechargeRecord::STATUS_RECHARGED_SUCCESS:
                        return Tag::create(admin_trans('player_recharge_record.status_success'))
                            ->color('#87d068');
                    case PlayerRechargeRecord::STATUS_RECHARGED_FAIL:
                        return Tag::create(admin_trans('player_recharge_record.status_fail'))
                            ->color('#f50');
                    case PlayerRechargeRecord::STATUS_RECHARGED_CANCEL:
                        return Tag::create(admin_trans('player_recharge_record.status_cancel'))
                            ->color('#2db7f5');
                    case PlayerRechargeRecord::STATUS_RECHARGED_REJECT:
                        return Tag::create(admin_trans('player_recharge_record.status_reject'))
                            ->color('#2db7f5');
                    case PlayerRechargeRecord::STATUS_RECHARGED_SYSTEM_CANCEL:
                        return Tag::create(admin_trans('player_recharge_record.status_system_cancel'))
                            ->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('reject_reason', admin_trans('player_recharge_record.fields.reject_reason'))->display(function ($value) {
                return Str::of($value)->limit(20, ' (...)');
            })->tip()->width('150px')->align('center');
            $grid->column('created_at', admin_trans('player_recharge_record.fields.created_at'))->sortable()->align('center');
            $grid->hideDelete();
            $grid->hideSelection();
            $grid->expandFilter();
            $grid->actions(function (Actions $actions, PlayerRechargeRecord $data) {
                $actions->hideDel();
                $actions->hideEdit();
                $dropdown = Dropdown::create(
                    Button::create([
                        admin_trans('player_recharge_record.btn.action'), Icon::create('DownOutlined')->style(['marginRight' => '5px'])
                    ]))->trigger(['click']);

                $dropdown->item(admin_trans('player_recharge_record.btn.view_channel_recharge_setting'), 'AppstoreAddOutlined')
                    ->modal([$this, 'rechargeSetting'], ['setting_id' => $data->setting_id]);
                $dropdown->item(admin_trans('player_recharge_record.btn.view_recharge_certificate'), 'far fa-file-image')
                    ->modal($this->rechargeCertificate([
                        'tradeno' => $data->tradeno,
                        'certificate' => $data->certificate,
                    ]))->title(admin_trans('player_recharge_record.view_recharge_certificate_title', null, ['{tradeno}' => $data->tradeno]));

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

                $dropdown->item(admin_trans('player_recharge_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_recharge_record.fields.status'))
                    ->options([
                        PlayerRechargeRecord::STATUS_WAIT => admin_trans('player_recharge_record.status_wait'),
                        PlayerRechargeRecord::STATUS_RECHARGING => admin_trans('player_recharge_record.status_examine'),
                        PlayerRechargeRecord::STATUS_RECHARGED_SUCCESS => admin_trans('player_recharge_record.status_examine_pass'),
                        PlayerRechargeRecord::STATUS_RECHARGED_REJECT => admin_trans('player_recharge_record.status_examine_reject'),
                        PlayerRechargeRecord::STATUS_RECHARGED_SYSTEM_CANCEL => admin_trans('player_recharge_record.status_system_cancel'),
                    ]);
                $filter->like()->text('tradeno')->placeholder(admin_trans('player_recharge_record.fields.tradeno'));
                $filter->eq()->number('money')->precision(2)->style(['width' => '200px'])->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')]);
            });
        });
    }

    /**
     * 充值订单审核拒绝
     * @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 PlayerRechargeRecord $playerRechargeRecord */
                $playerRechargeRecord = $this->model::find($id);
                if (empty($playerRechargeRecord)) {
                    return message_error(admin_trans('player_recharge_record.not_fount'));
                }
                if ($playerRechargeRecord->type != PlayerRechargeRecord::TYPE_REGULAR && $playerRechargeRecord->type != PlayerRechargeRecord::TYPE_ACTIVITY) {
                    return message_error(admin_trans('player_recharge_record.recharge_record_error'));
                }
                switch ($playerRechargeRecord->status) {
                    case PlayerRechargeRecord::STATUS_RECHARGED_SUCCESS:
                        return message_warning(admin_trans('player_recharge_record.recharge_record_has_pass'));
                    case PlayerRechargeRecord::STATUS_RECHARGED_FAIL:
                        return message_warning(admin_trans('player_recharge_record.recharge_record_has_fail'));
                    case PlayerRechargeRecord::STATUS_RECHARGED_CANCEL:
                        return message_warning(admin_trans('player_recharge_record.recharge_record_has_cancel'));
                    case PlayerRechargeRecord::STATUS_RECHARGED_REJECT:
                        return message_warning(admin_trans('player_recharge_record.recharge_record_has_reject'));
                    case PlayerRechargeRecord::STATUS_RECHARGED_SYSTEM_CANCEL:
                        return message_warning(admin_trans('player_recharge_record.recharge_record_has_system_cancel'));
                }
                try {
                    // 生成订单
                    $playerRechargeRecord->status = PlayerRechargeRecord::STATUS_RECHARGED_REJECT;
                    $playerRechargeRecord->reject_reason = $form->input('reject_reason');
                    $playerRechargeRecord->finish_time = date('Y-m-d H:i:s');
                    $playerRechargeRecord->user_id = Admin::id() ?? 0;
                    $playerRechargeRecord->user_name = !empty(Admin::user()) ? Admin::user()->username : '';
                    if ($playerRechargeRecord->save()) {
                        saveChannelFinancialRecord($playerRechargeRecord, ChannelFinancialRecord::ACTION_RECHARGE_REJECT);
                    }
                } catch (\Exception $e) {
                    return message_error(admin_trans('player_recharge_record.action_error'));
                }
                return message_success(admin_trans('player_recharge_record.action_success'));
            });
        });
    }

    /**
     * 充值订单审核通过
     * @param $id
     * @auth true
     * @group channel
     * @return Msg
     */
    public function pass($id): Msg
    {
        /** @var PlayerRechargeRecord $playerRechargeRecord */
        $playerRechargeRecord = $this->model::find($id);
        if (empty($playerRechargeRecord)) {
            return message_error(admin_trans('player_recharge_record.not_fount'));
        }
        if ($playerRechargeRecord->type != PlayerRechargeRecord::TYPE_REGULAR && $playerRechargeRecord->type != PlayerRechargeRecord::TYPE_ACTIVITY) {
            return message_error(admin_trans('player_recharge_record.recharge_record_error'));
        }
        switch ($playerRechargeRecord->status) {
            case PlayerRechargeRecord::STATUS_WAIT:
                return message_warning(admin_trans('player_recharge_record.recharge_record_not_complete'));
            case PlayerRechargeRecord::STATUS_RECHARGED_SUCCESS:
                return message_warning(admin_trans('player_recharge_record.recharge_record_has_pass'));
            case PlayerRechargeRecord::STATUS_RECHARGED_FAIL:
                return message_warning(admin_trans('player_recharge_record.recharge_record_has_fail'));
            case PlayerRechargeRecord::STATUS_RECHARGED_CANCEL:
                return message_warning(admin_trans('player_recharge_record.recharge_record_has_cancel'));
            case PlayerRechargeRecord::STATUS_RECHARGED_REJECT:
                return message_warning(admin_trans('player_recharge_record.recharge_record_has_reject'));
            case PlayerRechargeRecord::STATUS_RECHARGED_SYSTEM_CANCEL:
                return message_warning(admin_trans('player_recharge_record.recharge_record_has_system_cancel'));
        }
        /** @var Channel $channel */
        $channel = Channel::where('department_id', Admin::user()->department_id)->first();
        if (empty($channel)) {
            return message_error(admin_trans('channel.not_fount'));
        }
        DB::beginTransaction();
        try {
            $firstRecharge = PlayerRechargeRecord::query()
                ->where('player_id', $playerRechargeRecord->player_id)
                ->where('status', 2)
                ->where('setting_id', '>', 0)
                ->doesntExist();
            if (!$firstRecharge) {
                $playerRechargeRecord->gift_coins = 0;
            }
            $beforeGameAmount = $playerRechargeRecord->player->wallet->money;
            // 生成订单
            $playerRechargeRecord->status = PlayerRechargeRecord::STATUS_RECHARGED_SUCCESS;
            $playerRechargeRecord->finish_time = date('Y-m-d H:i:s');
            $playerRechargeRecord->user_id = Admin::id() ?? 0;
            $playerRechargeRecord->user_name = !empty(Admin::user()) ? Admin::user()->username : '';
            $allCoins = bcadd($playerRechargeRecord->coins, $playerRechargeRecord->gift_coins, 2);
            $playerRechargeRecord->player->wallet->money = bcadd($playerRechargeRecord->player->wallet->money, $allCoins, 2);
            $playerRechargeRecord->player->player_extend->recharge_amount = bcadd($playerRechargeRecord->player->player_extend->recharge_amount, $allCoins, 2);

            // 寫入金流明細
            $playerDeliveryRecord = new PlayerDeliveryRecord;
            $playerDeliveryRecord->player_id = $playerRechargeRecord->player_id;
            $playerDeliveryRecord->department_id = $playerRechargeRecord->department_id;
            $playerDeliveryRecord->target = $playerRechargeRecord->getTable();
            $playerDeliveryRecord->target_id = $playerRechargeRecord->id;
            $playerDeliveryRecord->type = PlayerDeliveryRecord::TYPE_RECHARGE;
            $playerDeliveryRecord->source = 'self_recharge';
            $playerDeliveryRecord->amount = $allCoins;
            $playerDeliveryRecord->amount_before = $beforeGameAmount;
            $playerDeliveryRecord->amount_after = $playerRechargeRecord->player->wallet->money;
            $playerDeliveryRecord->tradeno = $playerRechargeRecord->tradeno ?? '';
            $playerDeliveryRecord->remark = $playerRechargeRecord->remark ?? '';
            $playerDeliveryRecord->save();
            // 更新渠道信息
            $channel->recharge_amount = bcadd($channel->recharge_amount, $allCoins, 2);
            $channel->save();
            $playerRechargeRecord->push();
            // 記錄財務操作
            saveChannelFinancialRecord($playerRechargeRecord, ChannelFinancialRecord::ACTION_RECHARGE_PASS);
            DB::commit();
            sendSocketMessage('private-recharge_withdrawal', [
                'msg_type' => 'withdrawal',
                'player_id' => $playerRechargeRecord->player_id,
                'amount' => $playerRechargeRecord->player->wallet->money,
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('充值错误', [$e->getTrace()]);
            return message_error(admin_trans('player_recharge_record.action_error') . $e->getMessage() . $e->getLine());
        }
        return message_success(admin_trans('player_recharge_record.action_success'))->refresh();
    }


    /**
     * 查看付款凭证
     * @auth true
     * @group channel
     * @param $data
     * @return Detail
     */
    public function rechargeCertificate($data): Detail
    {
        return Detail::create($data, function (Detail $detail) {
            $detail->item('certificate')->display(function ($val) {
                if (!empty($val)) {
                    $image = Image::create()
                        ->width(100)
                        ->height(100)
                        ->style(['objectFit' => 'cover'])
                        ->src($val);
                }
                return Html::create()->content([
                    $image ?? EmptyStatus::create()->style(['margin' => '0 160px !important'])
                ])->style(['margin' => '0 auto']);
            });
        })->column(1);
    }

    /**
     * 查看充值账号配置
     * @auth true
     * @group channel
     * @param $setting_id
     * @return Detail
     */
    public function rechargeSetting($setting_id): Detail
    {
        $lang = Container::getInstance()->translator->getLocale();
        /** @var ChannelRechargeSetting $data */
        $data = ChannelRechargeSetting::find($setting_id);
        /** @var ChannelRechargeMethodLang $methodLang */
        $methodLang = $data->channel_recharge_method->methodLang->where('lang', $lang)->first();
        return Detail::create([
            'bank_name' => $methodLang->bank_name ?? '',
            'sub_bank' => $methodLang->sub_bank ?? '',
            'owner' => $methodLang->owner ?? '',
            'account' => $data->channel_recharge_method->account,
        ], function (Detail $detail) {
            $detail->item('bank_name', admin_trans('channel_recharge_method.fields.bank_name'));
            $detail->item('sub_bank', admin_trans('channel_recharge_method.fields.sub_bank'));
            $detail->item('owner', admin_trans('channel_recharge_method.fields.owner'));
            $detail->item('account', admin_trans('channel_recharge_method.fields.account'));
        })->column(2);
    }

    /**
     * 筛选玩家下拉
     * @return mixed
     */
    public function getPlayerOptions()
    {
        $request = Request::input();
        $player = Player::orderBy('created_at', 'desc')
            ->forPage(1, 20);
        if (!empty($request['search'])) {
            $player->where('phone', 'like', '%' . $request['search'] . '%');
        }
        $playerList = $player->get();
        $data = [];
        /** @var Player $player */
        foreach ($playerList as $player) {
            $data[] = [
                'value' => $player->id,
                'label' => $player->phone,
            ];
        }
        return Response::success($data);
    }
}
