<?php


namespace app\admin\service\consultant;


use app\model\Consultant;
use app\model\MarketCustomer;
use app\model\SysDept;
use app\model\SysUser;
use support\Db;
use support\Request;

class ConsultantService
{
    public static function index(Request $request)
    {
        $format = $request->get('format', 'normal');
        $limit = (int)$request->get('pageSize', $format === 'tree' ? 1000 : 10);
        $limit = $limit <= 0 ? 10 : $limit;
        $params = $request->get();
        $page = (int)$request->get('page');
        $page = $page > 0 ? $page : 1;
        $where = [];
        $whereDept = [];
        $whereTopDept = [];
        $deptIds = TeamService::getIdsByUser();
        if (false === $deptIds) {
            //无权限
            $where[] = ['dept_id', '=', 0];
        } else if (is_array($deptIds)) {
            //指定团队下的权限
            $where[] = [function($query) use ($deptIds) {
                $query->whereIn('dept_id', $deptIds);
            }];
        }
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', "%{$params['name']}%"];
        }
        if (!empty($params['mobile'])) {
            $where[] = ['mobile', 'like', "%{$params['mobile']}%"];
        }
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }
        if (!empty($params['dept_id'])) {
            $deptId = end($params['dept_id']);
            $whereDept[] = ['dept_id', '=', $deptId];
            $whereTopDept[] = ['top_dept_id', '=', $deptId];
        }
        if (!empty($params['type'])) {
            $where[] = ['type', '=', $params['type']];
        }
        $paginator = Consultant::where(function ($query) use ($whereDept, $whereTopDept) {
                $query->orWhere($whereDept)
                ->orWhere($whereTopDept);
        })->where($where)->orderBy('id', 'DESC')->paginate($limit, '*', 'page', $page);
        $total = $paginator->total();
        $items = $paginator->items();
        if (!empty($items)) {
            $teamKeys = TeamService::getKeys();
            foreach ($items as &$item) {
                $teamName = [];
                if (isset($teamKeys[$item->top_dept_id])) {
                    $teamName[] = $teamKeys[$item->top_dept_id];
                }
                if (isset($teamKeys[$item->dept_id])) {
                    $teamName[] = $teamKeys[$item->dept_id];
                }
                $item->team_name = !empty($teamName) ? implode('-', $teamName) : '';
            }
        }
        $data = [
            'total' => $total,
            'rows' => $items
        ];
        return json_success('success', $data);
    }

    /**
     * Notes: 添加员工
     * User: yb
     * Date: 2024/8/2
     * Time: 11:03
     * @param $params
     */
    public static function add($params)
    {
        if (!self::checkMobile($params['mobile'])) {
            return json_fail('请输入正确的手机号');
        }
        //查询员工是否已被注册
        if (Consultant::where('mobile', $params['mobile'])->exists()) {
            return json_fail('手机号已存在,员工已被注册');
        }
        //校验密码规则
        if (!empty($params['password'])) {
            $passwordLen = strlen($params['password']);
            if ($passwordLen > 20 || $passwordLen < 6) {
                return json_fail('请输入6-20位密码');
            }
        }
        //查询上级团队
        $topDeptId = SysDept::where('dept_id', $params['dept_id'])->where('dept_category', TeamService::DEPT_CATEGORY)->value('dept_super_id');
        if (!is_numeric($topDeptId)) {
            return json_fail('团队不存在');
        }
        if (empty($params['password'])) {
            $showPassword = substr($params['mobile'], 5);
            $password = self::handlePassword($showPassword);
        } else {
            $password = self::handlePassword($params['password']);
        }
        $type = 2;
        if (!empty($params['type'])) {
            if (in_array($params['type'], [1,2,3,4])) {
                $type = $params['type'];
                if ($type != 1) {
                    $params['relation_user_id'] = null;
                } else {
                    if (empty($params['relation_user_id'])) {
                        return json_fail('请绑定后台账号');
                    }
                }
            }
        }

        $insertData = [
            'name' => $params['name'],
            'mobile' => $params['mobile'],
            'dept_id' => $params['dept_id'],
            'top_dept_id' => $topDeptId,
            'job' => $params['job'] ?? '顾问',
            'gender' => $params['gender'] ?? 1,
            'password' => $password,
            'status' => $params['status'] ?? 1,
            'relation_user_id' => $params['relation_user_id'] ?? null,
            'type' => $type,
            'created_at' => time()
        ];
        $result = Consultant::insert($insertData);
        if ($result) {
            return json_success('新增成功');
        } else {
            return json_fail('新增失败');
        }
    }

    /**
     * Notes: 更新员工信息
     * User: yb
     * Date: 2024/8/2
     * Time: 11:54
     * @param $params
     */
    public static function update($params)
    {
        if (empty($params['id'])) {
            return json_fail('员工id不能为空');
        }
        //查找员工信息
        $info = Consultant::find($params['id']);
        if (empty($info)) {
            return json_fail('员工不存在');
        }
        if (!self::checkMobile($params['mobile'])) {
            return json_fail('请输入正确的手机号');
        }
        //查询员工是否已被注册
        if (Consultant::where('mobile', $params['mobile'])->where('id', '<>', $params['id'])->exists()) {
            return json_fail('手机号已存在,员工已被注册');
        }
        //校验密码规则
        if (!empty($params['password'])) {
            $passwordLen = strlen($params['password']);
            if ($passwordLen > 20 || $passwordLen < 6) {
                return json_fail('请输入6-20位密码');
            }
            $password = self::handlePassword($params['password']);
        }
        $type = 2;
        if (!empty($params['type'])) {
            if (in_array($params['type'], [1,2,3,4])) {
                $type = $params['type'];
                if ($type != 1) {
                    $params['relation_user_id'] = null;
                } else {
                    if (empty($params['relation_user_id'])) {
                        return json_fail('请绑定后台账号');
                    }
                }
            }
        }
        //查询上级团队
        $topDeptId = SysDept::where('dept_id', $params['dept_id'])->where('dept_category', TeamService::DEPT_CATEGORY)->value('dept_super_id');
        if (!is_numeric($topDeptId)) {
            return json_fail('团队不存在');
        }
        $updateData = [
            'name' => $params['name'],
            'mobile' => $params['mobile'],
            'job' => $params['job'] ?? '顾问',
            'gender' => $params['gender'] ?? 1,
            'status' => $params['status'] ?? 1,
            'relation_user_id' => $params['relation_user_id'] ?? null,
            'type' => $type,
            'dept_id' => $params['dept_id'],
            'top_dept_id' => $topDeptId,
            'updated_at' => time()
        ];
        if (!empty($params['password'])) {
            $updateData['password'] = $password;
        }
        Db::beginTransaction();
        try {
            $result = Consultant::where('id', $params['id'])->update($updateData);
            if ($info['dept_id'] != $updateData['dept_id']) {
                //修改员工下客户所属团队
                MarketCustomer::where('consultant_id', $params['id'])->update(['dept_id' => $params['dept_id']]);
            }
            Db::commit();
        }catch (\Exception $e) {
            Db::rollBack();
            return json_fail($e->getMessage());
        }

        if ($result) {
            return json_success('更新成功');
        } else {
            return json_fail('更新失败');
        }
    }

    /**
     * Notes: 删除员工
     * User: yb
     * Date: 2024/8/2
     * Time: 13:33
     * @param $ids
     * @return \support\Response
     */
    public static function delete($ids)
    {
        if (!$ids) {
            return json_fail("数据错误");
        }
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        try {
            if (is_array($ids)) {
                if (MarketCustomer::whereIn('consultant_id', $ids)->exists()) {
                    throw new \Exception('员工下存在客户');
                }
                Consultant::whereIn('id', $ids)->delete();
            } else {
                if (MarketCustomer::where('consultant_id', $ids)->exists()) {
                    throw new \Exception('员工下存在客户');
                }
                Consultant::where('id', $ids)->delete();
            }
        } catch (\Exception $e) {
            return json_fail($e->getMessage());
        }

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

    /**
     * Notes:
     * User: yb
     * Date: 2024/8/5
     * Time: 10:52
     */
    public static function userList()
    {
        $deptIds = TeamService::getIdsByUser();
        $where = [];
        if (false === $deptIds) {
            //无权限
            $where[] = ['join_user_dept_id', '=', 0];
        } else if (is_array($deptIds)) {
            //指定团队下的权限
            $where[] = [function($query) use ($deptIds) {
                $query->whereIn('join_user_dept_id', $deptIds);
            }];
        } else {
            $deptIds = SysDept::where('dept_category', '=', '获客团队')->pluck('dept_id');
            $deptIds = $deptIds->toArray();
            $where[] = [function($query) use ($deptIds) {
                $query->whereIn('join_user_dept_id', $deptIds);
            }];
        }
        $userList = SysUser::where($where)->select(['user_id', 'user_name', 'user_mobile'])->get();
        return json_success('请求成功', $userList);
    }

    /**
     * Notes:校验手机号
     * User: yb
     * Date: 2024/8/2
     * Time: 11:12
     * @param $mobile
     * @return bool
     */
    protected static function checkMobile($mobile)
    {
        if (preg_match('/^1[0-9]\d{9}$/', $mobile)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Notes: 处理密码
     * User: yb
     * Date: 2024/8/2
     * Time: 11:19
     * @param $password
     * @return mixed
     */
    protected static function handlePassword($password)
    {
        return md5(md5($password));
    }

    /**
     * Notes: 处理出生日期
     * User: yb
     * Date: 2024/8/2
     * Time: 11:28
     * @param $birth
     * @return false|string
     */
    protected static function handleBirth($birth)
    {
        return date('Y-m-d',strtotime($birth));
    }

}