<?php

namespace app\admin\service\consultant;

use app\model\Consultant;
use app\model\SysDept;
use app\model\SysUser;
use support\Db;
use support\exception\BusinessException;
use support\Request;
use Tinywan\Jwt\JwtToken;

class TeamService
{
    const DEPT_CATEGORY = '获客团队';

    /**
     * @Desc 营销团队详情
     * @Author Gorden
     * @Date 2024/2/21 10:35
     *
     * @param $id
     * @return \support\Response
     */
    public static function deptInfo($id)
    {
        $dept = SysDept::find($id);
        if (!$dept) {
            return json_fail('营销团队不存在');
        }

        $dept = $dept->toArray();
        return json_success('', $dept);
    }

    /**
     * @Desc 创建营销团队
     * @Author Gorden
     * @Date 2024/2/21 9:22
     *
     * @param $params
     * @return \support\Response
     */
    public static function insertDept($params)
    {
        Db::beginTransaction();
        try {
            $data = [
                'dept_category' => self::DEPT_CATEGORY,
                'dept_name' => $params['dept_name'],
                'dept_super_id' => $params['dept_super_id'] ?? 0,
                'dept_status' => $params['dept_status'] ?? 'ACTIVED',
                'dept_sort' => $params['dept_sort'] ?? 1,
                'dept_addtimes' => time()
            ];
            $where = [
                ['dept_category', '=', $data['dept_category']],
                ['dept_name', '=', $data['dept_name']],
                ['dept_super_id', '=', $data['dept_super_id']],
            ];
            $isExist = SysDept::where($where)->first();
            if ($isExist) {
                throw new BusinessException('团队已存在');
            }
            $deptId = SysDept::insertGetId($data);
            if (!$deptId) {
                throw new BusinessException('创建团队失败');
            }
            // 获取上级部门path
            $deptSuperPath = '/0/';
            if ($params['dept_super_id'] != 0) {
                $deptSuperPath = SysDept::where('dept_id', $params['dept_super_id'])->value('dept_super_path');
            }
            // 更新部门path
            $path = $deptSuperPath . $deptId . '/';
            if (!SysDept::where('dept_id', $deptId)->update(['dept_super_path' => $path])) {
                throw new \Exception('创建团队失败');
            }
            Db::commit();
        } catch (BusinessException|\Exception $e) {
            Db::rollBack();
            return json_fail($e->getMessage());
        }

        return json_success('团队创建成功');
    }

    /**
     * @Desc 修改营销团队
     * @Author Gorden
     * @Date 2024/2/21 10:15
     *
     * @param $id
     * @param $params
     * @return \support\Response
     */
    public static function updateDept($params)
    {
        $id = $params['id'];
        $dept = SysDept::where('dept_id', $id)->first();
        if (!$dept) {
            return json_fail('团队不存在');
        }

        try {
            $data = [
                'dept_name' => $params['dept_name'],
                'dept_sort' => $params['dept_sort'] ?? 0,
                'dept_status' => $params['dept_status'] ?? 'ACTIVED',
            ];
            $where = [
                ['dept_category', '=', self::DEPT_CATEGORY],
                ['dept_name', '=', $data['dept_name']],
                ['dept_super_id', '=', $dept['dept_super_id']],
                ['dept_id', '<>', $id],
            ];
            $isExist = SysDept::where($where)->first();
            if ($isExist) {
                throw new BusinessException('团队已存在');
            }
            // 修改失败，异常
            SysDept::where('dept_id', $id)->update($data);

        } catch (BusinessException|\Exception $e) {
            return json_fail($e->getMessage());
        }

        return json_success('修改团队成功');
    }

    /**
     * @Desc 修改营销团队状态
     * @Author Gorden
     * @Date 2024/2/21 10:41
     *
     * @param $id
     * @param $status
     * @return \support\Response
     */
    public static function updateStatus($id, $status)
    {
        try {
            if (!SysDept::where('dept_id', $id)->update(['dept_status' => $status])) {
                throw new \Exception('营销团队状态修改失败');
            }
        } catch (\Exception $e) {
            return json_fail('营销团队状态修改失败');
        }

        return json_success('营销团队状态修改成功');
    }

    /**
     * @Desc 删除营销团队
     * @Author Gorden
     * @Date 2024/2/21 10:48
     *
     * @param $id
     * @return \support\Response
     */
    public static function delDept(Request $request)
    {
        $ids = $request->post('dept_id');
        if (!$ids) {
            return json_fail("数据错误");
        }
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        //查询团队下是否存在员工
        $nums = Consultant::whereIn('dept_id', $ids)->count();
        if ($nums > 0) {
            return json_fail('请清除团队下员工后删除团队');
        }
        //查询团队下是否存在管理账号
        $nums = SysUser::whereIn('join_user_dept_id', $ids)->count();
        if ($nums > 0) {
            return json_fail('请清除团队下管理账号后删除团队');
        }
        try {
            if (is_array($ids)) {
                SysDept::whereIn('dept_id', $ids)->delete();
            } else {
                SysDept::where('dept_id', $ids)->delete();
            }
        } catch (\Exception $e) {
            return json_fail('删除团队失败');
        }

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

    /**
     * @Desc 检查营销团队是否存在
     * @Author Gorden
     * @Date 2024/2/21 13:37
     *
     * @param $deptId
     * @return bool
     */
    public static function checkDeptExist($deptId)
    {
        return SysDept::where('dept_id', $deptId)->exists();
    }

    /**
     * Notes: 上级团队列表
     * User: yb
     * Date: 2024/8/1
     * Time: 17:17
     */
    public static function parentList()
    {
        $deptIds = TeamService::getIdsByUser(1);
        $where = [
            ['dept_category', '=', self::DEPT_CATEGORY],
            ['dept_super_id', '=',  0]
        ];
        if (false === $deptIds) {
            //无权限
            $where[] = ['dept_id', '=', 0];
        } else if (is_array($deptIds)) {
            //指定团队下的权限
            $where[] = [function($query) use ($deptIds) {
                $query->whereIn('dept_id', $deptIds);
            }];
        }
        $list = SysDept::where($where)->select(['dept_id','dept_name'])->get();
        $result = $list->toArray();
        $result[] = [
            'dept_id' => 0,
            'dept_name' => '顶级团队',
        ];
        return json_success('请求成功', $result);
    }

    /**
     * Notes: 获取团队信息 只有名字
     * User: yb
     * Date: 2024/8/2
     * Time: 10:00
     * @return array
     */
    public static function getKeys()
    {
        $data = self::getTeams();
        $keys = [];
        if (!empty($data)) {
            $array = $data->toArray();
            foreach ($array as $item) {
                $keys[$item['dept_id']] = $item['dept_name'];
            }
        }
        return $keys;
    }

    /**
     * Notes: 获取团队信息包含整个item
     * User: yb
     * Date: 2024/8/9
     * Time: 20:31
     */
    public static function getItemKeys()
    {
        $data = self::getTeams();
        $keys = [];
        if (!empty($data)) {
            foreach ($data->toArray() as $item) {
                $keys[$item['dept_id']] = $item;
            }
        }
        return $keys;
    }

    /**
     * Notes: 根据id获取所有的子集
     * User: yb
     * Date: 2024/8/12
     * Time: 11:34
     * @param $id
     */
    public static function getIds($id, $self = 0)
    {
        $where = [
            ['dept_category', '=', self::DEPT_CATEGORY]
        ];
        $deptInfo = SysDept::where('dept_id', $id)->where('dept_category', self::DEPT_CATEGORY)->first();
        $deptSuperPath = $deptInfo->dept_super_path;
        $where[] = ['dept_super_path', 'like', "{$deptSuperPath}%"];
        if ($self == 1) {
            $where[] = ['dept_id', '<>', $id];
        }
        return SysDept::where($where)->pluck('dept_id')->toArray();
    }

    /**
     * Notes: 通过用户获取所有子集
     * User: yb
     * Date: 2024/8/16
     * Time: 16:48
     */
    public static function getIdsByUser($self = 0)
    {
        $userId = JwtToken::getCurrentId();
        $userInfo = SysUser::firstWhere(['user_id' => $userId]);
        $joinUserDeptId = $userInfo->join_user_dept_id;
        //获取部门信息
        $deptInfo = SysDept::firstWhere(['dept_id' => $joinUserDeptId]);
        if (empty($deptInfo)) {
            //无部门信息
            return false;
        }
        if ($deptInfo->dept_category != self::DEPT_CATEGORY) {
            //超管权限
            return true;
        }
        return self::getIds($joinUserDeptId, $self);
    }

    /**
     * Notes: 获取团队完整名称包含所有父集
     * User: yb
     * Date: 2024/8/9
     * Time: 20:43
     * @param $keys
     * @param $id
     * @return string
     */
    public static function getTeamName($keys, $id)
    {
        if (isset($keys[$id])) {
            $path = $keys[$id]['dept_super_path'];
            $array = explode('/', $path);
            array_shift($array);
            array_pop($array);
            $namesArr = [];
            foreach ($array as $item) {
                if (!empty($item)) {
                    if (isset($keys[$item]['dept_name'])) {
                        $namesArr[] = $keys[$item]['dept_name'];
                    }
                }
            }
            $name = implode(' - ', $namesArr);
            return $name;
        }
        return '';
    }

    public static function getTeams()
    {
        $where = [
            ['dept_category', '=', self::DEPT_CATEGORY]
        ];
        $data = SysDept::where($where)->select(['dept_id', 'dept_super_id', 'dept_super_path', 'dept_name'])->get();
        return $data;
    }
}