<?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 think\facade\Session;

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->where('username', 'like', "%{$params['username']}%");
            }
            if (!empty($params['phone'])) {
                $query->where('phone', 'like', "%{$params['phone']}%");
            }
            $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('用户名已存在');
            }
            if (!empty($id)) {
                AdminModel::where('id', $id)->update($params);
            } else {
                $admin = AdminModel::create($params);

                //插入user
                $params['id'] = $admin->id;
                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('超级管理员不能删除');
            }

            // 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();
            }

            //如果登录信息中含有client——id则自动进行绑定
            $userInfo = User::where('cs_uid', $admin->id)->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')
            ];
            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,
            ];

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($data);
    }
}