<?php

namespace app\admin\service\sys_manage;

use app\model\Member;
use app\model\SysUser;
use support\Db;
use support\Request;

class UserService
{
    /**
     * @Desc 用户列表
     * @Author Gorden
     * @Date 2024/2/21 14:46
     *
     * @param $page
     * @param $limit
     * @param $keywords
     * @return \support\Response
     */
    public static function userList(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 10);
        $username = $request->get('username', '');
        $loginName = $request->get('login_name', '');

        $rows = SysUser::with(['role','dept'])
            ->select('join_user_role_id', 'join_user_dept_id', 'user_id', 'user_status', 'user_category', 'user_name', 'user_login_name', 'user_mobile', 'user_remark', 'user_extend_json', 'user_addtimes')
            ->when($username != '', function ($query) use ($username) {
                $query->where('user_name', 'like', '%' . $username . '%');
            })->when($loginName != '', function ($query) use ($loginName) {
                $query->where('user_login_name', 'like', '%' . $loginName . '%');
            })
            ->orderBy('user_addtimes', 'DESC')
            ->forPage($page, $pageSize)
            ->get()
            ->toArray();
        foreach($rows as &$item){
            if(!empty($item['user_extend_json'])){
                $extendJson = json_decode($item['user_extend_json'],true);
                $item['avatar'] = !empty($extendJson['avatar']) ? getenv('STORAGE_DOMAIN').$extendJson['avatar'] : '';
                $item['info'] = $extendJson['info'] ?? '';
            }
            
        }
        $total = SysUser::when($username != '', function ($query) use ($username) {
            $query->where('user_name', 'like', '%' . $username . '%');
        })->count();

        return json_success('', compact('rows', 'page', 'pageSize', 'total'));
    }

    public static function selectTeacherList(Request $request)
    {
        $roleId = "28";
        $user = SysUser::where('join_user_role_id',$roleId)
            ->select('user_id','user_name')
            ->get()
            ->toArray();

        return json_success('',$user);
    }

    /**
     * @Desc 用户详情
     * @Author Gorden
     * @Date 2024/2/21 14:52
     *
     * @param $id
     * @return \support\Response
     */
    public static function userInfo($id)
    {
        $user = SysUser::select('join_user_role_id', 'join_user_dept_id', 'user_status', 'user_category', 'user_name', 'user_login_name', 'user_mobile', 'user_remark', 'user_extend_json', 'user_addtimes')
            ->where('user_id', $id)
            ->first();
        if (!$user) {
            return json_fail('用户不存在');
        }
        $user = $user->toArray();
        $member = Member::with([
            'cert'=>function($query){
                $query->select('join_cert_member_id','member_cert_name');
            }
        ])->whereJsonContains('member_json->user->user_id',$id)
            ->first();
        $memberTitle = $member->cert ? $member->cert->member_cert_name.'-'.$member->member_mobile : $member->member_mobile;
        $user['member_id'] = $member['member_id'];
        $user['memberList'] = [
            [
                'key'=>$member->member_id,
                'value'=>$memberTitle
            ]
        ];
        $user['permission'] = [];
        $user['manage'] = [];
        if(!empty($member->member_json)){
            $memberJson = json_decode($member->member_json,true);
            if(isset($memberJson['user']) && isset($memberJson['user']['permission'])){
                $user['permission'] = $memberJson['user']['permission'];
            }
            if(isset($memberJson['manage'])){
                $user['manage'] = $memberJson['manage'];
            }
        }

        return json_success('', $user);
    }

    /**
     * @Desc 添加用户
     * @Author Gorden
     * @Date 2024/2/21 13:50
     *
     * @param $params
     * @return \support\Response
     */
    public static function insertUser($params)
    {
        try {
            $data = [
                'user_id' => self::generateUserId(),
                'join_user_role_id' => $params['join_user_role_id'] ?? 0,
                'join_user_dept_id' => $params['join_user_dept_id'] ?? 0,
                'user_status' => $params['user_status'] ?? '',
                'user_category' => $params['user_category'] ?? '',
                'user_name' => $params['user_name'] ?? '',
                'user_login_name' => $params['user_login_name'] ?? '',
                'user_login_pass' => md5(sha1($params['user_login_pass'])),
                'user_mobile' => $params['user_mobile'] ?? '',
                'user_remark' => $params['user_remark'] ?? '',
                // 'user_extend_json' => !empty($params['user_extend_json']) ? $params['user_extend_json'] : '{}',
                'user_addtimes' => time()
            ];
            $extendJson['avatar'] = str_replace(getenv('STORAGE_DOMAIN'),'',$params['avatar']);
            $extendJson['info'] = $params['info'] ?? '[]';
            $data['user_extend_json'] = json_encode($extendJson);
            if (!SysUser::insert($data)) {
                throw new \Exception('添加用户失败');
            }
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('添加用户失败');
        }

        return json_success('添加用户成功');
    }

    /**
     * @Desc 修改用户
     * @Author Gorden
     * @Date 2024/2/21 14:06
     *
     * @param $id
     * @param $params
     * @return \support\Response
     */
    public static function updateUser($id, $params)
    {
        try {
            $data = [
                'join_user_role_id' => $params['join_user_role_id'],
                'join_user_dept_id' => $params['join_user_dept_id'],
                'user_login_name' => $params['user_login_name'],
                'user_status' => $params['user_status'],
                'user_category' => $params['user_category'],
                'user_name' => $params['user_name'],
                'user_remark' => $params['user_remark'],
                // 'user_extend_json' => !empty($params['user_extend_json']) ? $params['user_extend_json'] : '{}'
            ];

            $user = SysUser::where('user_id', $id)->first();
            if(!empty($user->user_extend_json)){
                $extendJson = json_decode($user->user_extend_json,true);
            }else{
                $extendJson = [];
            }
            $extendJson['avatar'] = str_replace(getenv('STORAGE_DOMAIN'),'',$params['avatar']);
            $extendJson['info'] = $params['info'];
            $data['user_extend_json'] = json_encode($extendJson);

            // 密码变动
            if (!empty($params['user_login_pass'])) {
                $data['user_login_pass'] = md5(sha1($params['user_login_pass']));
            }
            SysUser::where('user_id', $id)->update($data);
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('修改用户失败');
        }

        return json_success('修改用户成功');
    }

    /**
     * @Desc 修改用户状态
     * @Author Gorden
     * @Date 2024/2/21 15:03
     *
     * @param $id
     * @param $params
     * @return \support\Response
     */
    public static function updateStatus($id, $params)
    {
        try {
            if (!SysUser::where('user_id', $id)->update(['user_status' => $params['user_status']])) {
                throw new \Exception('用户状态修改失败');
            }
        } catch (\Exception $e) {
            return json_fail('用户状态修改失败');
        }

        return json_success('用户状态修改成功');
    }

    /**
     * @Desc 修改密码
     * @Author Gorden
     * @Date 2024/4/19 10:01
     *
     * @param $id
     * @param $params
     * @return \support\Response
     */
    public static function updatePassword($id, $params)
    {
        if ($params['user_login_pass'] != $params['confirmNewPassword']) {
            return json_fail('两次密码不一致');
        }
        $user = SysUser::where('user_id', $id)->first();
        if (md5(sha1($params['userPassword'])) != $user->user_login_pass) {
            return json_fail('原密码错误');
        }
        try {
            SysUser::where('user_id', $id)->update(['user_login_pass' => md5(sha1($params['user_login_pass']))]);

            return json_success('密码修改成功');
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('密码修改失败');
        }
    }

    /**
     * @Desc 删除用户
     * @Author Gorden
     * @Date 2024/2/21 15:11
     *
     * @param $id
     * @return \support\Response
     */
    public static function delUser(Request $request)
    {
        $ids = $request->post('user_id');
        if (!$ids) {
            return json_fail("数据错误");
        }
        try {
            if (is_array($ids)) {
                SysUser::whereIn('user_id', $ids)->delete();
            } else {
                SysUser::where('user_id', $ids)->delete();
            }
        } catch (\Exception $e) {
            return json_fail('删除用户失败');
        }

        return json_success('删除用户成功');
    }

    public static function checkUserExist($account)
    {
        return SysUser::where('user_login_name', $account)->exists();
    }

    public static function generateUserId()
    {
        $random = random_string(4,'up');

        return 'UR' . date('ymdHi') . $random;
    }
}