<?php

namespace app\admin\controller;

use app\BaseController;
use app\admin\model\Admin as AdminModel;
use app\admin\model\RoleMenu;
use app\admin\model\Menu;
use think\exception\Exception;
use think\facade\Db;
use app\admin\validate\AdminValidate;
use app\admin\model\User;
use app\admin\model\KefuWork;
use think\facade\Session;
use app\admin\model\KefuTime;
use thans\jwt\facade\JWTAuth;
use app\admin\model\Department;
use app\admin\model\Role;

class Admin extends BaseController
{
    protected $noNeedLogin = ['login'];
   
    /**
     * @api {get} /list 查询管理员列表
     */
    public function list()
    {
        try {
            $params = $this->request->param();
            $query = new AdminModel();
            if (!empty($params['username'])) {
                $query = $query->where('username', 'like', "%{$params['username']}%");
            }
            if (!empty($params['phone'])) {
                $query = $query->where('phone', 'like', "%{$params['phone']}%");
            }
            if (isset($params['is_kefu']) && $params['is_kefu'] != '') {
                $query = $query->where('is_kefu', $params['is_kefu']); 
            }
            if (!empty($params['role_id'])) {
                $query = $query->where('role_id', $params['role_id']);
            }
            if (!empty($params['department_id'])) {
                $query = $query->where('department_id', $params['department_id']);
            }
            
            $page = isset($params['page']) ? intval($params['page']) : 1;
            $limit = isset($params['limit']) ? intval($params['limit']) : 15;

            $count = $query->count();
            $list = $query->with(['role', 'department'])
                ->order('id', 'desc')
                ->limit($limit)
                ->page($page)
                ->select();

        } catch (\Exception $e) {
            return $this->error('查询失败：'.$e->getMessage());
        }
        return $this->success(['count' => $count, 'list' => $list]);
    }

    /**
     * @api {post} /update 添加/修改管理员
     */
    public function update()
    {

        Db::startTrans();
        try {
            $params = (new AdminValidate())->post()->goCheck('add');
            $id = $this->request->param('id');
            // 只允许超级管理员配置
            if ($this->admin_id != 1) {
                return $this->error('只有超级管理员才能操作');
            }

            if (empty($id)) {
                // 新增校验
                if (empty($params['password'])) {
                    return $this->error('密码不能为空');
                }
                if (empty($params['role_id'])) {
                    return $this->error('角色ID不能为空');
                }
                if (empty($params['department_id'])) {
                    return $this->error('部门ID不能为空');
                }
            } elseif ($id != 1) {
                if (empty($params['role_id'])) {
                    return $this->error('角色ID不能为空');
                }
                if (empty($params['department_id'])) {
                    return $this->error('部门ID不能为空');
                }
            }

            if (!empty($params['password'])) {
                $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
            } else {
                unset($params['password']);
            }
            if (!empty($params['payment_password'])) {
                $params['payment_password'] = password_hash($params['payment_password'], PASSWORD_DEFAULT);
            } else {
                unset($params['payment_password']);
            }

            $usernameCount = AdminModel::where('username', $params['username'])
                ->where('id', '<>', $id ?? 0)
                ->count();
            if ($usernameCount > 0) {
                return $this->error('用户名已存在');
            }

            $role = $params['is_kefu'] == 1 ? 3 : 2;//获取角色类型：1超管；2普管；3客服

            if (!empty($id)) {
                if ($id == 1) {
                    $role = 1;
                }
                unset($params['username']);
                AdminModel::where('id', $id)->update($params);
                User::where('uid', $id)->where('from', 0)->update(['role' => $role, 'realname' => $params['nickname'], 'phone' => $params['phone'], 'remark' => $params['remark']]);
            } else {
                $admin = AdminModel::create($params);

                //插入user
                $params['id'] = $admin->id;
                $params['role'] = $role;
                $avatar = Role::where('id', $params['role_id'])->value('avatar');
                $params['avatar'] = $avatar;
                User::addCs($params);
            }

            Db::commit(); 
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
        return $this->success([],'操作成功');
    }

    // 删除管理员
    public function delete()
    {
        try {
            
            $params = (new AdminValidate())->goCheck('del');

            // 只允许超级管理员配置
            if ($this->admin_id != 1) {
                return $this->error('只有超级管理员才能操作');
            }

            if ($params['id'] == 1) {
                return $this->error('超级管理员不能删除');
            }
            if ($params['id'] == 2) {
                return $this->error('机器人客服不能删除');
            }

            // TP 删除语法
            AdminModel::where('id', $params['id'])->delete();
        } catch (\Exception $e) {
            return $this->error('删除失败：'.$e->getMessage());
        }
        return $this->success([],'删除成功');
    }

    /**
     * @api {post} /setPassword 修改登录密码
     */
    public function setPassword()
    {
        Db::startTrans();
        try {
            $params = (new AdminValidate())->post()->goCheck('password');

            $user = AdminModel::find($this->admin_id);
            if (!$user) {
                throw new \Exception('用户不存在');
            }

            // 校验旧密码
            if (!password_verify($params['old_password'], $user->password)) {
                throw new \Exception('密码错误');
            }

            // 更新登录密码
            $user->password = password_hash($params['password'], PASSWORD_DEFAULT);
            $user->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    /**
     * @api {post} /login 管理员登录
     */
    public function login()
    {
        // 登录无需事务，移除多余的 Db::startTrans()
        try {
            $params = (new AdminValidate())->post()->goCheck('login');

            $admin = AdminModel::where('username', $params['username'])->find();
           
            if (!$admin) {
                throw new \Exception('账号不存在');
            }
            if (!password_verify($params['password'], $admin->password)) {
                throw new \Exception('密码错误');
            }
            // 获取角色权限（优化 TP 查询语法）
            if ($admin->role_id && $admin->id > 1) {
                $admin->role_menu = RoleMenu::alias('rm')
                    ->join('menu m', 'rm.menu_id = m.id','left')
                    ->where('rm.role_id', $admin->role_id)
                    ->where('m.status', 1)
                    ->field(['m.id', 'm.parent_id', 'm.type', 'm.name', 'm.perms', 'm.paths', 'm.component', 'm.params', 'm.is_cache', 'm.sort'])
                    ->order('m.sort', 'asc')
                    ->select()
                    ->toArray();
            } else {
                $admin->role_menu = Menu::alias('m')
                    ->where('m.status', 1)
                    ->field(['m.id', 'm.parent_id', 'm.type', 'm.name', 'm.perms', 'm.paths', 'm.component', 'm.params', 'm.is_cache', 'm.sort'])
                    ->order('m.sort', 'asc')
                    ->select()
                    ->toArray();
            }
            $role = Role::where('id', $admin->role_id)->find();
            $admin->role_name = $role ? $role->name : '';
            $admin->avatar = $role ? $role->avatar : '';
            $admin->department_name = Department::where('id', $admin->department_id)->value('name');

            //标记需要签到
            AdminModel::where('id', $admin->id)->update(['is_sign' => 1]);
            //如果登录信息中含有client——id则自动进行绑定
            $userInfo = User::where('account', $admin->username)->where('role', '>', 0)->find();
            if(!$userInfo){
                throw new \Exception('用户不存在');
            }
            if(!empty($params['client_id'])){
                $cid = $this->request->header('cid','');
                doBindUid($userInfo['user_id'],$params['client_id'],$cid,$this->request->isMobile());
            }
            $update=[
                'last_login_time' => time(),
                'last_login_ip' => $this->request->ip(),
                'login_count' => Db::raw('login_count+1'),
                'is_online' => 1,
                'chat_num' => 0,
                'is_finished' => 0,
            ];
            User::where('user_id',$userInfo['user_id'])->update($update);
            $userInfo['qrUrl']=getMainHost().'/scan/u/'.encryptIds($userInfo['user_id']);
            unset($userInfo['password'],$userInfo['salt']);
            $userInfo['displayName']=$userInfo['realname'];
            $userInfo['id']=$userInfo['user_id'];
            $authToken=User::refreshToken($userInfo,$param['terminal'] ?? 'web', ['id' => $admin->id, 'role_id' => $admin->role_id]);
            $data=[
                'sessionId'=>Session::getId(),
                'token' => $authToken,
                'userInfo'=>$userInfo,
                'adminInfo' => $admin,
            ];

            //判断是否是客服
            if ($userInfo['role'] == 3) {
                //通知客服签到
                wsSendMsg($userInfo['id'],'sign',['is_sign'=>1]);
                //添加客服登录时间
                KefuTime::addData($admin->id, 4);

                //添加客服在线时间
                KefuTime::addData($admin->id, 2);

                //添加客服上线次数
                KefuWork::addNum($admin->id, 'online_num');
            }
            
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($data, '登录成功');
    }

    //获取是否需要签到
    public function getSign() {
        $is_sign = AdminModel::where('id', $this->admin_id)->value('is_sign');
        return $this->success(['is_sign' => $is_sign]);
    }

    //退出登录
    public function logout(){
        try {
            $jwtData = JWTAuth::auth();
        } catch (\Exception $e) {
            return success(lang('退出成功'));
        }

        $userInfo = $jwtData['info']->getValue();
        //解密token中的用户信息
        $userInfo = str_encipher($userInfo,false, config('app.aes_token_key'));

        if (!$userInfo) {
            return success(lang('退出成功'));
        }
        //解析json
        $userInfo = (array)json_decode($userInfo, true);
        if($userInfo){
            //结束客服服务时间
            KefuTime::endData($this->admin_id, 4);

            // //客服离线后自动结束所有客服会话
            // User::KefuOffline($userInfo['user_id'], $this->admin_id);

            wsSendMsg(0,'isOnline',['id'=>$userInfo['user_id'],'is_online'=>0]);
        }
        JWTAuth::invalidate(JWTAuth::token()->get());
        return success(lang('退出成功'));
    }
}