<?php

namespace frontend\modules\api\components;

use common\components\AjaxException;
use common\components\BaseAjaxController;
use common\models\BaseUser;
use common\services\RoleService;
use common\services\UserService;
use Yii;
use yii\web\BadRequestHttpException;

class BaseAdminController extends BaseAjaxController
{
    private bool $debug = false;
    public int $uid;

    /**
     * @var BaseUser
     */
    public BaseUser $userInfo;

    private array $whiteControllerId = [
        'login', 'user',
    ];

    /**
     * @param $id
     * @param $module
     * @param $config
     */
    public function __construct($id, $module, $config = [])
    {
        if (!$this->debug) {
            $this->checkLogin();
        } else {
            $this->fakeLogin();
        }

        parent::__construct($id, $module, $config);
    }

    /**
     * @return void
     * @throws AjaxException
     */
    public function checkLogin(): void
    {
        $token = Yii::$app->request->headers->get("token");
        if (!$token) {
            throw new AjaxException('用户身份失效,请登录');
        } else {
            $uid = Yii::$app->redis->get($token);
            if (!$uid) {
                throw new AjaxException('用户身份失效,请先登录');
            }
            $this->loginWithUid($uid);
        }
    }

    /**
     * @return void
     */
    public function fakeLogin(): void
    {
        $uid = 1;
        $this->loginWithUid($uid);
    }

    /**
     * @param $uid
     * @return void
     * @throws AjaxException
     */
    private function loginWithUid($uid): void
    {
        $userInfo = UserService::getBaseUserById($uid);
        if ($userInfo->status == 0) {
            throw new AjaxException('账户已冻结');
        }
        // 这个判断现在暂时不需要
        // if(($userInfo->app_token != $token)  throw new LoginException('当前账号已在其他设备登录,您已强制下线!');
        $this->uid = $uid;
        $this->userInfo = $userInfo;
        $this->userInfo->isSuperAdmin = $userInfo->roles == 1;
        $this->userInfo->roleName = RoleService::getRoleNameById($userInfo->roles);
        $this->userInfo->realName = UserService::getRealNameByUserId($userInfo->id);
    }

    /**
     * @throws BadRequestHttpException
     */
    public function beforeAction($action): bool
    {
        $session = Yii::$app->session;
        $route = substr(Yii::$app->controller->getRoute(), strlen($this->module->id));
        $rules = $session['rules'];
        $controllerId = Yii::$app->controller->id;
        if ($rules !== "*") {
            if (!in_array($controllerId, $this->whiteControllerId)) {
                if (is_array($rules) && !in_array($route, $rules)) {
                    //TODO 临时取消权限
                    throw new BadRequestHttpException('权限不足!!!');
                }
            }
        }
        return parent::beforeAction($action);
    }

    /**
     * @param $table string 表名
     * @param $key  string 条件主键,作用参考switch中的case
     * @param $val  string 修改主键
     * @param $data array $key与$val主键对应的数据载体
     * UPDATE `fa_line` SET  weigh = CASE id  WHEN 10 THEN 1
     * WHEN 11 THEN 2
     * WHEN 12 THEN 3
     * WHEN 8 THEN 4
     * WHEN 13 THEN 5
     * WHEN 14 THEN 6
     * WHEN 22 THEN 7
     * END
     * WHERE id in (10,11,12,8,13,14,22)
     * @return string 批量更新SQL
     */
    public function batchUpdate(string $table, string $key, string $val, array $data, $valIsString = false): string
    {
        $ids = implode(",", array_column($data, $key));
        $condition = " ";
        foreach ($data as $v) {
            if (!$valIsString) {
                $condition .= "WHEN {$v[$key]} THEN {$v[$val]} ";
            } else {
                $condition .= "WHEN {$v[$key]} THEN '{$v[$val]}' ";
            }
        }
        return "UPDATE `{$table}` SET  {$val} = CASE {$key} {$condition} END WHERE {$key} in ({$ids})";
    }
}
