<?php

namespace addons\webman\common;


use addons\webman\Admin;
use addons\webman\controller\AdminController;
use addons\webman\controller\ChannelRechargeRecordController;
use addons\webman\controller\ChannelWithdrawRecordController;
use addons\webman\exception\HttpResponseException;
use addons\webman\model\AdminDepartment;
use addons\webman\model\Notice;
use addons\webman\model\PlayerRechargeRecord;
use addons\webman\model\PlayerWithdrawRecord;
use ExAdmin\ui\component\navigation\menu\MenuItem;
use ExAdmin\ui\contract\SystemAbstract;
use ExAdmin\ui\response\Response;
use ExAdmin\ui\support\Arr;
use ExAdmin\ui\support\Container;
use ExAdmin\ui\support\Token;
use ExAdmin\ui\token\AuthException;
use GatewayWorker\Lib\Gateway;


class System extends SystemAbstract
{
    /**
     * 网站名称
     * @return string
     */
    public function name(): ?string
    {
        return admin_sysconf('web_name');
    }

    /**
     * 网站logo
     * @return string
     */
    public function logo(): ?string
    {
        return admin_sysconf('web_logo');
    }

    /**
     * 网站logo跳转地址
     * @return string
     */
    public function logoHref(): ?string
    {
        return plugin()->webman->config('route.prefix');
    }

    /**
     * 头部导航右侧
     * @return array
     */
    public function navbarRight(): array
    {
        $ws = env('WS_URL', '');
        return [
            admin_view(plugin()->webman->getPath() . '/views/socket.vue')->attrs([
                'id' => Admin::id(),
                'type' => Admin::user()->type == 1 ? 'admin' : 'channel',
                'department_id' => Admin::user()->department_id,
                'count' => 0,
                'lang' => Container::getInstance()->translator->getLocale(),
                'ws' => $ws,
                'title' => admin_trans('admin.system_messages'),
                'examine_withdraw' => Admin::check(ChannelWithdrawRecordController::class, 'reject', '') || Admin::check(ChannelWithdrawRecordController::class, 'pass', ''),
                'examine_recharge' => Admin::check(ChannelRechargeRecordController::class, 'reject', '') || Admin::check(ChannelRechargeRecordController::class, 'pass', ''),
            ])
        ];
    }

    /**
     * 头部点击用户信息下拉菜单
     * @return array
     */
    public function adminDropdown(): array
    {
        return [
            MenuItem::create()->content(admin_trans('admin.user_info'))
                ->modal([AdminController::class, 'editInfo'], ['id' => Admin::id()]),
            MenuItem::create()->content(admin_trans('admin.update_password'))
                ->modal([AdminController::class, 'updatePassword'], ['id' => Admin::id()]),
        ];
    }

    /**
     * 用户信息
     * @return array
     * @throws HttpResponseException
     */
    public function userInfo(): array
    {
        try {
            Token::auth();
        } catch (AuthException $exception) {
            throw new HttpResponseException(
                response(
                    json_encode(['message' => $exception->getMessage(), 'code' => $exception->getCode()]),
                    401,
                    ['Content-Type' => 'application/json'])
            );
        }
        return Admin::user()
            ->setVisible(['id', 'nickname', 'avatar'])
            ->toArray();
    }

    /**
     * 菜单
     * @return array
     */
    public function menu(): array
    {
        return Arr::tree(admin_menu()->all());
    }

    /**
     * 上传写入数据库
     * @param $data 上传入库数据
     * @return Response
     */
    public function upload($data): Response
    {
        $model = plugin()->webman->config('database.attachment_model');
        $model::firstOrCreate($data, [
            'uploader_id' => Admin::id(),
        ]);
        return Response::success();
    }


    /**
     * 验证权限
     * @param $class 类名
     * @param $function 方法
     * @param $method 请求method
     * @return bool
     */
    public function checkPermissions($class, $function, $method): bool
    {
        return Admin::check($class, $function, $method);
    }

    /**
     * 获取新的消息
     * @param $page
     * @param $size
     * @return Response
     */
    public function noticeList($page, $size): Response
    {
        $typeArr = [];
        if (Admin::check(ChannelWithdrawRecordController::class, 'reject', '') || Admin::check(ChannelWithdrawRecordController::class, 'pass', '')) {
            $typeArr[] = Notice::TYPE_EXAMINE_WITHDRAW;
        }
        if (Admin::check(ChannelRechargeRecordController::class, 'reject', '') || Admin::check(ChannelRechargeRecordController::class, 'pass', '')) {
            $typeArr[] = Notice::TYPE_EXAMINE_RECHARGE;
        }
        $list = [];
        if (Admin::user()->type == AdminDepartment::TYPE_DEPARTMENT && !empty($typeArr)) {
            $list = Notice::where('receiver', Notice::RECEIVER_ADMIN)->whereIN('type', $typeArr)
                ->latest()
                ->forPage($page, $size)
                ->get();
        }
        if (Admin::user()->type == AdminDepartment::TYPE_CHANNEL && !empty($typeArr)) {
            $list = Notice::where('receiver', Notice::RECEIVER_DEPARTMENT)->whereIN('type', $typeArr)
                ->latest()
                ->forPage($page, $size)
                ->get();
        }
        $data = [];
        /** @var Notice $item */
        foreach ($list as $item) {
            $title = admin_trans('notice.title.' . $item->type);
            $createTime = date('Y-m-d H:i:s', strtotime($item->created_at));
            switch ($item->type) {
                case Notice::TYPE_EXAMINE_RECHARGE:
                    /** @var PlayerRechargeRecord $playerRechargeRecord */
                    $playerRechargeRecord = PlayerRechargeRecord::find($item->source_id);
                    $content = admin_trans('notice.content.' . $item->type, '', ['{player_name}' => !empty($playerRechargeRecord->player_name) ? $playerRechargeRecord->player_name : '', '{coins}' => $playerRechargeRecord->coins, '{money}' => $playerRechargeRecord->money]);
                    $data[] = [
                        'id' => $item->id,
                        'source_id' => $item->source_id,
                        'title' => $title,
                        'content' => $content,
                        'type' => $item->type,
                        'created_at' => $createTime,
                        'status' => $playerRechargeRecord->status == PlayerRechargeRecord::STATUS_RECHARGING,
                        'url' => admin_url([ChannelRechargeRecordController::class, 'examineList'])
                    ];
                    break;
                case Notice::TYPE_EXAMINE_WITHDRAW:
                    /** @var PlayerWithdrawRecord $playerWithdrawRecord */
                    $playerWithdrawRecord = PlayerWithdrawRecord::find($item->source_id);
                    $content = admin_trans('notice.content.' . $item->type, '', ['{player_name}' => !empty($playerWithdrawRecord->player_name) ? $playerWithdrawRecord->player_name : $playerWithdrawRecord->player_phone, '{coins}' => $playerWithdrawRecord->coins, '{money}' => $playerWithdrawRecord->money]);
                    $data[] = [
                        'id' => $item->id,
                        'source_id' => $item->source_id,
                        'title' => $title,
                        'content' => $content,
                        'type' => $item->type,
                        'created_at' => $createTime,
                        'status' => $playerWithdrawRecord->status == PlayerWithdrawRecord::STATUS_WAIT,
                        'url' => admin_url([ChannelWithdrawRecordController::class, 'examineList'])
                    ];
                    break;
            }
        }
        return Response::success($data);
    }
}
