<?php

namespace app\admin\controller\sys_manage;

use app\admin\service\sys_manage\DeptService;
use app\admin\service\sys_manage\RoleService;
use app\admin\service\sys_manage\UserService;
use app\admin\validate\sys_manage\UserValidate;
use app\model\Member;
use app\model\SysCategory;
use app\model\SysRole;
use app\model\SysUser;
use support\Request;

class UserController
{
    /**
     * @Desc 用户列表
     * @Author Gorden
     * @Date 2024/2/21 14:46
     *
     * @param Request $request
     * @return \support\Response
     */
    public function userList(Request $request)
    {
        return UserService::userList($request);
    }

    public function selectTeacherList(Request $request)
    {
        return UserService::selectTeacherList($request);
    }

    /**
     * @Desc 用户详情
     * @Author Gorden
     * @Date 2024/2/21 14:53
     *
     * @param $id
     * @return \support\Response
     */
    public function userInfo($id)
    {
        return UserService::userInfo($id);
    }

    /**
     * @Desc 添加用户
     * @Author Gorden
     * @Date 2024/2/21 14:53
     *
     * @param Request $request
     * @return \support\Response
     */
    public function addUser(Request $request)
    {
        $validate = new UserValidate();
        if (!$validate->scene('add')->check($request->post())) {
            return json_fail($validate->getError());
        }
        // 账号是否已存在
        if (UserService::checkUserExist($request->post('user_login_name'))) {
            return json_fail('账号已存在');
        }
        // 部门是否存在
        if (!empty($request->post('join_user_dept_id')) && !DeptService::checkDeptExist($request->post('join_user_dept_id'))) {
            return json_fail('部门不存在');
        }
        // 角色是否存在
        if (!empty($request->post('join_user_role_id')) && !RoleService::checkRoleExist($request->post('join_user_role_id'))) {
            return json_fail('角色不存在');
        }

        return UserService::insertUser($request->post());
    }

    /**
     * @Desc 修改用户
     * @Author Gorden
     * @Date 2024/2/21 14:07
     *
     * @param $id
     * @param Request $request
     * @return \support\Response
     */
    public function updateUser($id, Request $request)
    {
        $validate = new UserValidate();
        if (!$validate->scene('update')->check($request->post())) {
            return json_fail($validate->getError());
        }
        // 部门是否存在
        if (!empty($request->post('join_user_dept_id')) && !DeptService::checkDeptExist($request->post('join_user_dept_id'))) {
            return json_fail('部门不存在');
        }
        // 角色是否存在
        if (!empty($request->post('join_user_role_id')) && !RoleService::checkRoleExist($request->post('join_user_role_id'))) {
            return json_fail('角色不存在');
        }

        return UserService::updateUser($id, $request->post());
    }

    /**
     * @Desc 修改用户状态
     * @Author Gorden
     * @Date 2024/2/21 15:03
     *
     * @param $id
     * @param Request $request
     * @return \support\Response
     */
    public function updateStatus($id, Request $request)
    {
        $validate = new UserValidate();
        if (!$validate->scene('update_status')->check($request->post())) {
            return json_fail($validate->getError());
        }

        return UserService::updateStatus($id, $request->post());
    }

    public function updatePassword($id, Request $request)
    {
        return UserService::updatePassword($id, $request->post());
    }

    /**
     * @Desc 删除用户
     * @Author Gorden
     * @Date 2024/2/21 15:11
     *
     * @param $id
     * @return \support\Response
     */
    public function delUser(Request $request)
    {
        return UserService::delUser($request);
    }

    public function correlationMember(Request $request)
    {
        $memberId = $request->post('member_id', '');
        $userId = $request->post('user_id', '');
        $permission = $request->post('permission', []);
        $manage = $request->post('manage',[]);
        if (!$memberId || !$userId) {
            return json_fail('参数异常');
        }
        try {
            $member = Member::where('member_id', $memberId)->first();
            $memberJson = [];
            if (!empty($member->member_json)) {
                $memberJson = json_decode($member->member_json, true);
                // if(isset($memberJson['user'])){
                //     return json_fail('您选择的会员已被绑定，请选择其他会员');
                // }
            }
            if(!isset($manage['AppAgent']['url'])){
                unset($manage['AppAgent']);
            }
            if(!isset($manage['dayTotalManage']['url'])){
                unset($manage['dayTotalManage']);
            }
            if(!isset($manage['dayTotalPremises']['url'])){
                unset($manage['dayTotalPremises']);
            }

            $memberJson['user'] = [
                'user_id' => $userId,
                'permission' => $permission
            ];
            if(!empty($manage)){
                $memberJson['manage'] = $manage;
            }

            $member->member_json = json_encode($memberJson);
            $member->save();

            return json_success('success');
        } catch (\Exception $e) {
            return json_fail('关联会员失败');
        }
    }

    /**
     * @return \support\Response
     */
    public function selectDoctorList()
    {
        $roleId = SysRole::where('role_name', '医生')->value('role_id');
        $user = SysUser::where('join_user_role_id', $roleId)
            ->select('user_id','user_name')
            ->get();

        return json_success('', $user);
    }

    public function selectSalesmanList(Request $request)
    {
        $keywords = $request->get('keywords','');
        if(!$keywords){
            return json_fail('参数异常');
        }

        $users = SysUser::leftJoin('sys_dept','sys_dept.dept_id','=','sys_user.join_user_dept_id')
            ->where(function($query) use ($keywords){
                $query->where('sys_user.user_name','like','%'.$keywords.'%')
                ->orWhere('sys_user.user_mobile','like','%'.$keywords.'%')
                ->orWhere('sys_dept.dept_name','like','%'.$keywords.'%');
            })->where('sys_dept.dept_name','<>','')
            ->where('sys_dept.dept_category','营业场所')
            
            ->select('sys_user.user_id','sys_user.user_name','sys_user.user_mobile','sys_dept.dept_name')
            ->get()
            ->toArray();

        return json_success('',$users);
    }
}