package com.scpyun.platform.jilinsscgsdp.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import com.scpyun.base.core.annotation.Api;
import com.scpyun.base.core.annotation.ApiOperation;
import com.scpyun.base.core.exception.CustomException;
import com.scpyun.base.core.utils.*;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.platform.jilinsscgsdp.bean.vo.ReqSysOfficeVo;
import com.scpyun.platform.jilinsscgsdp.bean.vo.ReqSysUserVo;
import com.scpyun.platform.jilinsscgsdp.bean.vo.SysMenuVo;
import com.scpyun.platform.jilinsscgsdp.constant.NotesConstant;
import com.scpyun.platform.jilinsscgsdp.constant.NumberConstant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author liu
 * @Date 2024/6/19 10:49
 * @PackageName:com.scpyun.platform.jilinsscgsdp.service.impl
 * @ClassName: SysServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Api("测试")
@Service("sysService")
public class SysServiceImpl {
    @Autowired
    CommonService commonService;
    private final String nameSpace = "com.scpyun.platform.standard.jilinsscgsdp.sys.";

    @ApiOperation(value = "树状菜单列表", desc = "树状菜单列表")
    public List<SysMenuVo> selectMenuList(SysMenuVo vo) {
        List<SysMenuVo> rootMenu = new ArrayList<SysMenuVo>();
        if (StringUtils.isEmpty(vo.getParentId())) {
            return rootMenu;
        }
        String ids = vo.getParentId();
        List<String> strList = Arrays.asList(ids.split(","));
        for (int i = 0; i < strList.size(); i++) {
            vo.setId(strList.get(i));
            vo.setParentId(null);
            List<SysMenuVo> firstList = commonService.findList(nameSpace + "selectMenuList", vo);
            vo.setId(null);
            List<SysMenuVo> subList = commonService.findList(nameSpace + "selectMenuList", vo);
            for (SysMenuVo sub : firstList) {
                List<SysMenuVo> childList = this.getChild(String.valueOf(sub.getId()), subList);
                sub.setChildren(childList);
                rootMenu.add(sub);
            }
        }

        return rootMenu;
    }

    @ApiOperation(value = "添加机构", desc = "添加机构")
    public String insertOffice(ReqSysOfficeVo vo) {
        if (!vo.getLabel().equals("其他")){
            if (!vo.getName().contains(vo.getLabel())) {
                throw new CustomException(NotesConstant.OFFICE_EXCEPTION);
            }
        }
        String simpleUUID = IdUtil.simpleUUID();
        vo.setUuid(simpleUUID);
        vo.setCode(commonService.getObject(nameSpace + "getOfficeCode", vo));
        vo.setAreaId(commonService.getObject(nameSpace + "getAreaId", vo));
        if (commonService.insert(nameSpace + "saveOffice", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.INSERT_EXCEPTION);
        }
        if (NumberConstant.ONE_STRING.equals(vo.getUserJurisdiction())) {
            String userId = this.addUser(vo);
            vo.setUserId(userId);
            this.addRole(vo);
        }
        return "success";
    }

    @ApiOperation(value = "添加用户", desc = "添加用户")
    public String insertUser(ReqSysOfficeVo vo) {
        if (!IdcardUtil.isValidCard(vo.getCardno())) {
            throw new CustomException(NotesConstant.CARD_EXCEPTION);
        }
        vo.setUuid(vo.getId());
        String userId = this.addUser(vo);
        vo.setUserId(userId);
        this.addRoleForUser(vo);
        return "success";
    }

    @ApiOperation(value = "修改登录标识")
    public String updateLoginFlagByUserId(Map<String, Object> map) {
        if (!map.containsKey("id")){
            throw new CustomException(NotesConstant.REQUIRED_EXCEPTION);
        }
        if (!map.containsKey("login_flag")){
            throw new CustomException(NotesConstant.REQUIRED_EXCEPTION);
        }
        int update = commonService.update(nameSpace + "updateLoginFlagByUserId", map);
        if (update == NumberConstant.ONE_INT){
            return "success";
        }
        throw new CustomException(NotesConstant.UPDATE_EXCEPTION);
    }

    @ApiOperation(value = "社区添加网格员用户", desc = "社区添加网格员用户")
    public String insertGridUser(ReqSysOfficeVo vo) {
        if (!IdcardUtil.isValidCard(vo.getCardno())) {
            throw new CustomException(NotesConstant.CARD_EXCEPTION);
        }
        vo.setUserName(vo.getName());
        vo.setUuid(vo.get_user().getCompany_id());
        String userId = this.addUser(vo);
        vo.setUserId(userId);
        this.addGridRole(vo);
        return "success";
    }

//    @ApiOperation(value = "视频调用token", desc = "视频调用token")
//    public Object getImToken(ReqImTokenVo vo) {
//        if (StringUtils.isEmpty(vo.getUserId())) {
//            throw new CustomException(NotesConstant.REQUIRED_EXCEPTION);
//        }
//        if (StringUtils.isEmpty(vo.getClientId())) {
//            throw new CustomException(NotesConstant.REQUIRED_EXCEPTION);
//        }
//        Map<String, Object> paramsMap = new HashMap<>();
//        paramsMap.put("userId", vo.getUserId());
//        paramsMap.put("clientId", vo.getClientId());
//        //        paramsMap.put("clientId", "09ec50e0-2dab-4937-a517-7dde206ea3d6");
//        paramsMap.put("platform", NumberConstant.FIVE_INT);
//        return ImUtils.getImToken(paramsMap);
//    }

    @ApiOperation(value = "修改用户", desc = "修改用户")
    public String updateUser(ReqSysUserVo vo) {
        ReqSysOfficeVo office = new ReqSysOfficeVo();
        office.setPhone(vo.getPhone());
        Integer count = commonService.getObject(nameSpace + "getPhone", office);
        if (count >= 1) {
            throw new CustomException(NotesConstant.TEL_REPEAT_EXCEPTION);
        }
        if (commonService.update(nameSpace + "updateUser", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
        }
        return NotesConstant.SAVE_SUCCESS;
    }

    /**
     * 添加用户
     *
     * @param vo
     */
    public String addUser(ReqSysOfficeVo vo) {
        if(vo.get_user().getCompany_grade().equals("6")){ // 社区级账号
            vo.setJobDuty("1");// 只有社区账号添加用户时，才设置job_duty=1(网格员标识)
        }
        String simpleUUID = IdUtil.simpleUUID();
        vo.setUserId(simpleUUID);
        vo.setLoginName(commonService.getObject(nameSpace + "getLoginName", vo));
        Integer count = commonService.getObject(nameSpace + "getPhone", vo);
        if (count >= NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.TEL_REPEAT_EXCEPTION);
        }
        if (commonService.insert(nameSpace + "saveUser", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
        }
        return simpleUUID;
    }

    /**
     * 添加用户权限
     *
     * @param vo
     */
    public void addRole(ReqSysOfficeVo vo) {
        /*List<ReqSysOfficeVo> rolelist = commonService.findList(nameSpace + "selectRoleNameList", vo);
        for (ReqSysOfficeVo role : rolelist) {
            vo.setRoleId(role.getRoleId());
            if (commonService.insert(nameSpace + "addRoleForUsers", vo) != NumberConstant.ONE_INT) {
                throw new CustomException(NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
            }
        }*/
        String company_grade = vo.get_user().getCompany_grade();
        if(company_grade.equals("3")){ // 市级
            vo.setRoleId("1745fcfda7c2435c9c275d1e3a75998c");// 市级横向部门角色id
        }else if(company_grade.equals("4")){// 区级
            vo.setRoleId("792bd07b928e4dfbbce77b2f46924074");// 区级横向部门角色id
        }else if(company_grade.equals("5")){// 街道
            vo.setRoleId("59cb1982717d4e758b183e3648f0e4f4");// 街道级横向部门角色id
        }else if(company_grade.equals("2")){// 省
            vo.setRoleId("6d22cbbd59604ccbb858931416acc9de");// 省级横向部门角色id
        }
        if (commonService.insert(nameSpace + "addRoleForUsers", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
        }
    }

    public void addRoleForUser(ReqSysOfficeVo vo) {
        if(StringUtils.isNotEmpty(vo.getOfficeType()) && vo.getOfficeType().equals("2")){// 添加网格员
            vo.setRoleId("8545188e-2dfc-11ef-af17-f8f21ee9b878");
            if (commonService.insert(nameSpace + "addRoleForUsers", vo) != NumberConstant.ONE_INT) {
                throw new CustomException(NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
            }
        }else{
            List<ReqSysOfficeVo> rolelist = commonService.findList(nameSpace + "selectRoleNameList", vo);
            for (ReqSysOfficeVo role : rolelist) {
                vo.setRoleId(role.getRoleId());
                if (commonService.insert(nameSpace + "addRoleForUsers", vo) != NumberConstant.ONE_INT) {
                    throw new CustomException(NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
                }
            }
        }
    }

    /**
     * 添加网格员用户权限
     *
     * @param vo
     */
    public void addGridRole(ReqSysOfficeVo vo) {
        // 随机获取网格员id
        vo.setId(commonService.getObject(nameSpace + "getUserByIdNew", null));
        // 更具网格员id获取权限集合
        List<ReqSysOfficeVo> rolelist = commonService.findList(nameSpace + "selectRoleList", vo);
        for (ReqSysOfficeVo role : rolelist) {
            vo.setRoleId(role.getRoleId());
            if (commonService.insert(nameSpace + "addRoleForUsers", vo) != NumberConstant.ONE_INT) {
                throw new CustomException(NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
            }
        }
    }

    /**
     * 获取子节点
     *
     * @param id       父节点id
     * @param menuList 所有菜单列表
     * @return 每个根节点下，所有子菜单列表
     */
    private List<SysMenuVo> getChild(String id, List<SysMenuVo> menuList) {
        // 子菜单
        List<SysMenuVo> childList = new ArrayList<SysMenuVo>();
        for (SysMenuVo nav : menuList) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            // 相等说明：为该根节点的子节点。
            if (nav.getParentId().equals(id)) {
                childList.add(nav);
            }
        }
        // 递归
        for (SysMenuVo nav : childList) {
            List<SysMenuVo> subList = this.getChild(nav.getId(), menuList);
            if (subList.size() != NumberConstant.ZERO_INT) {
                nav.setChildren(subList);
            }
        }
        // 如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == NumberConstant.ZERO_INT) {
            return new ArrayList<SysMenuVo>();
        }
        return childList;
    }

    @ApiOperation(value = "添加机构", desc = "添加机构")
    public String createOffice(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("area_id"))) {
            throw new CustomException("区划编码不能为空！");
        }
        if (StringUtils.isEmpty(map.get("name"))) {
            throw new CustomException("机构名称不能为空！");
        }
        if (StringUtils.isEmpty(map.get("parent_id"))) {
            throw new CustomException("父级id不能为空！");
        }
        if (StringUtils.isEmpty(map.get("grade"))) {
            throw new CustomException("机构等级不能为空！");
        }
        if (StringUtils.isEmpty(map.get("sort"))) {
            throw new CustomException("排序不能为空！");
        }
        Map<String,Object>  officeInfo = commonService.getObject(nameSpace + "getOfficeInfoById", new HashMap(){{
            put("id", map.get("parent_id"));
        }});
        if (officeInfo == null || officeInfo.isEmpty()) {
            throw new CustomException("机构信息查询失败");
        }
        Integer count = commonService.getObject(nameSpace+"getAreaCount",map.get("area_id"));
        if (count.equals(0)) {
            throw new CustomException("区划编码无效");
        }
        String parent_id =  "0".equals(StringUtils.toStr(officeInfo.get("id"))) ? "000000000000" : StringUtils.toStr(officeInfo.get("id")) ;
        String parent_ids = "0".equals(parent_id) ? "0" : StringUtils.toStr(officeInfo.get("parent_ids")) + "," + parent_id;
        String code = commonService.getObject(nameSpace + "getOfficeCodeById", new HashMap() {{
            put("sys_area", officeInfo.get("sys_area"));
        }});
        map.put("parent_id", parent_id);
        map.put("parent_ids", parent_ids);
        map.put("code", code);
        map.put("sys_area",  officeInfo.get("sys_area"));
        if (commonService.insert(nameSpace + "createOffice", map) != 1)
            throw new CustomException(9999,NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
        return "success";
    }
    @ApiOperation(value = "添加用户", desc = "添加用户")
    public String createUser(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("company_id"))) {
            throw new CustomException("机构id不能为空！");
        }
        if (StringUtils.isEmpty(map.get("name"))) {
            throw new CustomException("姓名不能为空！");
        }
        Map<String, Object> _user = (Map<String, Object>) map.get("_user");
        String company_grade = StringUtils.toStr(_user.get("company_grade"));
        if("6".equals(company_grade)){ // 社区级账号
            map.put("jobDuty","1");// 只有社区账号添加用户时，才设置job_duty=1(网格员标识)
        }
        String simpleUUID = IdUtil.simpleUUID();
        map.put("id", simpleUUID);
        map.put("office_id", map.get("company_id"));
        String loginName = commonService.getObject(nameSpace + "getLoginNameByComId", new HashMap() {{
            put("company_id", map.get("company_id"));
        }});
        map.put("login_name",loginName);

        if (StringUtils.isNotEmpty(map.get("phone"))) {
            Integer phoneCount = commonService.getObject(nameSpace + "getPhoneCount", new HashMap(){{
                put("phone", map.get("phone"));
            }});
            if (phoneCount > 0) {
                throw new CustomException("手机号重复，请勿重复添加!");
            }
        }

        if (StringUtils.isNotEmpty(map.get("cardno"))) {
            Integer cardnoCount = commonService.getObject(nameSpace + "getCardnoCount", new HashMap(){{
                put("cardno", map.get("cardno"));
            }});
            if (cardnoCount > 0) {
                throw new CustomException("身份证号重复，请勿重复添加!");
            }
        }
        Map<String,Object>  officeInfo = commonService.getObject(nameSpace + "getOfficeInfoById", new HashMap(){{
            put("id", map.get("company_id"));
        }});
        if (officeInfo == null || officeInfo.isEmpty()) {
            throw new CustomException("机构信息查询失败");
        }
        this.addUserRole(StringUtils.toStr(officeInfo.get("grade")), simpleUUID,company_grade);

        if (commonService.insert(nameSpace + "createUser", map) != 1) {
            throw new CustomException(9999,NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
        }
        return loginName;
    }
    public void addUserRole(String grade,String user_id,String company_grade) {
        List<String> roleList = new ArrayList<>();
        switch (grade) {
            case "0":
                roleList.add("035b1402ba384a57b0859c1dd0f905fa");
                roleList.add("eb2c9ea04bdf4ef3abc7eeb5855abaaf");
                break;
            case "2":
                roleList.add("227b160d998e49a1a8d3bdb9ac4e4f11");
                break;
            case "3":
                roleList.add("8545133b-2dfc-11ef-af17-f8f21ee9b878");
                break;
            case "4":
                roleList.add("854516b6-2dfc-11ef-af17-f8f21ee9b878");
                break;
            case "5":
                roleList.add("85451799-2dfc-11ef-af17-f8f21ee9b878");
                break;
            case "6":
                if ("6".equals(company_grade)) {
                    roleList.add("8545188e-2dfc-11ef-af17-f8f21ee9b878");
                } else {
                    roleList.add("85451817-2dfc-11ef-af17-f8f21ee9b878");
                }
                break;
        }
        if (commonService.insert(nameSpace + "insertUserRole",new HashMap<String,Object>(){{
            put("user_id",user_id);
            put("role_list",roleList);
        }}) == 0){
            throw new CustomException(9999, "设置权限失败");
        }
    }
}
