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

import com.alibaba.fastjson.JSON;
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.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.tzs.api.dto.EquInfoDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.EquipmentCategoryDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.*;
import com.yeejoin.amos.boot.module.tzs.api.enums.EquimentEnum;
import com.yeejoin.amos.boot.module.tzs.api.enums.EquipmentCategoryEnum;
import com.yeejoin.amos.boot.module.tzs.api.enums.EquipmentClassifityEnum;
import com.yeejoin.amos.boot.module.tzs.api.mapper.CategoryOtherInfoMapper;
import com.yeejoin.amos.boot.module.tzs.api.mapper.EquipmentCategoryMapper;
import com.yeejoin.amos.boot.module.tzs.api.mapper.SupervisoryCodeInfoMapper;
import com.yeejoin.amos.boot.module.tzs.api.service.IEquipmentCategoryService;
import com.yeejoin.amos.boot.module.tzs.biz.utils.JsonUtils;
import com.yeejoin.amos.boot.module.tzs.flc.api.feign.IdxFeignService;
import com.yeejoin.amos.boot.module.tzs.flc.api.feign.PrivilegeFeginService;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
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.utils.ResponseModel;

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

/**
 * 装备分类服务实现类
 *
 * @author system_generator
 * @date 2021-10-20
 */
@Service
@Slf4j
public class EquipmentCategoryServiceImpl extends BaseService<EquipmentCategoryDto, EquipmentCategory, EquipmentCategoryMapper> implements IEquipmentCategoryService {

    @Autowired
    EquipmentCategoryMapper equipmentCategoryMapper;

    @Value("classpath:/json/equipCategory.json")
    private Resource equipCategory;

    @Autowired
    private JdbcTemplate bizJdbcTemplate;

    @Autowired
    CategoryOtherInfoMapper categoryOtherInfoMapper;

    @Autowired
    SupervisoryCodeInfoMapper supervisoryCodeInfoMapper;

    @Autowired
    PrivilegeFeginService privilegeFeginService;
    @Autowired
    IdxFeignService idxFeignService;

    @Autowired
    private static  final String TABLENAME="tableName";

    @Value("${regulator.unit.code}")
    private String code;

    @Autowired
    private RedisUtils redisUtils;
    //管辖机构redis缓存key
    private static final String REGULATOR_UNIT_TREE = "REGULATOR_UNIT_TREE";
    //行政区划redis缓存key
    private static final String PROVINCE = "PROVINCE";
    private static final String CITY = "CITY";
    private static final String REGION = "REGION";
    //西安行政区划code
    private static final String XIAN = "610100";
    //判断行政区划查询市还是区
    private static final String END_CODE = "0000";
    //一码通监督管理表单id
    private static final String SUPERVISION_FROM_ID = "1627903532906602497";

    //一码通复制功能url参数key
    private static final String COPY_KEY = "stashType";
    /**
     * 分页查询
     */
    public Page<EquipmentCategoryDto> queryForEquipmentCategoryPage(Page<EquipmentCategoryDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<EquipmentCategoryDto> queryForEquipmentCategoryList() {
        return this.queryForList("", false);
    }

    public List<EquipmentCategoryDto> selectClassify() {
        return equipmentCategoryMapper.selectClassify();
    }

    @Override
    public List<Map<String, Object>> equipTree(String type) {
        List<Map<String, Object>> menus = new ArrayList<>();
        Map<String, List<Map<String, Object>>> resourceJson = JsonUtils.getResourceJson(equipCategory);
        List<Map<String, Object>> mapList;
        if (ValidationUtil.isEmpty(type)) {
            mapList = resourceJson.get(EquipmentClassifityEnum.BDLS.getCode());
        } else {
            mapList = resourceJson.get(type);
        }
        for (Map map : mapList) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("instanceName", map.get("name"));
            resultMap.put("instanceId", map.get("code"));
            menus.add(resultMap);
        }
        return menus;
    }

    @Override
    public Page equipClaimOverview() {
        Page page = new Page<>();
        Map<String, List<Map<String, Object>>> resourceJson = JsonUtils.getResourceJson(equipCategory);
        List<Map<String, Object>> mapList = resourceJson.get(EquipmentClassifityEnum.BDLS.getCode());
        List<Map<String, Object>> list = new ArrayList<>();
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if(ObjectUtils.isEmpty(reginParams)){
            return null;
        }
        String level = reginParams.getUserModel().getCompanys().get(0).getLevel();
        String orgCode = reginParams.getUserModel().getCompanys().get(0).getOrgCode();
        String companyCode = reginParams.getUserModel().getCompanys().get(0).getCompanyCode();
        List<Map<String, Object>> listMap = equipmentCategoryMapper.getCategoryCount(level, orgCode, companyCode);
        for (Map<String, Object> map : mapList) {
            for (Map<String, Object> map1 : listMap) {
                if (map.get("code").equals(map1.get("category"))) {
                    map.put("waitClaim", map1.get("waitClaim"));
                    map.put("alreadyClaim", map1.get("alreadyClaim"));
                    map.put("refuseClaim", map1.get("refuseClaim"));
                    Long sum = Long.valueOf(map1.get("waitClaim").toString()) + Long.valueOf(map1.get("alreadyClaim").toString()) + Long.valueOf(map1.get("refuseClaim").toString());
                    map.put("sum", sum);
                }
            }
            list.add(map);
        }
        page.setCurrent(1);
        page.setTotal(list.size());
        page.setRecords(list);
        return page;
    }

    /**
     * 生成监管码和电梯96333识别码
     */
    @Override
    public Map<String, String> createSupervisorCode(Map<String, Object> map, String record) {
        String city, county, equipCategory;
        EquInfoDto equInfoDto = new EquInfoDto();
        if (ObjectUtils.isEmpty(record)) {
            //获取对应行政区划
            county = EquipmentCategoryEnum.XZQH.getCode();
            city = map.get("regionCode").toString();
            //获取对应设备分类
            equipCategory = map.get("equCategory").toString();
        } else {
            equInfoDto = categoryOtherInfoMapper.selectEquipInfo(record);
            //判断这条数据认领状态是否为已认领,否则直接返回
            if (!ObjectUtils.isEmpty(equInfoDto) && EquipmentCategoryEnum.YRL.getName().equals(equInfoDto.getStatus())) {
                city = equInfoDto.getCity();
                county = equInfoDto.getCounty();
                equipCategory = equInfoDto.getEquipCategory();
            } else {
                return new HashMap<>();
            }
        }
        //生成码
        Map<String, String> codeMap;
        synchronized (EquipmentCategoryServiceImpl.class) {
            codeMap = creatCode(city, county, equipCategory, record);
        }
        if (ObjectUtils.isEmpty(codeMap)) {
            return new HashMap<>();
        }
        log.info(record + "已生成对应监管码或96333电梯识别码");
        String equState = EquipmentCategoryEnum.CSZT.getCode();
        SupervisoryCodeInfo supervisoryCodeInfo = new SupervisoryCodeInfo();
        supervisoryCodeInfo.setCode96333(codeMap.get("code96333"));
        supervisoryCodeInfo.setSupervisoryCode(codeMap.get("superviseCode"));
        supervisoryCodeInfo.setStatus(equState);
        if (!ObjectUtils.isEmpty(record)) {
            String supervisorCode, elevatorCode;
            //设备状态为报废，对应电梯码作废
            equState = EquipmentCategoryEnum.BF.getCode().equals(equInfoDto.getEquState()) ? EquipmentCategoryEnum.WSY.getCode() : EquipmentCategoryEnum.YSY.getCode();
            supervisorCode = codeMap.get("superviseCode");
            elevatorCode = EquipmentCategoryEnum.BF.getCode().equals(equInfoDto.getEquState()) ? null : codeMap.get("code96333");
            List<CategoryOtherInfo> categoryOtherInfo = categoryOtherInfoMapper.selectList(new QueryWrapper<CategoryOtherInfo>().eq("SUPERVISORY_CODE", supervisorCode));
            if (categoryOtherInfo.size() > 0) {
                categoryOtherInfoMapper.updateCode(supervisorCode, equState);
            } else {
                supervisoryCodeInfo.setStatus(equState);
                supervisoryCodeInfoMapper.insert(supervisoryCodeInfo);
            }
            //修改源数据的电梯码
            categoryOtherInfoMapper.updateSupervisorCode(supervisorCode, elevatorCode, record);
        } else {
            supervisoryCodeInfoMapper.insert(supervisoryCodeInfo);
        }
        return codeMap;
    }

    @Override
    public List<LinkedHashMap> getTree() {
        List<LinkedHashMap> result = (List<LinkedHashMap>) redisUtils.get(REGULATOR_UNIT_TREE);
        //判断redis是否存在管辖机构树
        return !ObjectUtils.isEmpty(result) ? result : creatTree();
    }

    @Override
    public List<LinkedHashMap> creatTree() {
        FeignClientResult tree = privilegeFeginService.tree();
        List<LinkedHashMap> result = (List<LinkedHashMap>) tree.getResult();
        List<LinkedHashMap> treeData = deleteRegulatorTreeData(result);
        List<LinkedHashMap> supervisionTree = treeData.stream().filter(e -> code.equals(e.get("orgCode"))).collect(Collectors.toList());
        List<LinkedHashMap> resultTree = updateNullChildren(supervisionTree);
        redisUtils.set(REGULATOR_UNIT_TREE, resultTree);
        return resultTree;
    }

    /**
     * 将管辖机构树中children为[]的修改为null
     * @param result
     * @return
     */
    private List<LinkedHashMap> updateNullChildren(List<LinkedHashMap> result) {
        Iterator it = result.iterator();
        while (it.hasNext()) {
            LinkedHashMap e = (LinkedHashMap) it.next();
            //将管辖机构树中children为[]的修改为null
            if(e.get("children") != null){
                if(((List<LinkedHashMap>) e.get("children")).size() == 0){
                    e.put("children",null);
                }
            }
            if (!ObjectUtils.isEmpty(e.get("children"))) {
                updateNullChildren((List<LinkedHashMap>) e.get("children"));
            }
        }
        return result;
    }

    /**
     * 删除管辖机构树中level为使用单位的数据
     *
     * @param result 管辖机构树
     * @return 筛选过滤后不包含使用单位的管辖机构树
     */
    private List<LinkedHashMap> deleteRegulatorTreeData(List<LinkedHashMap> result) {
        Iterator it = result.iterator();
        while (it.hasNext()) {
            LinkedHashMap e = (LinkedHashMap) it.next();
            //删除使用单位
            if ("company".equals(e.get("level"))) {
                it.remove();
            }
            if(e.get("companyName").toString().contains("行政审批局")){
                it.remove();
            }
            if (!ObjectUtils.isEmpty(e.get("children"))) {
                deleteRegulatorTreeData((List<LinkedHashMap>) e.get("children"));
            }
        }
        return result;
    }


    @Override
    public List<LinkedHashMap> getRegion(String level, String parentId) {
        List<LinkedHashMap> list;
        if (!ObjectUtils.isEmpty(level)) {
            list = (List<LinkedHashMap>) redisUtils.get(PROVINCE);
            return ObjectUtils.isEmpty(list) ? getProvinceList(level) : list;
        } else if (!ObjectUtils.isEmpty(parentId)) {
            String regionCode = parentId.split("_")[0];
            //regionCode以0000结果查询市、否则查询区
            Map<String, Object> map = regionCode.endsWith(END_CODE) ? (Map<String, Object>) redisUtils.get(CITY) : (Map<String, Object>) redisUtils.get(REGION);
            if (ObjectUtils.isEmpty(map)) {
                map = getRegionList();
            }
            list = (List<LinkedHashMap>) map.get(regionCode);
            return list;
        } else {
            return new ArrayList<>();
        }
    }

    public Map<String, Object> getRegionList() {
        //查询省下所有的行政区划市，封装并存入redis
        Map<String, Object> map1 = new HashMap<>();
        List<LinkedHashMap> cityList;
        FeignClientResult tree = privilegeFeginService.getTree();
        List<LinkedHashMap> result = (List<LinkedHashMap>) tree.getResult();
        //获取陕西省regionCode
        String regionCode = ((List<LinkedHashMap>) privilegeFeginService.getProvince("1").getResult()).get(0).get("regionCode").toString();
        cityList = deleteTreeData(result, regionCode);
        Map<String, Object> cityMap = new HashMap<>();
        cityMap.put(regionCode, cityList);
        map1.put(regionCode, cityList);
        redisUtils.set(CITY, cityMap);
        //查询市下所有的行政区划区，封装并存入redis
        if (!ObjectUtils.isEmpty(cityList)) {
            List<LinkedHashMap> region = (List<LinkedHashMap>) privilegeFeginService.getTree().getResult();
            Map<String, Object> map = new HashMap<>();
            for (LinkedHashMap linkedHashMap : cityList) {
                List<LinkedHashMap> regionList = deleteTreeData(region, linkedHashMap.get("regionCode").toString());
                map.put(linkedHashMap.get("regionCode").toString(), regionList);
                map1.put(linkedHashMap.get("regionCode").toString(), regionList);
            }
            redisUtils.set(REGION, map);
        }
        return map1;
    }

    public List<LinkedHashMap> getProvinceList(String level) {
        List<LinkedHashMap> list;
        FeignClientResult result = privilegeFeginService.getProvince(level);
        list = (List<LinkedHashMap>) result.getResult();
        list.get(0).put("sequenceNbr", list.get(0).get("regionCode"));
        redisUtils.set(PROVINCE, list);
        return list;
    }

    @Override
    public Map<String, Object> getCategoryAndDefineByRecord(String record) {
        if (ObjectUtils.isEmpty(record)) {
            return new HashMap<>();
        }
        return equipmentCategoryMapper.getCategoryAndDefineByRecord(record);
    }

    @Override
    public List<CategoryOtherInfo> checkCode(Map<String, Object> obj) {
        List<CategoryOtherInfo> codeList;
        if("save".equals(obj.get("type"))){
            codeList = categoryOtherInfoMapper.selectList(new QueryWrapper<CategoryOtherInfo>().eq("CODE96333", obj.get("CODE96333")));
        } else {
            codeList = categoryOtherInfoMapper.selectList(new QueryWrapper<CategoryOtherInfo>().ne("RECORD",obj.get("id")).eq("CODE96333", obj.get("CODE96333")));
        }
         return codeList;
    }

    @Override
    public List<String> updateOtherInfo(Map<String, Object> map) {
        List<String> supervisoryCodeList = (ArrayList) map.get("supervisoryCode");
        List<String> list = new ArrayList<>();
        for (String supervisoryCode : supervisoryCodeList) {
            CategoryOtherInfo categoryOtherInfo = categoryOtherInfoMapper.selectOne(new QueryWrapper<CategoryOtherInfo>().eq("SUPERVISORY_CODE", supervisoryCode));
            if (ObjectUtils.isEmpty(categoryOtherInfo)) {
                list.add(supervisoryCode + "：对应的数据修改失败，请查询对应监管码是否正确");
            } else {
                list.add(supervisoryCode + (categoryOtherInfoMapper.updateOtherInfo(supervisoryCode, "1") == 1 ? "：对应的数据已经修改成功" : "：对应的数据修改失败，请查询对应监管码是否正确"));
            }
        }
        return list;
    }

    /**
     * 获取行政区划以市或区的list集合
     *
     * @param result 需要删除的源数据
     * @param type   匹配行政区划的regionCode，获取市则需要传省的regionCode，获取区则需要传市的regionCode
     * @return 对应市或区的list集合
     */
    private List<LinkedHashMap> deleteTreeData(List<LinkedHashMap> result, String type) {
        Iterator it = result.iterator();
        List<LinkedHashMap> list = new ArrayList<>();
        while (it.hasNext()) {
            LinkedHashMap e = (LinkedHashMap) it.next();
            //修改数据
            if (type.equals(e.get("parentRegionCode").toString())) {
                e.put("children", null);
                e.put("sequenceNbr", e.get("regionCode"));
                list.add(e);
            }
            if (!ObjectUtils.isEmpty(e.get("children"))) {
                List<LinkedHashMap> children = deleteTreeData((List<LinkedHashMap>) e.get("children"), type);
                list.addAll(children);
            }
        }
        return list;
    }

    /**
     * 具体生成监管码和电梯96333识别码逻辑
     */
    private Map<String, String> creatCode(String city, String county, String equipCategory, String record) {
        Map<String, String> resultMap = new HashMap<>();
        StringBuilder supervisorCode = new StringBuilder();
        StringBuilder elevatorCode = new StringBuilder();
        CategoryOtherInfo otherInfo;
        CategoryOtherInfo categoryOtherInfo = new CategoryOtherInfo();
        String prefix;
        if (equipCategory.startsWith("3") && !XIAN.equals(city)) {
            prefix = getPrefix(EquipmentCategoryEnum.XZQHDT.getCode(), city);
            //查询未使用的电梯码
            categoryOtherInfo = categoryOtherInfoMapper.selectElevatorCode(prefix, EquipmentCategoryEnum.WSY.getCode());
        }
        if (!ObjectUtils.isEmpty(record)) {
            //查询对应record对应数据
            otherInfo = categoryOtherInfoMapper.selectOne(new QueryWrapper<CategoryOtherInfo>().eq("RECORD", record));
            if (!ObjectUtils.isEmpty(otherInfo)) {
                //判断原数据是否存在监管码，存在则用原监管码即可，不存在则生成
                if (!ObjectUtils.isEmpty(otherInfo.getSupervisoryCode())) {
                    supervisorCode = new StringBuilder(otherInfo.getSupervisoryCode());
                } else {
                    String supervisor = createSupervisorCode(city, county, equipCategory);
                    supervisorCode.append(supervisor);
                }
                //判断是否是否需要生成96333电梯码、这个record对应的otherInfo不为空
                if (equipCategory.startsWith("3") && !XIAN.equals(city)) {
                    if (!ObjectUtils.isEmpty(otherInfo.getCode())) {
                        elevatorCode.append(new StringBuilder(otherInfo.getCode()));
                    } else {
                        //如果存在未使用的电梯码则启用未使用的否则创建
                        String elevator = ObjectUtils.isEmpty(categoryOtherInfo) ? createElevatorCode(city, county) : categoryOtherInfo.getCode();
                        elevatorCode.append(elevator);
                    }
                }
            }
        } else {
            String supervisor = createSupervisorCode(city, county, equipCategory);
            supervisorCode.append(supervisor);
            if (equipCategory.startsWith("3") && !XIAN.equals(city)) {
                //如果存在未使用的电梯码则启用未使用的否则创建
                String elevator = ObjectUtils.isEmpty(categoryOtherInfo) ? createElevatorCode(city, county) : categoryOtherInfo.getCode();
                elevatorCode.append(elevator);
            }
        }
        if (ObjectUtils.isEmpty(supervisorCode) && ObjectUtils.isEmpty(elevatorCode)) {
            return new HashMap<>();
        }
        resultMap.put("superviseCode", ObjectUtils.isEmpty(supervisorCode) ? null : supervisorCode.toString());
        resultMap.put("code96333", ObjectUtils.isEmpty(elevatorCode) ? null : elevatorCode.toString());
        resultMap.put("qrCode",ObjectUtils.isEmpty(supervisorCode) ? null : supervisorCode.toString());
        return resultMap;
    }

    private String getPrefix(String type, String county) {
        return equipmentCategoryMapper.getAdministrativeDivision(type, county).get("code").toString();
    }

    /**
     * 生成监管码
     *
     * @param city   行政区划市
     * @param county 行政区划区
     * @return 监管码
     */
    private String createSupervisorCode(String city, String county, String equipCategory) {
        StringBuilder supervisorCode = new StringBuilder();
        //生成监管码前缀
        Map<String, Object> divisionMap = equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQH.getCode(), county);
        String division = ObjectUtils.isEmpty(divisionMap) ? equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQH.getCode(), city).get("code").toString() : divisionMap.get("code").toString();
        supervisorCode.append(division).append(equipCategory).append("-");
        //获取行政区划区县、市是否存在历史监管码
        CategoryOtherInfo supervisor = categoryOtherInfoMapper.selectSupervisorCode(supervisorCode.toString());
        //生成对应监管码
        if (!ObjectUtils.isEmpty(supervisor) && supervisor.getSupervisoryCode() != null) {
            //获取补零位长度
            String supervisoryCode = supervisor.getSupervisoryCode().substring(6);
            long num = Long.valueOf(supervisoryCode) + 1;
            int numLength = String.valueOf(num).length();
            int a = 7 - numLength;
            StringBuilder zero = new StringBuilder();
            for (int i = 0; i < a; i++) {
                zero.append(EquipmentCategoryEnum.BLW.getCode());
            }
            zero.append(num);
            supervisorCode.append(zero);
        } else {
            supervisorCode.append(EquipmentCategoryEnum.JGM.getCode());
        }
        return supervisorCode.toString();
    }

    /**
     * 生成96333电梯识别码
     *
     * @param city   行政区划市
     * @param county 行政区划区
     * @return 96333电梯识别码
     */
    private String createElevatorCode(String city, String county) {
        StringBuilder elevatorCode = new StringBuilder();
        //生成生成96333电梯码前缀
        Map<String, Object> elevatorMap = equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQHDT.getCode(), county);
        String elevator = ObjectUtils.isEmpty(elevatorMap) ? equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQHDT.getCode(), city).get("code").toString() : elevatorMap.get("code").toString();
        elevatorCode.append(elevator);
        //获取行政区划区县、市是否存在历史96333电梯码
        CategoryOtherInfo elevatorOtherInfo = categoryOtherInfoMapper.selectElevatorCode(elevatorCode.toString(), null);
        //生成对应96333电梯码
        if (!ObjectUtils.isEmpty(elevatorOtherInfo) && elevatorOtherInfo.getCode() != null) {
            //获取补零位长度
            String elevatorCode1 = elevatorOtherInfo.getCode().substring(2);
            long num = Long.valueOf(elevatorCode1) + 1;
            int numLength = String.valueOf(num).length();
            int a = 5 - numLength;
            StringBuilder zero = new StringBuilder();
            for (int i = 0; i < a; i++) {
                zero.append(EquipmentCategoryEnum.BLW.getCode());
            }
            zero.append(num);
            elevatorCode.append(zero);
        } else {
            elevatorCode.append(EquipmentCategoryEnum.getValue.get(elevator));
        }
        return elevatorCode.toString();
    }


    /**
     * 获取当前登录人单位类型
     *
     * @return
     */

    public List<JSONObject> getCompanyType() {
        ResponseModel<AgencyUserModel> me = privilegeFeginService.getMe();

        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        List<CompanyModel> companys = reginParams.getUserModel().getCompanys();

        List<JSONObject> objectList = new ArrayList<>();
        for (CompanyModel company : companys) {
            JSONObject object = new JSONObject();
            object.put("level", company.getLevel());
            object.put("orgCode", company.getOrgCode());
            object.put("companyCode", company.getCompanyCode());
            objectList.add(object);
        }
        return objectList;
    }


    @Override
    public Map<String, Map<String, Object>> getFormRecordById(Map<String, Object> map) {
        ResponseModel<Map<String, Map<String, Object>>> responseModel = idxFeignService.getFormRecordById(map);
        Map<String, Map<String, Object>> result = responseModel.getResult();
        if (!ObjectUtils.isEmpty(map.get(COPY_KEY))) {
            result.get(SUPERVISION_FROM_ID).remove("CLAIM_STATUS");
            result.get(SUPERVISION_FROM_ID).remove("CODE96333");
            result.get(SUPERVISION_FROM_ID).remove("SUPERVISORY_CODE");
        }
        return result;
    }

    /**
     * 分页查询数据
     */
    public Page<Map<String, Object>> getPage(Map<String, Object> map) {
        String tableName = map.get(TABLENAME).toString();
        Object sort = map.get("sort");
        Integer number = ValidationUtil.isEmpty(map.get("number")) ? 0 : Integer.valueOf(map.get("number").toString());
        Integer size = ValidationUtil.isEmpty(map.get("size")) ? 0 : Integer.valueOf(map.get("size").toString());

        Page<Map<String, Object>> page = new Page<>(number, size);
        Assert.hasText(tableName, "表名不能为空");
        String selectSql = "SELECT * FROM  " + tableName;
        String countSql = " SELECT COUNT(*) count FROM  " + tableName;

        StringJoiner andJoiner = new StringJoiner(" AND ");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!(entry.getKey().equals("tableName") || entry.getKey().equals("number") || entry.getKey().equals("size") || entry.getKey().equals("sort")) && !ValidationUtil.isEmpty(entry.getValue())) {
                if (!ValidationUtil.isEmpty(entry.getValue()) && entry.getValue().toString().contains("[") && entry.getValue().toString().contains("]")) {
                    String jsonValue = entry.getValue().toString().replace("[", "[\"").replace("]", "\"]").replaceAll(" ", "").replaceAll(",", "\",\"");
                    StringJoiner orJoiner = new StringJoiner(" or ");
                    // 兼容数据库存储String和list格式
                    JSON.parseArray(jsonValue).stream().forEach(x -> {
                        orJoiner.add(entry.getKey() + " like '%" + x + "%'");
                    });
                    andJoiner.add("(" + orJoiner + ")");
                } else {
                    andJoiner.add(entry.getKey() + " like '%" + entry.getValue().toString() + "%'");
                }
            }
        }

        if (!ValidationUtil.isEmpty(andJoiner.toString())) {
            selectSql = selectSql + " WHERE " + andJoiner;
            countSql = countSql + " WHERE " + andJoiner;
        }
        if (!ValidationUtil.isEmpty(sort)) {
            String[] split = sort.toString().split(",");
            selectSql = selectSql + " ORDER BY " + split[0] + (split[1].equals("descend") ? " DESC " : " ASC ");
        }
        int begin = (number - 1) * size;
        if (size > 0) {
            selectSql += " LIMIT " + begin + "," + size;
        }
        Long count = bizJdbcTemplate.queryForObject(countSql, Long.class);
        String finalSelectSql = selectSql;
        List<Map<String, Object>> mapList = bizJdbcTemplate.queryForList(finalSelectSql);
        page.setTotal(count);
        page.setRecords(mapList);

        return page;
    }

    /**
     * levlel=company,是企业,如果不是都是监管单位,
     * * 在接口中查询当前登录人所属单位是监管单位还是企业。
     * * 如果为监管单位添加监管机构查询参数（ORG_BRANCH_CODE）；
     * * 如果为企业添加使用单位查询参数(USE_UNIT_CREDIT_CODE)
     */
    private static final String LEVEL = "company";
    private static final String EQUSTATE = "EQU_STATE";

    public Page<Map<String, Object>> getTable(Map<String, Object> map) {

        if (!ValidationUtil.isEmpty(map.get(EQUSTATE))) {
            map.put(EQUSTATE, EquimentEnum.getCode.get(map.get(EQUSTATE).toString()).toString());
        }
        ResponseModel<Page<Map<String, Object>>> model = new ResponseModel<>();
        List<JSONObject> objectList = getCompanyType();
        List<Map<String, Object>> res = new ArrayList<>();
        Long total = 0L;
        for (JSONObject object : objectList) {
            String level = object.getString("level");
            String code = object.getString("orgCode");
            String companyCode = object.getString("companyCode");
            if (!ValidationUtil.isEmpty(level)) {
                Page<Map<String, Object>> m = new Page<>();
                if (LEVEL.equals(level)) {
                    //企业
                    map.put("USE_UNIT_CREDIT_CODE", companyCode);
                    m = this.getPage(map);
                    map.remove("USE_UNIT_CREDIT_CODE");
                } else {
                    //监管单位
                    map.put("ORG_BRANCH_CODE", code);
                    m = this.getPage(map);
                    map.remove("ORG_BRANCH_CODE");
                }
                total += m.getTotal();
                if (!ValidationUtil.isEmpty(m) &&  !ValidationUtil.isEmpty(m.getRecords())) {
                    res.addAll(m.getRecords());
                }
            }
        }

        Page<Map<String, Object>> objectPage = new Page<>();
        objectPage.setRecords(res);
        objectPage.setTotal(total);
        objectPage.setSize(Long.valueOf(map.get("size").toString()));
        objectPage.setCurrent(Long.valueOf(map.get("number").toString()));
        model.setResult(objectPage);
        //设备状态码对应枚举值
        List<Map<String, Object>> records = model.getResult().getRecords();
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> record : records) {
            if (!ValidationUtil.isEmpty(record.get(EQUSTATE))) {
                Integer integer = Integer.valueOf(record.get(EQUSTATE).toString());
                String status = EquimentEnum.getName.get(integer);
                record.put(EQUSTATE, status);
            }
            result.add(record);
        }
        Page<Map<String, Object>> mapPage = model.getResult().setRecords(result);
        return mapPage;
    }



    public List<Map<String, Object>> scalp(Map<String, Object> map) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (!ValidationUtil.isEmpty(map.get("orgBranchName"))) {
            list = equipmentCategoryMapper.getSrcee(map.get(TABLENAME).toString(),
                    map.get("orgBranchName").toString(), null, null, null, null);
        }
        if (!ValidationUtil.isEmpty(map.get("equList"))) {
            list = equipmentCategoryMapper.getSrcee(map.get(TABLENAME).toString(),
                    null, map.get("equList").toString(), null, null, null);
        }
        if (!ValidationUtil.isEmpty(map.get("equCategory"))) {
            list = equipmentCategoryMapper.getSrcee(map.get(TABLENAME).toString(),
                    null, null, map.get("equCategory").toString(), null, null);
        }
        if (!ValidationUtil.isEmpty(map.get("usePlace"))) {
            list = equipmentCategoryMapper.getSrcee(map.get(TABLENAME).toString(),
                    null, null, null, map.get("usePlace").toString(), null);
        }
        if (!ValidationUtil.isEmpty(map.get("equState"))) {
            list = equipmentCategoryMapper.getSrcee(map.get(TABLENAME).toString(),
                    null, null, null, null, map.get("equState").toString());
        }
        return list;
    }


    /**
     * 设备字典,通过设备父类code,获得子类
     */
    public List<EquipmentCategory> getChildren(String code) {
        LambdaQueryWrapper<EquipmentCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EquipmentCategory::getCode, code);
        EquipmentCategory equipmentCategory = baseMapper.selectOne(wrapper);
        LambdaQueryWrapper<EquipmentCategory> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(EquipmentCategory::getParentId, equipmentCategory.getId());
        List<EquipmentCategory> equipmentCategories = baseMapper.selectList(wrapper2);
        return equipmentCategories;
    }
}