package com.yeejoin.amos.boot.module.tcm.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.tcm.api.dto.*;
import com.yeejoin.amos.boot.module.tcm.api.entity.*;
import com.yeejoin.amos.boot.module.tcm.api.enums.EquipmentClassifityEnum;
import com.yeejoin.amos.boot.module.tcm.api.enums.PersonManageRoleEnum;
import com.yeejoin.amos.boot.module.tcm.api.enums.TwoStipulateGroupEnum;
import com.yeejoin.amos.boot.module.tcm.api.enums.UnitTypeEnum;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzsBaseIndividualityMapper;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzsUserEquipMapper;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzsUserInfoMapper;
import com.yeejoin.amos.boot.module.tcm.api.service.ITzsUserInfoService;
import com.yeejoin.amos.boot.module.tcm.api.vo.TzsUserInfoVo;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.GroupModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TzsUserInfoServiceImpl extends BaseService<TzsUserInfoDto, TzsUserInfo, TzsUserInfoMapper> implements ITzsUserInfoService {

    @Autowired
    private TzsUserInfoMapper tzsUserInfoMapper;

    @Autowired
    private TzsUserEquipMapper tzsUserEquipMapper;

    @Autowired
    private TzsUserEquipServiceImpl tzsUserEquipService;

    @Autowired
    DataDictionaryServiceImpl iDataDictionaryService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    TzBaseEnterpriseInfoServiceImpl baseEnterpriseInfoService;

    @Autowired
    TzsBaseIndividualityServiceImpl individualityService;

    @Autowired
    TzsBaseIndividualityMapper individualityMapper;

    //企业人员角色
    private final String USER_ROLE = "QYRYJS";
    //企业人员用户组
    private final String ROLE_GROUP = "QYRYYHZ";
    //两个规定用户组-对应企业人员的人员类型前缀
    private final String QYRYGW = "QYRYGW";

    //两个规定用户组-对应企业人员的人员类型前缀
    private final String QYRYGW_NAME = "企业人员类型";
    //平台用户锁定状态
    private final String UNLOCK = "UNLOCK";
    private final String LOCK = "LOCK";

    @Autowired
    AmosRequestContext amosRequestContext;

    @Autowired
    private TzsUserQualificationsServiceImpl tzsUserQualificationsService;

    @Override
    public Page<TzsUserInfoDto> page(TzsUserInfoDto dto, Page<TzsUserInfoDto> page) {
        Page<TzsUserInfoDto> tzsUserInfoDtoPage = tzsUserInfoMapper.selectPageMessage(page, dto);
        tzsUserInfoDtoPage.getRecords().forEach(item -> {
            if (!ObjectUtils.isEmpty(item.getProfile())) {
                List<CommonFile> commonFiles = JSON.parseArray(item.getProfile(), CommonFile.class);
                if (!ObjectUtils.isEmpty(commonFiles)) {
                    item.setProfile(commonFiles.get(0).getUrl());
                }
            }
            if (!ObjectUtils.isEmpty(item.getBirthday())) {
                int age = getAge(item.getBirthday());
                item.setAge(Math.max(age, 0));
            }
        });
        return tzsUserInfoDtoPage;
    }

    public String setPostName(String postKey) {
        JSONArray dictIds = JSON.parseArray(postKey);
        if (dictIds == null || dictIds.isEmpty()) {
            return "";
        }
        LambdaQueryWrapper<DataDictionary> lambda = new QueryWrapper<DataDictionary>().lambda();
        lambda.in(DataDictionary::getSequenceNbr, dictIds);
        List<DataDictionary> dataDictionaries = iDataDictionaryService.getByTypeAndDesc(QYRYGW, QYRYGW_NAME);
        List<DataDictionary> postDataList = dataDictionaries.stream().filter(d -> dictIds.stream().anyMatch(id -> id.toString().equals(d.getSequenceNbr().toString()))).collect(Collectors.toList());
        return postDataList.stream().map(DataDictionary::getName).collect(Collectors.joining(","));
    }


    private int getAge(Date birth) {
        Calendar cal = Calendar.getInstance();
        int thisYear = cal.get(Calendar.YEAR);
        int thisMonth = cal.get(Calendar.MONTH);
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(birth);
        int birthYear = cal.get(Calendar.YEAR);
        int birthMonth = cal.get(Calendar.MONTH);
        int birthdayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        int age = thisYear - birthYear;

        // 未足月
        if (thisMonth <= birthMonth) {
            // 当月
            if (thisMonth == birthMonth) {
                // 未足日
                if (dayOfMonth < birthdayOfMonth) {
                    age--;
                }
            } else {
                age--;
            }
        }
        return age;
    }

    @Override
    public void addQualificationsMessage(String userId, List<TzsUserQualifications> list) {
        list.forEach(item -> {
            item.setUserInfoId(userId);
        });
        tzsUserQualificationsService.saveOrUpdateBatch(list);
    }

    @Override
    public void updateQualificationsMessage(String userId, List<TzsUserQualifications> list) {
        LambdaQueryWrapper<TzsUserQualifications> lambda = new QueryWrapper<TzsUserQualifications>().lambda();
        lambda.eq(TzsUserQualifications::getUserInfoId, userId);
        tzsUserQualificationsService.getBaseMapper().delete(lambda);
        addQualificationsMessage(userId, list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Object[] ids1) {
        LambdaQueryWrapper<TzsUserInfo> lambda = new QueryWrapper<TzsUserInfo>().lambda();
        lambda.in(TzsUserInfo::getSequenceNbr, ids1);
        TzsUserInfo tzsUserInfo = new TzsUserInfo();
        tzsUserInfo.setIsDelete(true);
        tzsUserInfoMapper.update(tzsUserInfo, lambda);
        List<TzsUserInfo> tzsUserInfos = tzsUserInfoMapper.selectList(lambda);
        for (TzsUserInfo userInfo : tzsUserInfos) {
            tzsUserEquipMapper.delete(new QueryWrapper<TzsUserEquip>().eq("user_seq", userInfo.getSequenceNbr()));
            if(!ObjectUtils.isEmpty(userInfo.getAmosUserId())){
                Privilege.agencyUserClient.multDeleteUser(userInfo.getAmosUserId());
                deleteGroupAndPersonRelation(userInfo.getPostName(),userInfo.getAmosUserId());
            }
        }
    }


    @Override
    public void deleteGroupAndPersonRelation(String postName, String amosUserId) {
        String[] split = postName.split(",");
        for (String s : split) {
            if(!ObjectUtils.isEmpty(TwoStipulateGroupEnum.getId.get(s))){
                Privilege.groupUserClient.deleteGroupUser(TwoStipulateGroupEnum.getId.get(s), amosUserId);
            }
        }
    }

    @Override
    public Map<String, Object> getDetail(Long id) {
        Map<String, Object> maps = new HashMap<>();
        TzsUserInfo tzsUserInfo = tzsUserInfoMapper.selectById(id);
        TzsUserInfoVo tzsUserInfoVo = new TzsUserInfoVo();
        BeanUtils.copyProperties(tzsUserInfo, tzsUserInfoVo, "identification", "profile", "post");
        if (!ObjectUtils.isEmpty(tzsUserInfo.getPost())) {
            tzsUserInfoVo.setPost(JSON.parseArray(tzsUserInfo.getPost()));
        }
        if (!ObjectUtils.isEmpty(tzsUserInfo.getEquipType())) {
            tzsUserInfoVo.setEquipType(JSON.parseArray(tzsUserInfo.getEquipType()));
        }
        tzsUserInfoVo.setIdentification(ObjectUtils.isEmpty(tzsUserInfo.getIdentification()) ? null : JSON.parseArray(tzsUserInfo.getIdentification()));
        tzsUserInfoVo.setProfile(ObjectUtils.isEmpty(tzsUserInfo.getProfile()) ? null : JSON.parseArray(tzsUserInfo.getProfile()));
        tzsUserInfoVo.setAppointDoc(ObjectUtils.isEmpty(tzsUserInfo.getAppointDoc()) ? null : JSON.parseArray(tzsUserInfo.getAppointDoc()));
        tzsUserInfoVo.setOtherAccessories(ObjectUtils.isEmpty(tzsUserInfo.getOtherAccessories()) ? null : JSON.parseArray(tzsUserInfo.getOtherAccessories()));
        maps.put("userInfo", tzsUserInfoVo);
//        LambdaQueryWrapper<TzsUserQualifications> lambda = new QueryWrapper<TzsUserQualifications>().lambda();
//        lambda.eq(TzsUserQualifications::getUserInfoId, id);
//        ArrayList<TzsUserQualificationsVo> tzsUserQualificationsVos = new ArrayList<>();
//        List<TzsUserQualifications> list = tzsUserQualificationsService.getBaseMapper().selectList(lambda);
//        list.forEach(item -> {
//            TzsUserQualificationsVo vo = new TzsUserQualificationsVo();
//            BeanUtils.copyProperties(item, vo, "file");
//            vo.setFile(ObjectUtils.isEmpty(item.getFile()) ? new ArrayList() : JSON.parseArray(item.getFile()));
//            tzsUserQualificationsVos.add(vo);
//        });
//        HashMap<String, Object> subForm = new HashMap<>();
//        subForm.put("subForm", tzsUserQualificationsVos);
//        maps.put("qualificationsInfo", subForm);
        return maps;
    }

    @Override
    public boolean BindAccount(Map<String, Object> map) {
        String loginName = map.get("userName").toString();
        String pwd = map.get("password").toString();
        String sequenceNbr = map.get("sequenceNbr").toString();
        String roles = map.get("role").toString();
        String status = map.get("status").toString();
        String roleGroupCode = map.get("roleGroup").toString();
        TzsUserInfo tzsUserInfo = tzsUserInfoMapper.selectById(sequenceNbr);

        FeignClientResult<AgencyUserModel> userResult = null;
        try {
            AgencyUserModel agencyUserModel = new AgencyUserModel();
            agencyUserModel.setUserName(loginName);
            agencyUserModel.setRealName(tzsUserInfo.getName());
            agencyUserModel.setLockStatus(status);
            agencyUserModel.setPassword(pwd);
            agencyUserModel.setRePassword(pwd);
            agencyUserModel.setAgencyCode("tzs");
            agencyUserModel.setMobile(null);

            ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
            if (ObjectUtils.isEmpty(reginParams)) {
                return false;
            }
            Long companySeq = reginParams.getCompany().getSequenceNbr();
            List<String> appCodesSet = reginParams.getUserModel().getAppCodes();
            List<RoleModel> allRoleList = new ArrayList<>();
            List<Long> roleIds = new ArrayList<>();
            DataDictionary unitType = iDataDictionaryService
                    .getOne(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getCode, roles).eq(DataDictionary::getType, USER_ROLE));
            String role = unitType.getExtend() != null ? unitType.getExtend() : "";
            for (String s : role.split(",")) {
                RoleModel roleModel = Privilege.roleClient.seleteOne(Long.valueOf(s)).getResult();
                allRoleList.add(roleModel);
            }
            allRoleList.forEach(r -> {
                if (!roleIds.contains(r.getSequenceNbr())) {
                    roleIds.add(r.getSequenceNbr());
                }
            });

            //添加人员管理角色

            String post = tzsUserInfo.getPost();
            if(post.contains(PersonManageRoleEnum.code.getId().toString())){
                String companyType = tzsUserInfoMapper.selectCompanyTypeById(companySeq);
                if(companyType.contains(PersonManageRoleEnum.jyjc.getName())){
                    roleIds.add(PersonManageRoleEnum.jyjc.getId());
                }
                if(companyType.contains(PersonManageRoleEnum.use.getName())){
                    roleIds.add(PersonManageRoleEnum.use.getId());
                }
                if(companyType.contains(PersonManageRoleEnum.agw.getName())){
                    roleIds.add(PersonManageRoleEnum.agw.getId());
                }
            }

            Map<Long, List<Long>> roleSeqMap = new HashMap<>();
            Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
            roleSeqMap.put(companySeq, roleIds);
            orgRoles.put(companySeq, allRoleList);
            agencyUserModel.setAppCodes(new ArrayList<>(appCodesSet));
            agencyUserModel.setOrgRoles(orgRoles);
            agencyUserModel.setOrgRoleSeqs(roleSeqMap);
            userResult = Privilege.agencyUserClient.create(agencyUserModel);
            if (userResult.getStatus() == 200) {

                tzsUserInfo.setAmosUserId(userResult.getResult().getUserId());
                tzsUserInfo.setAmosUserName(userResult.getResult().getUserName());
                tzsUserInfo.setLockStatus(status);
                //绑定企业整改用户组
                List<String> userIds = new ArrayList<>();
                userIds.add(userResult.getResult().getUserId());
                DataDictionary roleGroup = iDataDictionaryService
                        .getOne(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getCode, roleGroupCode).eq(DataDictionary::getType, ROLE_GROUP));
                if (!ObjectUtils.isEmpty(roleGroup) && roleGroup.getExtend() != null) {
                    Privilege.groupUserClient.create(Long.valueOf(roleGroup.getExtend()), userIds);
                }
                //绑定两个规定用户组
                post = post.replace("[", "").replace("]", "").replace("\"", "");
                for (String code : post.split(",")) {
                    DataDictionary groupId = iDataDictionaryService
                            .getOne(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getCode, code).likeRight(DataDictionary::getType, QYRYGW));
                    if (!ObjectUtils.isEmpty(groupId) && groupId.getExtend() != null) {
                        Privilege.groupUserClient.create(Long.valueOf(groupId.getExtend()), userIds);
                    }
                }
                tzsUserInfoMapper.updateById(tzsUserInfo);
            }
            return true;
        } catch (Exception e) {
            if (userResult != null && userResult.getResult() != null
                    && StringUtils.isNotEmpty(userResult.getResult().getUserId())) {
                Privilege.agencyUserClient.multDeleteUser(userResult.getResult().getUserId());
            }
            log.error(e.getMessage(), e);
            throw new BadRequest(e.getMessage());
        }

    }

    @Override
    public String startOrStopAccount(Map<String, Object> map) {
        Long sequenceNbr = Long.valueOf(map.get("sequenceNbr").toString());
        String amosUserId = map.get("amosUserId").toString();
        String lockStatus = null;
        FeignClientResult<List<String>> userResult = null;
        if (UNLOCK.equals(map.get("lockStatus"))) {
            userResult = Privilege.agencyUserClient.lockUsers(amosUserId);
            lockStatus = 200 == userResult.getStatus() ? LOCK : UNLOCK;
        } else {
            userResult = Privilege.agencyUserClient.unlockUsers(amosUserId);
            lockStatus = 200 == userResult.getStatus() ? UNLOCK : LOCK;
        }
        if (!ObjectUtils.isEmpty(lockStatus)) {
            TzsUserInfo tzsUserInfo = new TzsUserInfo();
            tzsUserInfo.setSequenceNbr(sequenceNbr);
            tzsUserInfo.setLockStatus(lockStatus);
            tzsUserInfoMapper.updateById(tzsUserInfo);
        }
        return userResult.getResult().get(0);
    }

    @Override
    public List<Map<String, Object>> getEquipmentType(String creditCode) {
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        LambdaQueryWrapper<TzBaseEnterpriseInfo> lambda = new QueryWrapper<TzBaseEnterpriseInfo>().lambda();
        lambda.eq(TzBaseEnterpriseInfo::getUseCode, creditCode);
        List<TzBaseEnterpriseInfo> tzBaseEnterpriseInfos = baseEnterpriseInfoService.getBaseMapper().selectList(lambda);
        if (!ObjectUtils.isEmpty(tzBaseEnterpriseInfos) && !ObjectUtils.isEmpty(tzBaseEnterpriseInfos.get(0).getEquipCategory())) {
            String equipCategory = tzBaseEnterpriseInfos.get(0).getEquipCategory();
            JSONArray objects = JSON.parseArray(equipCategory);
            for (Object object : objects) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("code", object);
                map.put("name", EquipmentClassifityEnum.getEnumByCode(object.toString()).getName());
                maps.add(map);
            }
            return maps;
        }
        return new ArrayList<>();
    }

    @Override
    public Map<String, Integer> getArrangementStatistic(String companyCode) {
        return tzsUserInfoMapper.getArrangementStatistic(companyCode);
    }

    @Override
    public Map<String, Object> getCompanyType() {
        Map<String, Object> result = new HashMap<>();
        result.put("companyType", null);
        List<CompanyModel> companyModels = FeignUtil.remoteCall(() -> Privilege.companyClient.queryListByChild(RequestContext.getExeUserId()));
        if (companyModels.isEmpty()) {
            return result;
        }
        result.put("creditCode", companyModels.get(0).getCompanyCode());
        boolean productCompany = false;
        boolean useCompany = false;
        boolean installCompany = false;
        boolean inspectionCompany = false;
        for (CompanyModel companyModel : companyModels) {
            String companyType = companyModel.getCompanyType();
            if (companyType.contains("使用单位") || companyType.contains("个人主体")) {
                useCompany = true;
            }
            if (companyType.contains("充装单位") || companyType.contains("安装改造维修单位") || companyType.contains("制造单位") || companyType.contains("设计单位")) {
                productCompany = true;
            }
            if (companyType.contains("安装改造维修单位")){
                installCompany = true;
            }
            if (companyType.contains("检验检测机构")){
                inspectionCompany = true;
            }
        }
        StringBuilder companyType = new StringBuilder();
        if (useCompany) {
            companyType.append("use-");
        }
        if (productCompany) {
            companyType.append("pro-");
        }

        if (installCompany) {
            companyType.append("install-");
        }
        if (inspectionCompany) {
            companyType.append("inspection");
        }
        result.put("companyType", companyType);
        return result;
    }

    @Override
    public Page<TzsEquipListDto> getEquipList(String type, String userSeq, TzsEquipListDto dto, Page<TzsEquipListDto> page) {
        List<CompanyModel> companyModels = FeignUtil.remoteCall(() -> Privilege.companyClient.queryListByChild(RequestContext.getExeUserId()));
        if (companyModels.isEmpty()) {
            throw new BadRequest("未指定人员归属单位信息");
        }
        String companyCode = companyModels.get(0).getCompanyCode();
        Page<TzsEquipListDto> tzsUserInfoDtoPage;
        tzsUserInfoDtoPage = tzsUserInfoMapper.getAllEquipList(page, type, companyCode, userSeq, dto);
        return tzsUserInfoDtoPage;
    }

    @Override
    public Boolean equipBind(String type, String userSeq, String creditCode, Map<String, Object> map) {
        Object recordList = map.get("ids");
        List<String> ids = (List<String>) recordList;
        List<TzsUserEquip> tzsUserEquipList = new ArrayList<>();
        boolean flag = false;
        if ("bind".equals(type)) {
            for (String equipId : ids) {
                TzsUserEquip tzsUserEquip = new TzsUserEquip();
                tzsUserEquip.setEquipId(equipId);
                tzsUserEquip.setUserSeq(userSeq);
                tzsUserEquip.setCreditCode(creditCode);
                tzsUserEquipList.add(tzsUserEquip);
            }
            flag = tzsUserEquipService.saveBatch(tzsUserEquipList);
        } else if ("untie".equals(type)) {
            int num = tzsUserEquipMapper.delete(new QueryWrapper<TzsUserEquip>().eq("user_seq", userSeq).in("equip_id", ids));
            flag = num > 0 ? true : flag;
        }
        return flag;
    }

    @Override
    public List<TzsUserInfo> getSafetyList(String companyCode) {
        return tzsUserInfoMapper.selectList(new QueryWrapper<TzsUserInfo>().eq("unit_code", companyCode).eq("is_delete",false).like("post", 6549));
    }

    @Override
    public List<Map<String, Object>> getGroupList() {
        FeignClientResult<Collection<GroupModel>> collectionFeignClientResult = Privilege.groupClient.selectForList(1712370734598221825L, null);
        Collection<GroupModel> GroupModelResult = collectionFeignClientResult.getResult();
        List<GroupModel> collect = GroupModelResult.stream().filter(e -> "twoStipulate".equals(e.getGroupDesc())).collect(Collectors.toList());
        List<Map<String, Object>> result = new ArrayList<>();
        for (GroupModel groupModel : collect) {
            Map<String, Object> map = new HashMap<>();
            map.put("groupName", groupModel.getGroupName());
            map.put("sequenceNbr", groupModel.getSequenceNbr());
            result.add(map);
        }
        return result;
    }

    @Override
    public Map<String, Object> getPersonType() {
        String userId = RequestContext.getExeUserId();
        if (ObjectUtils.isEmpty(userId)) {
            return null;
        }
        String postName = tzsUserInfoMapper.selectPostNameByUserId(userId);
        Map<String, Object> result = new HashMap<>();
        result.put("postName", ObjectUtils.isEmpty(postName) ? null : postName);
        return result;
    }

    @Override
    public List<GroupAndPersonInfoDto> getGroupAndPersonInfo(Long groupId) {

        List<GroupAndPersonInfoDto> result = new ArrayList<>();
        List<GroupAndPersonInfoDto> groupAndPersonInfoDtoList = tzsUserInfoMapper.getUnitInfoByUserId(groupId);
        DataDictionary dataDictionary = iDataDictionaryService.getByExtend(groupId.toString(), QYRYGW);
        for (GroupAndPersonInfoDto groupAndPersonInfoDto : groupAndPersonInfoDtoList) {
            if (!ObjectUtils.isEmpty(groupAndPersonInfoDto)) {
                groupAndPersonInfoDto.setGroupName(ObjectUtils.isEmpty(dataDictionary) ? null : dataDictionary.getName());
                String[] UnitType = groupAndPersonInfoDto.getUnitType().split(",");
                if (UnitType.length > 0) {
                    StringBuilder unitTypeCode = new StringBuilder();
                    for (String s : UnitType) {
                        unitTypeCode.append(UnitTypeEnum.getCode.get(s)).append(",");
                    }
                    groupAndPersonInfoDto.setUnitTypeCode(unitTypeCode.substring(0, unitTypeCode.length() - 1));
                } else {
                    groupAndPersonInfoDto.setUnitTypeCode(UnitTypeEnum.getCode.get(UnitType));
                }

                if (!ObjectUtils.isEmpty(groupAndPersonInfoDto.getEquipCategory())) {
                    String EquipCategory = groupAndPersonInfoDto.getEquipCategory()
                            .replace("[", "")
                            .replace("]", "")
                            .replace("\"", "");
                    List<String> equipCategoryList = Arrays.asList(EquipCategory.split(","));
                    if (equipCategoryList.size() > 0) {
                        StringBuilder equipCategoryCode = new StringBuilder();
                        StringBuilder equipCategory = new StringBuilder();
                        for (String s : equipCategoryList) {
                            equipCategoryCode.append(s).append(",");
                            equipCategory.append(EquipmentClassifityEnum.getName.get(s)).append(",");
                        }
                        groupAndPersonInfoDto.setEquipCategory(equipCategory.substring(0, equipCategory.length() - 1));
                        groupAndPersonInfoDto.setEquipCategoryCode(equipCategoryCode.substring(0, equipCategoryCode.length() - 1));
                    } else {
                        groupAndPersonInfoDto.setEquipCategory(EquipmentClassifityEnum.getName.get(equipCategoryList.get(0)));
                        groupAndPersonInfoDto.setEquipCategoryCode(equipCategoryList.get(0));
                    }
                } else {
                    groupAndPersonInfoDto.setEquipCategory(null);
                    groupAndPersonInfoDto.setEquipCategoryCode(null);
                }
                result.add(groupAndPersonInfoDto);
            }
        }
        return result;
    }

    @Override
    public Boolean createUnitPerson() {
        List<TzsUserInfo> result = tzsUserInfoMapper.getUnitPersonInfo();
        return this.saveBatch(result);
    }


    @Override
    public void testGroup(String groupSeq) {
        List<String> userIds = tzsUserInfoMapper.selectUserIds();
        Privilege.groupUserClient.create(Long.valueOf(groupSeq), userIds);
    }


    @Override
    public List<Map<String, Object>> getUserType(String unitType) {
        List<String> type = new ArrayList<>();
        type.add("QYRYGW");
        if (unitType.contains("use")) {
            type.add("QYRYGW-SYDW");
        }
        if (unitType.contains("pro")) {
            type.add("QYRYGW-SCDW");
        }
        if (unitType.contains("install")) {
            type.add("QYRYGW-INSTALL");
        }
        if (unitType.contains("inspection")) {
            type.add("QYRYGW-INSPECTION");
        }
        return tzsUserInfoMapper.getUserTypeList(type);
    }

    public List<LinkedHashMap> screenData(List<LinkedHashMap> result, List<LinkedHashMap> data, String id) {
        if (!ObjectUtils.isEmpty(result)) {
            return result;
        }
        List<LinkedHashMap> list = data.stream().filter(item -> item.get("sequenceNbr").toString().equals(id)).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(list)) {
            return list;
        }
        for (LinkedHashMap item : data) {
            if (!ObjectUtils.isEmpty(item.get("children"))) {
                List<LinkedHashMap> children = screenData(result, (List<LinkedHashMap>) item.get("children"), id);
                if (!ObjectUtils.isEmpty(children)) {
                    result = children;
                    break;
                }
            }
        }
        return result;
    }

    @Override
    public TzIndividualityDto getIndividualityInfo() {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        AgencyUserModel userModel = reginParams.getUserModel();
        CompanyBo companyBo = reginParams.getCompany();
        TzIndividualityDto individuality = new TzIndividualityDto();
        TzBaseEnterpriseInfoDto baseEnterpriseInfoDto = baseEnterpriseInfoService.getInfoByUseCode(companyBo.getCompanyCode());
        if (!ValidationUtil.isEmpty(baseEnterpriseInfoDto)) {
            individuality = individualityMapper.getIndividualityInfo(baseEnterpriseInfoDto.getSequenceNbr());
            individuality.setPhone(userModel.getMobile());
            individuality.setGoverningBody(baseEnterpriseInfoDto.getGoverningBody());
            individuality.setAddress(baseEnterpriseInfoDto.getAddress());
        }
        return individuality;
    }

    @Transactional
    @Override
    public TzIndividualityDto updateIndividualityInfo(TzIndividualityDto individualityDto) {
        TzsBaseIndividuality individuality = new TzsBaseIndividuality();
        TzBaseEnterpriseInfo baseEnterpriseInfo = baseEnterpriseInfoService.getById(individualityDto.getEnterpriseId());
        if (!ValidationUtil.isEmpty(baseEnterpriseInfo)) {
            BeanUtils.copyProperties(individualityDto, individuality);
            // 更新tz_base_individuality信息
            individuality.setRealName(individualityDto.getName());
            individualityService.saveOrUpdate(individuality);

            // 更新tz_base_enterprise_info信息
            baseEnterpriseInfo.setAddress(individualityDto.getAddress());
            baseEnterpriseInfo.setContactPhone(individualityDto.getPhone());
            baseEnterpriseInfo.setUseContact(individualityDto.getName());
            baseEnterpriseInfoService.updateById(baseEnterpriseInfo);
            // 更新privilege_agency_user手机号
            ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
            AgencyUserModel userModel = reginParams.getUserModel();
            if (!userModel.getMobile().equals(individualityDto.getPhone())) {
                userModel.setMobile(individualityDto.getPhone());
                Privilege.agencyUserClient.modifyMobile(userModel, userModel.getUserId());
            }
        }
        return individualityDto;
    }
}
