<?php

namespace frontend\modules\api\controllers;

use common\components\AjaxException;
use common\models\BaseUser;
use common\services\AdminLogService;
use common\services\CaseService;
use common\services\UserService;
use Exception;
use frontend\modules\api\components\BaseAdminController;
use Yii;
use yii\base\InvalidConfigException;
use yii\web\Response;
use yii\web\User;

class UserController extends BaseAdminController
{
    /**
     * 用户列表
     * @param int $current
     * @param int $page
     * @return Response
     * @throws InvalidConfigException
     */
    public function actionList(int $current = 1, int $page = 10)
    {
        //公共部分
        $query = BaseUser::find()->alias("u")
            ->join('LEFT JOIN', 'staff s', 's.uid = u.id')
            ->where("u.id > 1")
            ->andWhere("u.status >= 0")
            ->limit($page)
            ->offset(($current - 1) * $page);
        //排序
        $this->initSequence($query, "u.id desc");
        //主要筛选条件
        $this->addConditionToQueryNew("u.id", "id", $query);
        $this->addConditionToQuery("username", $query, true);
        if ($this->getParams("name") !== null && $this->getParams("name") !== "") {
            $query->andWhere(["like", "s.name", $this->getParams("name")]);
        }
        if ($this->getParams("department") !== null && $this->getParams("department") !== "") {
            $query->andWhere(["like", "s.department", $this->getParams("department")]);
        }
        if ($this->getParams("employment") !== null && $this->getParams("employment") !== "") {
            $query->andWhere(["like", "s.employment", $this->getParams("employment")]);
        }
        if ($this->getParams("seniority") !== null && $this->getParams("seniority") !== "") {
            $query->andWhere(["s.seniority" => $this->getParams("seniority")]);
        }
        if ($this->getParams("phone") !== null && $this->getParams("phone") !== "") {
            $query->andWhere(["like", "s.phone", $this->getParams("phone")]);
        }
        $this->addConditionToQuery("email", $query, true);
        $this->addConditionToQuery("roles", $query, true);
        $this->addStartEndConditionToQuery("last_login_time", $query);
        $info = $query
            ->asArray()
            ->select(UserService::getUserSqlSelectInfo())
            ->all();
        $info = CaseService::setStudyTime($info);
        $data['data'] = $info;
        //返回
        $data['total'] = $query->count();
        return $this->asJson($data);
    }

    /**
     * 用户信息
     * @param  $userId
     * @return Response
     * @throws Exception
     */
    public function actionInfo($userId)
    {
        // 基础校验
        /** @var BaseUser $info */
        $info = UserService::getQuery()->alias("u")
            ->join('LEFT JOIN', 'staff s', 's.uid = u.id')
            ->where(["u.id" => $userId])
            ->asArray()
            ->select(UserService::getUserSqlSelectInfo())
            ->one();
        // 计算学习案例时长
        $info = CaseService::setStudyTime([$info])[0];
        $data['data'] = $info;
        // 追加头像路径
        $imageBasePath = $this->getImageBasePath();
        $data['imageBasePath'] = $imageBasePath;
        //返回时去除密码
        unset($data['data']['password']);
        return $this->asJson($data);
    }

    /**
     * 用户添加
     * @return Response
     * @throws Exception
     */
    public function actionAdd()
    {
        UserService::add();
        return $this->asJson();
    }

    /**
     * 用户修改
     * @param $id
     * @return Response
     * @throws Exception
     */
    public function actionUserUpdate($id)
    {
        UserService::update($id);
        return $this->asJson();
    }

    /**
     * 从excel批量导入
     * @return Response
     * @throws \yii\db\Exception
     */
    public function actionAddBatch()
    {
        // 获取传值
        $post = Yii::$app->request->post();
        $json = $post['json'];
        if (count($json) > 10000) {
            return $this->asJson([], 1, "批量新增数量过大，请控制在10000条记录之内！"); //通知前端
        }
        $param = [
            'username',
            'password',
            'name',
            'phone',
            'email',
            'status',
            'roles',
            'department_id',
            'job_id',
            'create_time',
            'update_time',
        ];
        $paramData = [];
        foreach ($json as $key => $value) {
            $time = strtotime('now');
            if ($key > 0) {
                //插入
                $paramData[] = [
                    'username' => $value[1],
                    'password' => md5($value[2]),
                    'name' => $value[3],
                    'phone' => (string)$value[4],
                    'email' => $value[5],
                    'status' => $value[6],
                    'roles' => (string)$value[7],
                    'department_id' => $value[8],
                    'job_id' => $value[9],
                    'create_time' => date("Y-m-d H:i:s", $time),
                    'update_time' => date("Y-m-d H:i:s", $time),
                ];
            }
        }
        Yii::$app->db->createCommand()->batchInsert(BaseUser::tableName(), $param, $paramData)->execute();
        $data = [];
        return $this->asJson($data);
    }

    /**
     * 用户名查重
     * @param $category
     * @param $value
     * @return Response
     */
    public function actionCheck($category, $value)
    {
        // 定义返回值
        $checkData = [];
        if ($category == "username") {
            $info = UserService::getQuery()->andWhere(['username' => $value])->one();
            if ($info) {
                return $this->asJson([], 1, "此用户账号 {$value} 已存在！"); //通知前端
            }
        } else {
            return $this->asJson([], 1, "类型错误！"); //通知前端
        }
        // 返回
        return $this->asJson($checkData);
    }

    /**
     * 修改资料
     * @param $password
     * @param $origin
     * @return Response
     * @throws Exception
     */
    public function actionChangeInfo($password, $origin)
    {
        // 基础校验
        $info = UserService::getBaseUserById($this->uid);
//        if ($info->password !== md5($origin)) {
        if ($info->password !== $origin) {
            throw new AjaxException("原始密码错误!");
        }
//        if ($info->password === md5($password)) {
        if ($info->password === $password) {
            throw new AjaxException("新密码与原始密码相同!");
        }
        $info->password = $password;
//        $info->password = md5($password);
        if (!$info->save()) {
            throw new AjaxException("保存失败!");
        }
        $data['data'] = [];
        return $this->asJson($data);
    }

    /**
     * 返回可以审核案例的用户列表
     * @return Response
     */
    public function actionCanCheckList(): Response
    {
        $data = UserService::getCanCheckList();
        return $this->asJson($data);
    }

    /**
     * 保存头像
     * @param null $userId
     * @return Response
     * @throws Exception
     */
    public function actionSaveAvatar($userId = null)
    {
        // 基础校验
        $info = UserService::getBaseUserById($userId);
        $info->path = $_GET['path'];
        if (!$info->save()) {
            return $this->asJson([], 1, "保存失败！"); //通知前端
        }
        $data['data'] = [];
        return $this->asJson($data);
    }

    /**
     * 登出
     * @return Response
     */
    public function actionLogout()
    {
        $model = "";
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        AdminLogService::saveLogWithUpdateHistory($origin, $model, 0, "", $this->getAllParams());
        return $this->asJson();
    }
}
