<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin?????? ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace app\dice\controller\player;

use app\dice\helper\AdminScopeHelper;
use app\dice\model\lottery_pool_config\DiceLotteryPoolConfig;
use plugin\saiadmin\app\model\system\SystemUser;
use plugin\saiadmin\basic\BaseController;
use app\dice\logic\player\DicePlayerLogic;
use app\dice\validate\player\DicePlayerValidate;
use plugin\saiadmin\service\Permission;
use support\Request;
use support\Response;

/**
 * ???-?????
 */
class DicePlayerController extends BaseController
{
    /**
     * ????
     */
    public function __construct()
    {
        $this->logic = new DicePlayerLogic();
        $this->validate = new DicePlayerValidate;
        parent::__construct();
    }

    /**
     * ??????????DiceLotteryPoolConfig.id?name????? lottery_config_id ????
     * @param Request $request
     * @return Response ?? [ ['id' => int, 'name' => string], ... ]
     */
    #[Permission('???-????', 'dice:player:index:index')]
    public function getLotteryConfigOptions(Request $request): Response
    {
        $list = DiceLotteryPoolConfig::field('id,name')->order('id', 'asc')->select();
        $data = $list->map(function ($item) {
            return ['id' => (int) $item['id'], 'name' => (string) ($item['name'] ?? '')];
        })->toArray();
        return $this->success($data);
    }

    /**
     * ??????????SystemUser.id?username?realname??? admin_id ????
     * ????????????????????????????????
     * @param Request $request
     * @return Response ?? [ ['id' => int, 'username' => string, 'realname' => string], ... ]
     */
    #[Permission('???-????', 'dice:player:index:index')]
    public function getSystemUserOptions(Request $request): Response
    {
        $query = SystemUser::field('id,username,realname')->where('status', 1)->order('id', 'asc');
        if (isset($this->adminInfo['id']) && (int) $this->adminInfo['id'] > 1) {
            $deptList = $this->adminInfo['deptList'] ?? [];
            if (!empty($deptList)) {
                $query->auth($deptList);
            }
        }
        $list = $query->select();
        $data = $list->map(function ($item) {
            $label = trim((string) ($item['realname'] ?? '')) ?: (string) ($item['username'] ?? '');
            return [
                'id' => (int) $item['id'],
                'username' => (string) ($item['username'] ?? ''),
                'realname' => (string) ($item['realname'] ?? ''),
                'label' => $label ?: (string) $item['id'],
            ];
        })->toArray();
        return $this->success($data);
    }

    /**
     * ????
     * @param Request $request
     * @return Response
     */
    #[Permission('???-????', 'dice:player:index:index')]
    public function index(Request $request): Response
    {
        $where = $request->more([
            ['username', ''],
            ['name', ''],
            ['phone', ''],
            ['status', ''],
            ['coin', ''],
            ['lottery_config_id', ''],
        ]);
        $query = $this->logic->search($where);
        AdminScopeHelper::applyAdminScope($query, $this->adminInfo ?? null);
        $query->with(['diceLotteryPoolConfig']);
        $data = $this->logic->getList($query);
        return $this->success($data);
    }

    /**
     * ????
     * @param Request $request
     * @return Response
     */
    #[Permission('???-????', 'dice:player:index:read')]
    public function read(Request $request): Response
    {
        $id = $request->input('id', '');
        $model = $this->logic->read($id);
        if (!$model) {
            return $this->fail('??????');
        }
        $allowedIds = AdminScopeHelper::getAllowedAdminIds($this->adminInfo ?? null);
        if ($allowedIds !== null && !in_array((int) ($model->admin_id ?? 0), $allowedIds, true)) {
            return $this->fail('????????');
        }
        $data = is_array($model) ? $model : $model->toArray();
        return $this->success($data);
    }

    /**
     * ????
     * @param Request $request
     * @return Response
     */
    #[Permission('???-????', 'dice:player:index:save')]
    public function save(Request $request): Response
    {
        $data = $request->post();
        $this->validate('save', $data);
        // ?????????????????????
        if (empty($data['admin_id']) && isset($this->adminInfo['id']) && (int) $this->adminInfo['id'] > 0) {
            $data['admin_id'] = (int) $this->adminInfo['id'];
        }
        $result = $this->logic->add($data);
        if ($result) {
            return $this->success('????');
        } else {
            return $this->fail('????');
        }
    }

    /**
     * ????
     * @param Request $request
     * @return Response
     */
    #[Permission('???-????', 'dice:player:index:update')]
    public function update(Request $request): Response
    {
        $data = $request->post();
        $this->validate('update', $data);
        $model = $this->logic->read($data['id'] ?? 0);
        if ($model) {
            $allowedIds = AdminScopeHelper::getAllowedAdminIds($this->adminInfo ?? null);
            if ($allowedIds !== null && !in_array((int) ($model->admin_id ?? 0), $allowedIds, true)) {
                return $this->fail('????????');
            }
        }
        $result = $this->logic->edit($data['id'], $data);
        if ($result) {
            return $this->success('????');
        } else {
            return $this->fail('????');
        }
    }

    /**
     * ?????????????
     * @param Request $request
     * @return Response
     */
    #[Permission('???-????', 'dice:player:index:update')]
    public function updateStatus(Request $request): Response
    {
        $id = $request->input('id');
        $status = $request->input('status');
        if ($id === null || $id === '') {
            return $this->fail('?? id');
        }
        if ($status === null || $status === '') {
            return $this->fail('?? status');
        }
        $model = $this->logic->read($id);
        if ($model) {
            $allowedIds = AdminScopeHelper::getAllowedAdminIds($this->adminInfo ?? null);
            if ($allowedIds !== null && !in_array((int) ($model->admin_id ?? 0), $allowedIds, true)) {
                return $this->fail('????????');
            }
        }
        $this->logic->edit($id, ['status' => (int) $status]);
        return $this->success('????');
    }

    /**
     * ????
     * @param Request $request
     * @return Response
     */
    #[Permission('???-????', 'dice:player:index:destroy')]
    public function destroy(Request $request): Response
    {
        $ids = $request->post('ids', '');
        if (empty($ids)) {
            return $this->fail('?????????');
        }
        $ids = is_array($ids) ? $ids : explode(',', (string) $ids);
        $allowedIds = AdminScopeHelper::getAllowedAdminIds($this->adminInfo ?? null);
        if ($allowedIds !== null) {
            $models = $this->logic->model->whereIn('id', $ids)->column('admin_id', 'id');
            $validIds = [];
            foreach ($ids as $id) {
                $adminId = (int) ($models[$id] ?? 0);
                if (in_array($adminId, $allowedIds, true)) {
                    $validIds[] = $id;
                }
            }
            $ids = $validIds;
            if (empty($ids)) {
                return $this->fail('?????????');
            }
        }
        $result = $this->logic->destroy($ids);
        if ($result) {
            return $this->success('????');
        } else {
            return $this->fail('????');
        }
    }

}
