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


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
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.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.enums.UnitDataSourceEnum;
import com.yeejoin.amos.boot.module.statistics.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.statistics.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.statistics.api.entity.TzsBaseInstitution;
import com.yeejoin.amos.boot.module.statistics.api.enums.EnterpriseEnums;
import com.yeejoin.amos.boot.module.statistics.api.enums.ProblemStatusEnum;
import com.yeejoin.amos.boot.module.statistics.api.enums.UnitTypeEnum;
import com.yeejoin.amos.boot.module.statistics.api.feign.AccessFeignService;
import com.yeejoin.amos.boot.module.statistics.api.mapper.EnterpriseBizMapper;
import com.yeejoin.amos.boot.module.statistics.api.mapper.PlanTaskMapper;
import com.yeejoin.amos.boot.module.statistics.api.mapper.TzsBaseInstitutionMapper;
import com.yeejoin.amos.boot.module.ymt.api.dto.BaseUnitLicenceDto;
import com.yeejoin.amos.boot.module.ymt.api.dto.EquipmentCategoryDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.BaseUnitLicence;
import com.yeejoin.amos.boot.module.ymt.api.mapper.BaseUnitLicenceMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.EquipmentCategoryMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.TzBaseEnterpriseInfoMapper;
import com.yeejoin.amos.boot.module.ymt.flc.api.dto.RegUnitIcDto;
import com.yeejoin.amos.boot.module.ymt.flc.api.dto.RegUnitInfoDto;
import com.yeejoin.amos.boot.module.ymt.flc.api.entity.RegUnitIc;
import com.yeejoin.amos.boot.module.ymt.flc.api.entity.RegUnitInfo;
import com.yeejoin.amos.boot.module.ymt.flc.api.mapper.RegUnitIcMapper;
import com.yeejoin.amos.boot.module.ymt.flc.api.mapper.RegUnitInfoMapper;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * @author Administrator
 */
@Service
public class EnterpriseBizByTCMServiceImpl {

    public static final String INSPECTION_AND_TESTING_INSTITUTIONS = "检验检测机构";
    public static final String INSPECTION_AGENCY = "检验机构";
    public static final String TESTING_INSTITUTIONS = "检测机构";

    private RedisUtils redisUtils;

    private StCommonServiceImpl stCommonService;

    private TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper;

    private EnterpriseBizMapper enterpriseBizMapper;

    private TzsBaseInstitutionMapper tzsBaseInstitutionMapper;

    private AccessFeignService accessFeignService;

    private DataDictionaryServiceImpl iDataDictionaryService;

    private BaseUnitLicenceMapper baseUnitLicenceMapper;

    private RegUnitInfoMapper regUnitInfoMapper;

    private RegUnitIcMapper regUnitIcMapper;

    private PlanTaskMapper planTaskMapper;

    private EquipmentCategoryMapper equipmentCategoryMapper;

    public EnterpriseBizByTCMServiceImpl(RedisUtils redisUtils, StCommonServiceImpl stCommonService,
                                         TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper,
                                         EnterpriseBizMapper enterpriseBizMapper,
                                         TzsBaseInstitutionMapper tzsBaseInstitutionMapper,
                                         AccessFeignService accessFeignService,
                                         DataDictionaryServiceImpl iDataDictionaryService,
                                         BaseUnitLicenceMapper baseUnitLicenceMapper,
                                         RegUnitInfoMapper regUnitInfoMapper,
                                         RegUnitIcMapper regUnitIcMapper,
                                         PlanTaskMapper planTaskMapper,
                                         EquipmentCategoryMapper equipmentCategoryMapper) {
        this.redisUtils = redisUtils;
        this.stCommonService = stCommonService;
        this.tzBaseEnterpriseInfoMapper = tzBaseEnterpriseInfoMapper;
        this.enterpriseBizMapper = enterpriseBizMapper;
        this.tzsBaseInstitutionMapper = tzsBaseInstitutionMapper;
        this.accessFeignService = accessFeignService;
        this.iDataDictionaryService = iDataDictionaryService;
        this.baseUnitLicenceMapper = baseUnitLicenceMapper;
        this.regUnitInfoMapper = regUnitInfoMapper;
        this.regUnitIcMapper = regUnitIcMapper;
        this.planTaskMapper = planTaskMapper;
        this.equipmentCategoryMapper = equipmentCategoryMapper;
    }

    // 自定义日期序列化器
    public static class CustomDateSerializer extends JsonSerializer<Date> {
        private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider provider)
                throws IOException {
            gen.writeString(dateFormat.format(value));
        }
    }

    public Map<String, Object> getInfoByUseCodeMap(String useCode) {
        TzBaseEnterpriseInfoDto infoByUseCode = getInfoByUseCode(useCode);
        // 通过sourceId获取问题信息
        Map<String,Object> problemInfo = enterpriseBizMapper.getProblemInfoBySourceId(infoByUseCode.getSequenceNbr().toString());
        ObjectMapper objectMapper = new ObjectMapper();
        // 自定义日期序列化器
        SimpleModule module = new SimpleModule();
        module.addSerializer(Date.class, new CustomDateSerializer());
        objectMapper.registerModule(module);
        // 禁用默认日期格式化
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        Map<String,Object> resultMap = new HashMap<>();

        RegUnitIcDto regUnitIcDto = infoByUseCode.getRegUnitIcDto();
        RegUnitInfoDto regUnitInfoDto = infoByUseCode.getRegUnitInfoDto();
        TzsBaseInstitution tzsBaseInstitution = infoByUseCode.getRegUnitMessage();
        Map<String,Object> regUnitIcDtoMap = new HashMap<>();
        Map<String,Object> regUnitInfoDtoMap = new HashMap<>();
        Map<String,Object> tzsBaseInstitutionMap = new HashMap<>();
        try {
            resultMap = objectMapper.convertValue(infoByUseCode, Map.class);
            regUnitIcDtoMap = objectMapper.convertValue(regUnitIcDto, Map.class);
            regUnitInfoDtoMap = objectMapper.convertValue(regUnitInfoDto, Map.class);
            tzsBaseInstitutionMap = objectMapper.convertValue(tzsBaseInstitution, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(!ObjectUtils.isEmpty(regUnitIcDtoMap)){
            resultMap.putAll(regUnitIcDtoMap);
        }
        if(!ObjectUtils.isEmpty(regUnitInfoDtoMap)){
            regUnitInfoDtoMap.remove("unitLicences");
            resultMap.putAll(regUnitInfoDtoMap);
        }
        if(!ObjectUtils.isEmpty(tzsBaseInstitutionMap)){
            resultMap.putAll(tzsBaseInstitutionMap);
        }
        resultMap.remove("regUnitIcDto");
        resultMap.remove("regUnitInfoDto");
        resultMap.remove("tzsBaseInstitution");

        String unitAddress = "";
        if (StrUtil.isNotBlank(resultMap.get("province")+"") && !"null".equals(resultMap.get("province")+"")){
            unitAddress += resultMap.get("province");
        }
        if (StrUtil.isNotBlank(resultMap.get("city")+"") && !"null".equals(resultMap.get("city")+"")){
            unitAddress += "/" + resultMap.get("city");
        }
        if (StrUtil.isNotBlank(resultMap.get("district")+"") && !"null".equals(resultMap.get("district")+"")){
            unitAddress += "/" + resultMap.get("district");
        }
        // 确保不以斜杠开始
        if (unitAddress.startsWith("/")) {
            unitAddress = unitAddress.substring(1);
        }

        if(StrUtil.isNotBlank(unitAddress)) {
            resultMap.put("unitAddress", unitAddress);
        }

        Map<String,Object> longitudeLatitudeMap = new HashMap<>();
        longitudeLatitudeMap.put("address", resultMap.get("address"));
        longitudeLatitudeMap.put("latitude", resultMap.get("latitude"));
        longitudeLatitudeMap.put("longitude", resultMap.get("longitude"));
        resultMap.put("longitudeLatitude", longitudeLatitudeMap);

        resultMap.put("problemTime", ObjectUtils.isEmpty(problemInfo) ? null : problemInfo.get("problem_time"));
        resultMap.put("problemStatus", (ObjectUtils.isEmpty(resultMap.get("status")) || "null".equals(resultMap.get("status"))) ? ProblemStatusEnum.NORMAL.getName() : ProblemStatusEnum.getName.get(resultMap.get("status")));
        return resultMap;
    }

    public TzBaseEnterpriseInfoDto getInfoByUseCode(String useCode) {
        TzBaseEnterpriseInfo tzBaseEnterpriseInfo = enterpriseBizMapper.queryByUseCode(useCode);
        if (ObjectUtils.isEmpty(tzBaseEnterpriseInfo)) {
            return null;
        }
        TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = getDetail(tzBaseEnterpriseInfo);
        if (!ObjectUtils.isEmpty(tzBaseEnterpriseInfo)){
            LambdaQueryWrapper<TzsBaseInstitution> lambda = new QueryWrapper<TzsBaseInstitution>().lambda();
            lambda.eq(TzsBaseInstitution::getEnterpriseId, tzBaseEnterpriseInfo.getSequenceNbr());
            TzsBaseInstitution tzsBaseInstitution = tzsBaseInstitutionMapper.selectOne(lambda);
            tzBaseEnterpriseInfoDto.setRegUnitMessage(tzsBaseInstitution);
        }
        return ObjectUtils.isEmpty(tzBaseEnterpriseInfo) ? null : tzBaseEnterpriseInfoDto;
    }

    private TzBaseEnterpriseInfoDto getDetail(TzBaseEnterpriseInfo tzBaseEnterpriseInfo){
        TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = detail(tzBaseEnterpriseInfo.getSequenceNbr());
        if(!ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getOfficeRegion())){
            List<Integer> officeRegion = new ArrayList<>();
            for (String s : tzBaseEnterpriseInfo.getOfficeRegion().split("#")) {
                officeRegion.add(Integer.valueOf(s));
            }
            tzBaseEnterpriseInfoDto.setOfficeRegion(officeRegion);
        }
        RegUnitIcDto regUnitIcDto = tzBaseEnterpriseInfoDto.getRegUnitIcDto();
        String creditCode = tzBaseEnterpriseInfoDto.getUseCode();
        if (!ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getRegisterType()) && tzBaseEnterpriseInfo.getRegisterType().contains(UnitTypeEnum.grzt.getName())) {
            // 个人主体时截取证件号码（eg. 6600_210423195703287959 证件类型_证件号码）
            if (creditCode.split("_").length > 1) {
                creditCode = creditCode.split("_")[1];
            }
        }
        // 陕西省内企业从工商平台查询工商信息
        if (UnitDataSourceEnum.SHAANXI.getName().equals(tzBaseEnterpriseInfo.getDataSources())
                && EnterpriseEnums.QY_DW.getTypeName().equals(tzBaseEnterpriseInfo.getRegisterType())) {
            Map<String, Object> resultMap = accessFeignService.getData(creditCode).getResult();
            String area = String.valueOf(resultMap.get("area"));
            String city = area.substring(0, area.indexOf("市") + 1);
            String district = area.substring(city.length());
            if (district.equals("高新区")) {
                district = "雁塔区";
            }
            String industryName = "";
            DataDictionary dataDictionary = iDataDictionaryService.getByCode(String.valueOf(resultMap.get("industryCode")), "HYXLDM");
            if (!ValidationUtil.isEmpty(dataDictionary)) {
                industryName = dataDictionary.getName();
            }
            String approveDate = String.valueOf(resultMap.get("approval_time"));
            approveDate = approveDate.contains("年") ? approveDate.replace("年", "-") : approveDate;
            approveDate = approveDate.contains("月") ? approveDate.replace("月", "-") : approveDate;
            approveDate = approveDate.contains("日") ? approveDate.replace("日", "-") : approveDate;
            regUnitIcDto.setUnitCode(String.valueOf(resultMap.get("creditCode")));
            String approve = approveDate.substring(0, 10) + "核准";
            tzBaseEnterpriseInfoDto.setApproval(approve);
            try {
                regUnitIcDto.setApprovedDate(DateUtils.dateParse(approveDate, "yyyy-MM-dd"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            regUnitIcDto.setUnitName(String.valueOf(resultMap.get("unitName")));
            regUnitIcDto.setRegisteredOrgan(String.valueOf(resultMap.get("registration_authority")));
            for (DataDictionary djjg : iDataDictionaryService.getByType("DJJG")) {
                if(djjg.getName().equals(resultMap.get("registration_authority"))){
                    regUnitIcDto.setRegisteredOrganCode(djjg.getSequenceNbr().toString());
                }
            }
            regUnitIcDto.setBusinessState(String.valueOf(resultMap.get("operating_status")));
            regUnitIcDto.setProvince("陕西省");
            regUnitIcDto.setCity(city);
            regUnitIcDto.setDistrict(district);
            regUnitIcDto.setStree(String.valueOf(resultMap.get("street")));
            regUnitIcDto.setCommunity(String.valueOf(resultMap.get("community")));
            regUnitIcDto.setAddress(String.valueOf(resultMap.get("address")));
            regUnitIcDto.setLegalPerson(String.valueOf(resultMap.get("legalPeople")));
            regUnitIcDto.setIndustryName(industryName);
            regUnitIcDto.setRegisterAddress("陕西省/" + city + "/" + district);
            ArrayList<Object> objects = new ArrayList<>();
            objects.add("陕西省");
            objects.add(city);
            objects.add(district);
            regUnitIcDto.setRegisterAddressList(objects);
            regUnitIcDto.setIsNotAccess("1");
            // 判断是否可以让用户编辑工商及许可信息 事业单位、个人主体或省外企业都可编辑
            tzBaseEnterpriseInfoDto.setCanEdit("0");
            tzBaseEnterpriseInfoDto.setLicenseCanEdit("1");
        } else {
            regUnitIcDto = tzBaseEnterpriseInfoDto.getRegUnitIcDto();
            regUnitIcDto.setIsNotAccess("0");
            List<String> addressList = Lists.newArrayList();
            addressList.add(tzBaseEnterpriseInfo.getProvince());
            addressList.add(tzBaseEnterpriseInfo.getCity());
            addressList.add(tzBaseEnterpriseInfo.getDistrict());
            regUnitIcDto.setRegisterAddressList(addressList);
            // 判断是否可以让用户编辑工商及许可信息 事业单位、个人主体或省外企业都可编辑
            tzBaseEnterpriseInfoDto.setCanEdit("1");
            tzBaseEnterpriseInfoDto.setLicenseCanEdit("1");
        }
        tzBaseEnterpriseInfoDto.setRegUnitIcDto(regUnitIcDto);
        tzBaseEnterpriseInfoDto.setApprovalTime(regUnitIcDto.getApprovedDate());
        return tzBaseEnterpriseInfoDto;
    }


    public TzBaseEnterpriseInfoDto detail(Long id) {
        TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = new TzBaseEnterpriseInfoDto();
        TzBaseEnterpriseInfo tzBaseEnterpriseInfo = enterpriseBizMapper.queryBySeq(String.valueOf(id));
        if (tzBaseEnterpriseInfo != null) {
            BeanUtils.copyProperties(tzBaseEnterpriseInfo, tzBaseEnterpriseInfoDto);
            tzBaseEnterpriseInfoDto.setSafetyTwoPhoto(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getSafetyTwoPhoto()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getSafetyTwoPhoto()));
            tzBaseEnterpriseInfoDto.setSafetyOnePhoto(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getSafetyOnePhoto()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getSafetyOnePhoto()));
            tzBaseEnterpriseInfoDto.setUnitBusinessLicense(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getUnitBusinessLicense()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getUnitBusinessLicense()));
            tzBaseEnterpriseInfoDto.setOtherAccessories(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getOtherAccessories()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getOtherAccessories()));
            tzBaseEnterpriseInfoDto.setUnitExequatur(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getUnitExequatur()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getUnitExequatur()));
            tzBaseEnterpriseInfoDto.setEquipCategory(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getEquipCategory()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getEquipCategory()));
        }

        // 当前用户选择角色的许可信息（使用。。安改维。。检验检测。。）
        List<BaseUnitLicence> unitLicences = baseUnitLicenceMapper.selectList(new LambdaQueryWrapper<BaseUnitLicence>()
                .eq(BaseUnitLicence::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
        List<BaseUnitLicenceDto> unitLicenceDtos = new ArrayList<>();
        List<BaseUnitLicence> unitLicencesCollect;
        if ("监管机构".equals(tzBaseEnterpriseInfoDto.getUnitType())) {
            unitLicencesCollect = unitLicences;
        } else {
            Predicate<BaseUnitLicence> certTypePredicate;
            if (Stream.of(INSPECTION_AGENCY,TESTING_INSTITUTIONS).anyMatch(tzBaseEnterpriseInfoDto.getUnitType()::contains)) {
                certTypePredicate = baseUnitLicence -> INSPECTION_AGENCY.equals(baseUnitLicence.getCertType()) ||
                        TESTING_INSTITUTIONS.equals(baseUnitLicence.getCertType());
            } else {
                certTypePredicate = baseUnitLicence -> tzBaseEnterpriseInfoDto.getUnitType().contains(baseUnitLicence.getCertType());
            }
            unitLicencesCollect = unitLicences.stream()
                    .filter(certTypePredicate)
                    .collect(Collectors.toList());
        }
        if (!ValidationUtil.isEmpty(unitLicencesCollect)) {
            for (BaseUnitLicence baseUnitLicence : unitLicencesCollect) {
                BaseUnitLicenceDto baseUnitLicenceDto = new BaseUnitLicenceDto();
                BeanUtils.copyProperties(baseUnitLicence, baseUnitLicenceDto);
                unitLicenceDtos.add(baseUnitLicenceDto);
            }
        }
        tzBaseEnterpriseInfoDto.setUnitLicences(unitLicenceDtos);
        // 管理员信息
        RegUnitInfo regUnitInfo = regUnitInfoMapper.selectOne(
                new LambdaQueryWrapper<RegUnitInfo>().eq(RegUnitInfo::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
        RegUnitInfoDto regUnitInfoDto = new RegUnitInfoDto();
        if (regUnitInfo != null) {
            BeanUtils.copyProperties(regUnitInfo, regUnitInfoDto);
        }
        regUnitInfoDto.setAdminIdCardPhoto((ValidationUtil.isEmpty(regUnitInfo)||ValidationUtil.isEmpty(regUnitInfo.getAdminIdCardPhoto())) ? new ArrayList() : JSON.parseArray(regUnitInfo.getAdminIdCardPhoto()));
        tzBaseEnterpriseInfoDto.setRegUnitInfoDto(regUnitInfoDto);

        // 工商信息
        RegUnitIc regUnitIc = regUnitIcMapper.selectOne(
                new LambdaQueryWrapper<RegUnitIc>().eq(RegUnitIc::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
        RegUnitIcDto regUnitIcDto = new RegUnitIcDto();
        if (regUnitIc != null) {
            BeanUtils.copyProperties(regUnitIc, regUnitIcDto);
        }
        tzBaseEnterpriseInfoDto.setRegUnitIcDto(regUnitIcDto);
        return tzBaseEnterpriseInfoDto;

    }

    /**
     * 用户选择信心redis获取
     **/
    protected ReginParams getSelectedOrgInfo() {
        return JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
    }


    public Map<String, Object> getTwoRules(Page<Map<String,Object>> page, JSONObject map) {
        Map<String, Object> result = new HashMap<>();
        //查询列表信息
        Page<HashMap<String, Object>> pageList = planTaskMapper.getPlanTaskInfo(page,map);
        //处理userName
        // 2025/04/14 htt 处理了源头的错误数据 故不需要转化了
        // if(!CollectionUtils.isEmpty(pageList.getRecords())) {
        //     Map<String, String> userMap = new HashMap<>();
        //     List<String> userIds = new ArrayList<>();
        //     for (Map<String, Object> record : pageList.getRecords()) {
        //         String ids = record.get("userName")+"";
        //         if (StrUtil.isNotBlank(ids)) {
        //             for (String id : ids.split(",")) {
        //                 userIds.add(id);
        //             }
        //         }
        //     }
        //     if(!CollectionUtils.isEmpty(userIds)){
        //         List<Map<String,String>> userinfoList =planTaskMapper.getUserByUserName(userIds);
        //         for (Map<String, String> userinfo : userinfoList) {
        //             userMap.put(userinfo.get("userName"),userinfo.get("realName"));
        //         }
        //     }
        //     for (Map<String, Object> record : pageList.getRecords()) {
        //         String ids = record.get("userName")+"";
        //         if (StrUtil.isNotBlank(ids)) {
        //             List<String> realNameList = new ArrayList<>();
        //             for (String id : ids.split(",")) {
        //                 if(StrUtil.isNotBlank(userMap.get(id))) {
        //                     realNameList.add(userMap.get(id));
        //                 }
        //             }
        //             if(!CollectionUtils.isEmpty(realNameList)) {
        //                 record.put("userName", realNameList.stream().collect(Collectors.joining(",")));
        //             }else{
        //                 record.put("userName","");
        //             }
        //         }
        //     }
        // }

        result.put("taskList",pageList);
        //查询企业类型
        String unitType = planTaskMapper.getUnitTypeByUseUnitCode(map.getString("useUnitCode"));
        List<Map<String,String>> userinfoList = new ArrayList<>();
        List<Map<String,Object>> userResult = new ArrayList<>();
        //查询人员信息
        if(null != unitType && unitType.contains("使用单位")){
            userinfoList = planTaskMapper.getUserInfo(map.getString("useUnitCode"),true);
            //主要负责人
            Map<String,Object> userMap1 = new HashMap<>();
            userMap1.put("postName","主要负责人");
            userMap1.put("name",new ArrayList<>());
            userMap1.put("postCode","6548");
            //安全总监
            Map<String,Object> userMap2 = new HashMap<>();
            userMap2.put("postName","安全总监");
            userMap2.put("name",new ArrayList<>());
            userMap2.put("postCode","6547");
            //安全员
            Map<String,Object> userMap3 = new HashMap<>();
            userMap3.put("postName","安全员");
            userMap3.put("name",new ArrayList<>());
            userMap3.put("postCode","6549");
            for(int i = 0;i<userinfoList.size();i++){
                String postString = userinfoList.get(i).get("post");
                if(!StrUtil.isEmpty(postString)){
                    JSONArray postArray = JSONArray.parseArray(postString);
                    if(postArray.contains("6548")){
                        ((List)userMap1.get("name")).add(userinfoList.get(i).get("name"));
                    }else if(postArray.contains("6547")){
                        ((List)userMap2.get("name")).add(userinfoList.get(i).get("name"));
                    }else if(postArray.contains("6549")){
                        ((List)userMap3.get("name")).add(userinfoList.get(i).get("name"));
                    }
                }
            }
            userResult.add(userMap1);
            userResult.add(userMap2);
            userResult.add(userMap3);
        }else{
            userinfoList = planTaskMapper.getUserInfo(map.getString("useUnitCode"),false);
            //主要负责人
            Map<String,Object> userMap1 = new HashMap<>();
            userMap1.put("postName","主要负责人");
            userMap1.put("name",new ArrayList<>());
            userMap1.put("postCode","6548");
            //质量安全总监
            Map<String,Object> userMap2 = new HashMap<>();
            userMap2.put("postName","质量安全总监");
            userMap2.put("name",new ArrayList<>());
            userMap2.put("postCode","6550");
            //质量安全员
            Map<String,Object> userMap3 = new HashMap<>();
            userMap3.put("postName","质量安全员");
            userMap3.put("name",new ArrayList<>());
            userMap3.put("postCode","6551");
            for(int i = 0;i<userinfoList.size();i++){
                String postString = userinfoList.get(i).get("post");
                if(!StrUtil.isEmpty(postString)){
                    JSONArray postArray = JSONArray.parseArray(postString);
                    if(postArray.contains("6548")){
                        ((List)userMap1.get("name")).add(userinfoList.get(i).get("name"));
                    }else if(postArray.contains("6550")){
                        ((List)userMap2.get("name")).add(userinfoList.get(i).get("name"));
                    }else if(postArray.contains("6551")){
                        ((List)userMap3.get("name")).add(userinfoList.get(i).get("name"));
                    }
                }
            }
            userResult.add(userMap1);
            userResult.add(userMap2);
            userResult.add(userMap3);
        }
        result.put("person",userResult);
        return result;
    }

    public List<Map<String, Object>> getPlanCheck(String planTaskDetailId) {
        return planTaskMapper.getPlanCheckByPlanTaskDetailId(planTaskDetailId);
    }

    public Page<Map<String,Object>> getPersonPage(JSONObject map, Page page) {
        Page<Map<String, Object>> result = planTaskMapper.getPersonPage(page, map);
        List<EquipmentCategoryDto> equipmentCategoryDtos = equipmentCategoryMapper.selectClassify();
        Map<String,String> equipType = new HashMap<>();
        for(EquipmentCategoryDto dto : equipmentCategoryDtos){
            equipType.put(dto.getCode(),dto.getName());
        }
        for(Map<String,Object> m : result.getRecords()){
            if(StrUtil.isNotEmpty((String) m.get("equipType"))){
                JSONArray array = JSONArray.parseArray(m.get("equipType")+"");
                array.forEach(t->{
                    if(StrUtil.isEmpty((String) m.get("equipTypeName"))){
                        m.put("equipTypeName",equipType.get(t+""));
                    }else{
                        m.put("equipTypeName",m.get("equipTypeName")+"/"+equipType.get(t+""));
                    }
                });
            }
        }
        return result;
    }

    public List<Map<String, Object>> getPostList() {
        return planTaskMapper.getPostList();
    }
}
