<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use think\facade\Cookie;
use think\facade\Request;
use think\facade\Config;
use app\model\UserModel;
use app\model\UserRoleModel;
use app\model\UserLoginLogModel;
use app\validate\UserValidate;
use app\service\IpWhiteListService;

class User extends BaseController
{
    protected $message = [
        'logout' => '退出成功',
        'login' => '登录成功',
        'error' => '账号或密码错误',
        'param' => '参数错误',
        'duplicate' => '账号名已存在',
        'create_suc' => '创建账号成功',
        'empty' => '账号不存在',
        'suc' => '操作成功',
        'res' => '获取成功',
        'ip_denied' => 'IP地址不在白名单中，禁止登录'
    ];

    /**
     * 登录
     */
    public function login()
    {
        // 获取输入数据
        $userName = trim(Request::post('user_name', ''));
        $password = trim(Request::post('password', ''));

        // 验证输入数据
        $checkMessage = $this->validateInput([
            'user_name' => $userName,
            'password' => $password,
        ], 'login');

        if(!empty($checkMessage)) {
            return json_error([], $checkMessage);
        }

        // 获取客户端信息
        $clientIp = getClientIp();
        $userAgent = Request::header('user-agent', '');
        
        // 查询用户
        $user = UserModel::where('user_name', $userName)->find();
        
        // 准备登录日志数据
        $loginLogData = [
            'merchant_id' => $user ? $user->merchant_id : 0,
            'user_id' => $user ? $user->user_id : 0,
            'login_device' => $userAgent,
            'login_ip' => $clientIp,
            'login_status' => UserLoginLogModel::STATUS_FAILED
        ];
        
        if ($user && password_verify($password, $user->password)) {
            // 检查IP白名单
            if (!IpWhiteListService::checkIpWhiteList($clientIp, $user->white_list_ip)) {
                // 记录登录失败日志（IP白名单验证失败）
                UserLoginLogModel::recordLogin($loginLogData);
                
                return json_error([
                    'client_ip' => $clientIp,
                    'white_list_ip' => $user->white_list_ip
                ], $this->message['ip_denied']);
            }

            $token = generateToken([
                'user_id' => $user->user_id,
                'merchant_id' => $user->merchant_id,
                'user_role' => $user->user_role
            ]);
            Cookie::set('auth_token', $token, ['expire' => $GLOBALS['cookieExpire'], 'httponly' => true]);
            
            // 更新登录时间
            $user->login_time = time();
            $user->save();
            
            // 记录登录成功日志
            $loginLogData['login_status'] = UserLoginLogModel::STATUS_SUCCESS;
            UserLoginLogModel::recordLogin($loginLogData);

            return json_success([
                'user_name' => $user->user_name,
                'nick_name' => $user->nick_name,
                'login_time' => $user->login_time,
                'token' => $token,
            ], $this->message['login']);
        } else {
            // 记录登录失败日志（密码错误或用户不存在）
            UserLoginLogModel::recordLogin($loginLogData);
            
            return json_error([], $this->message['error']);
        }
    }
    
    /**
     * 用户注销
     */
    public function logout()
    {
        Cookie::delete('auth_token');
        return json_success([], '退出成功');
    }

    /**
     * 创建用户
     */
    public function createUser()
    {
        // 获取当前登录用户信息
        $userInfo = $this->request->userInfo;

        // 获取输入数据
        $data = Request::only([
            'user_name', 'nick_name', 'password', 'phone', 
            'user_role/d', 'white_list_ip'
        ]);
        $data['merchant_id'] = $userInfo['merchant_id'];

        try {
            // 验证数据
            $this->validate($data, UserValidate::class . '.create');
        } catch (\think\exception\ValidateException $e) {
            return json_error($e->getError());
        }

        // 验证Ip白名单格式
        $checkIpWhiteList = IpWhiteListService::validateWhiteListFormat($data['white_list_ip']);
        if ($checkIpWhiteList[0] == false) {
            return json_error($checkIpWhiteList[1]);
        }
        
        // 验证角色是否存在
        if ($data['user_role'] > 0) {
            $role = UserRoleModel::getRoleById($data['user_role'], $userInfo['merchant_id']);
            if (!$role) {
                return json_error([], '选择的角色不存在');
            }
        }

        // 检查账号名是否已存在
        if (UserModel::where('user_name', $data['user_name'])->find()) {
            return json_error($this->message['duplicate']);
        }
        
        // 创建新用户
        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        
        try {
            $user = UserModel::create($data);
            return json_success(['user_id' => $user->user_id], $this->message['create_suc']);
        } catch (\Exception $e) {
            return json_error([], '创建账号失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取账号列表
     */
    public function list()
    {
        $userInfo = $this->request->userInfo;
        
        $page = Request::get('page', 1, 'intval');
        $limit = Request::get('limit', 10, 'intval');
        $userName = Request::get('user_name', '', 'trim');
        $nickName = Request::get('nick_name', '', 'trim');
        $userRole = Request::get('user_role', 0, 'intval');
        
        $where = [
            ['merchant_id', '=', $userInfo['merchant_id']]
        ];
        
        if ($userName) {
            $where[] = ['user_name', 'like', '%' . $userName . '%'];
        }
        
        if ($nickName) {
            $where[] = ['nick_name', 'like', '%' . $nickName . '%'];
        }
        
        if ($userRole > 99) {
            $where[] = ['user_role', '=', $userRole];
        } else {
            $where[] = ['user_role', '>', 99];
        }
        
        $total = UserModel::where($where)->count();
        $list = UserModel::where($where)
            ->field('user_id, user_name, nick_name, phone, user_role, white_list_ip, create_time, login_time, update_time')
            ->order('user_id', 'desc')
            ->page($page, $limit)
            ->select();
            
        // 获取角色信息
        $roleIds = array_unique(array_column($list->toArray(), 'user_role'));
        $roles = [];
        if ($roleIds) {
            $roleList = UserRoleModel::whereIn('id', $roleIds)->select();
            foreach ($roleList as $role) {
                $roles[$role->id] = $role->role_name;
            }
        }
        
        // 添加角色名称
        foreach ($list as $user) {
            $user->role_name = $roles[$user->user_role] ?? '未分配';
        }
        
        return json_success([
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ]);
    }
    
    /**
     * 获取用户详情
     */
    public function detail()
    {
        $userInfo = $this->request->userInfo;
        
        $userId = Request::param('user_id', 0, 'intval');
        if (!$userId)
        {
            $userId = $userInfo['user_id'];
        }
        
        if (!$userId) {
            return json_error([], '账号ID不能为空');
        }
        
        $user = UserModel::where('user_id', $userId)
            ->where('merchant_id', $userInfo['merchant_id'])
            ->field('user_id, user_name, nick_name, phone, user_role, merchant_id, white_list_ip, create_time, login_time, update_time')
            ->find();
            
        if (!$user) {
            return json_error($this->message['empty']);
        }
        
        // 获取角色信息
        if ($user->user_role > 0) {
            if ($user->user_role > 99) {
                $role = UserRoleModel::getRoleById($user->user_role, $userInfo['merchant_id']);
                $user->role_name = $role ? $role->role_name : '未分配';
                $user->role_privileges = $role ? $role->privileges : [];
            } else {
                $user->role_name = '超级管理员';
                $user->role_privileges = [];
            }
        } else {
            $user->role_name = '未分配';
            $user->role_privileges = [];
        }
        
        return json_success($user);
    }
    
    /**
     * 更新用户
     */
    public function update()
    {
        $userInfo = $this->request->userInfo;
        
        $userId = Request::post('user_id', 0, 'intval');
        if (!$userId) {
            return json_error([], '账号ID不能为空');
        }
        
        $user = UserModel::where('user_id', $userId)
            ->where('merchant_id', $userInfo['merchant_id'])
            ->find();
            
        if (!$user) {
            return json_error($this->message['empty']);
        }
        
        // 获取请求中提供的所有可更新字段
        $requestData = Request::post();
        $allowedFields = ['nick_name', 'phone', 'password', 'user_role', 'white_list_ip'];
        $updateData = [];
        
        // 只处理请求中存在且允许更新的字段
        foreach ($allowedFields as $field) {
            if (array_key_exists($field, $requestData)) {
                // 对于密码字段，空值则跳过
                if ($field === 'password' && empty($requestData[$field])) {
                    continue;
                }
                if ($field === 'user_role') {
                    $requestData[$field] = intval($requestData[$field]);
                }
                $updateData[$field] = $requestData[$field];
            }
        }
        
        if (empty($updateData)) {
            return json_error([], '没有要更新的数据');
        }
                
        // 使用验证器进行字段验证  
        $validate = new UserValidate();        
        // 只验证传入的字段
        if (!$validate->only(array_keys($updateData))->check($updateData)) {
            return json_error([], $validate->getError());
        }
        
        // 额外的业务逻辑验证
        // 验证角色是否存在
        if (isset($updateData['user_role']) && $updateData['user_role'] > 99) {
            $role = UserRoleModel::getRoleById($updateData['user_role'], $userInfo['merchant_id']);
            if (!$role) {
                return json_error([], '选择的角色不存在');
            }
        }
        
        // 验证IP白名单格式
        if (isset($updateData['white_list_ip'])) {
            $checkIpWhiteList = IpWhiteListService::validateWhiteListFormat($updateData['white_list_ip']);
            if ($checkIpWhiteList[0] == false) {
                return json_error([], $checkIpWhiteList[1]);
            }
        }
        
        // 密码加密
        if (isset($updateData['password'])) {
            $updateData['password'] = password_hash($updateData['password'], PASSWORD_DEFAULT);
        }
        
        try {
            $user->save($updateData);
            return json_success([], $this->message['suc']);
        } catch (\Exception $e) {
            return json_error([], '更新失败：' . $e->getMessage());
        }
    }
    
    /**
     * 删除用户
     */
    public function delete()
    {
        $userInfo = $this->request->userInfo;
        
        $userId = Request::post('user_id', 0, 'intval');
        if (!$userId) {
            return json_error([], '账号ID不能为空');
        }
        
        if ($userId == $userInfo['user_id']) {
            return json_error([], '不能删除自己');
        }
        
        $user = UserModel::where('user_id', $userId)
            ->where('merchant_id', $userInfo['merchant_id'])
            ->find();
            
        if (!$user) {
            return json_error($this->message['empty']);
        }
        
        try {
            $user->delete();
            return json_success([], '删除成功');
        } catch (\Exception $e) {
            return json_error([], '删除失败：' . $e->getMessage());
        }
    }
    
    /**
     * 验证输入数据
     */
    protected function validateInput(array $data, $scene = '')
    {
        $validate = new UserValidate();

        // 执行场景验证
        if (!$validate->scene($scene)->check($data)) {
            return $validate->getError();
        }
        return "";
    }
}