java 中动态查询通用

package com.sf.gis.taskmanage.factor.controller;

import com.sf.gis.common.constants.RedisConstant;
import com.sf.gis.common.domain.dto.factor.*;
import com.sf.gis.common.domain.vo.AppTagVo;
import com.sf.gis.common.domain.vo.factor.FactorFieldValueDicVo;
import com.sf.gis.common.domain.vo.factor.FactorListVo;
import com.sf.gis.common.domain.vo.factor.FactorMetaNewVo;
import com.sf.gis.common.domain.vo.factor.FactorMetaVo;
import com.sf.gis.common.result.JsonResponse;
import com.sf.gis.taskmanage.factor.service.FactorService;
import io.swagger.v3.oas.annotations.Operation;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xxx
 * @since 2023-10-13
 */
@RestController
@RequestMapping("/factor")
public class FactorController {

    @Autowired
    private FactorService factorManagementService;

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 获取要素管理必选字段和查询返回必选字段
     *
     * @param
     * @return
     */
    @PostMapping("/getFieldByMeta")
    public JsonResponse<FactorMetaVo> getFieldByMeta(@RequestBody FactorMetaQuery factorMetaQuery) {
        FactorMetaVo factorMetaVo = factorManagementService.getFieldByMeta(factorMetaQuery);
        return JsonResponse.ok(factorMetaVo);
    }

    @PostMapping("/getOuterTableEnumValue")
    public JsonResponse<List<FactorFieldValueDicVo>> getOuterTableEnumValue(@RequestBody FactorFieldQuery query) {
        return JsonResponse.ok(factorManagementService.getOuterTableEnumValue(query));
    }
    @PostMapping("/getFieldByMetaNew")
    public JsonResponse<FactorMetaNewVo> getFieldByMetaNew(@RequestBody FactorMetaQuery factorMetaQuery) {
        FactorMetaNewVo factorMetaVo = factorManagementService.getFieldByMetaNew(factorMetaQuery);
        return JsonResponse.ok(factorMetaVo);
    }

    /**
     * 查询要素管理列表
     *
     * @param
     * @return
     */
    @PostMapping("/getFactorList")
    public JsonResponse<FactorListVo> getFactorList(@RequestBody FactorQuery query) {
        FactorListVo factorList = factorManagementService.getFactorList(query);
        return JsonResponse.ok(factorList);
    }

    /**
     * 查询要素管理列表(新需求,结合人楼房一起查)
     *
     * @param
     * @return
     */
    @PostMapping("/getFactorListNew")
    public JsonResponse<FactorListVo> getFactorListNew(@RequestBody FactorQuery query) {
        FactorListVo factorList = factorManagementService.getFactorListNew(query);
        return JsonResponse.ok(factorList);
    }

    /**
     * 查询字段可选下拉值和字典值
     *
     * @param
     * @return
     */
    @PostMapping("/getValuesByFieldName")
    public JsonResponse<List<FactorFieldValueDicVo>> getValuesByFieldName(@RequestBody FactorFieldQuery query) {
        List<FactorFieldValueDicVo> factorList = factorManagementService.getValuesByFieldName(query);
        return JsonResponse.ok(factorList);
    }

    /**
     * 获取标签表值
     */
    @PostMapping("/getTags")
    public JsonResponse<List<AppTagVo>> getTags(@RequestBody FactorFieldQuery query) {
        List<AppTagVo> tags = factorManagementService.getTags(query.getLayerMetaTagtable());
        return JsonResponse.ok(tags);
    }

    /**
     * 修改默认查询条件和默认查询结果
     *
     * @param
     * @return
     */
    @PostMapping("/updateField")
    @Operation(summary = "修改要素默认条件")
    public JsonResponse updateField(@RequestBody FactorUpdateParam param) {
        factorManagementService.updateField(param);
        return JsonResponse.ok("success");
    }

    /**
     * 发送验证码
     *
     * @param
     * @return
     */
    @PostMapping("/sendVerificationCode")
    @Operation(summary = "发送验证码")
    public JsonResponse sendVerificationCode() {
        Object object= factorManagementService.sendVerificationCode();
        return JsonResponse.ok(object);
    }

    /**
     * 导出
     *
     * @param
     * @return
     */
    @PostMapping("/exportFactorList")
    public void exportFactorList(HttpServletResponse response, @RequestBody FactorExportParam query) throws Exception{
        factorManagementService.exportFactorList(response,query);
    }

}

11111111111111111

package com.sf.gis.taskmanage.factor.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.sf.gis.common.domain.dto.factor.*;
import com.sf.gis.common.domain.vo.AppTagVo;
import com.sf.gis.common.domain.vo.factor.FactorFieldValueDicVo;
import com.sf.gis.common.domain.vo.factor.FactorListVo;
import com.sf.gis.common.domain.vo.factor.FactorMetaNewVo;
import com.sf.gis.common.domain.vo.factor.FactorMetaVo;
import com.sf.gis.common.entity.FactorPlan;
import com.sf.gis.taskmanage.factor.mapper.FactorPlanMapper;
import org.apache.ibatis.annotations.Param;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public interface FactorService {
    FactorMetaVo getFieldByMeta(FactorMetaQuery factorMetaQuery);

    FactorMetaNewVo getFieldByMetaNew(FactorMetaQuery factorMetaQuery);

    FactorListVo getFactorList(FactorQuery query);

    FactorListVo getFactorListNew(FactorQuery query);

    List<FactorFieldValueDicVo> getValuesByFieldName(FactorFieldQuery query);

    List<AppTagVo> getTags(String tagTable);

    void updateField(FactorUpdateParam param);

    Object sendVerificationCode();

    void exportFactorList(HttpServletResponse response, FactorExportParam query)throws Exception;

    List<FactorFieldValueDicVo> getOuterTableEnumValue(FactorFieldQuery query);
}

2222222222222222222

package com.sf.gis.common.domain.vo.factor;

import com.sf.gis.common.entity.base.AppTagEntity;
import lombok.Data;

import java.util.List;

@Data
public class FactorMetaVo {

    /**
     * 主题视图名
     */
    private String layerMetaTagView;

    /**
     * 主题表名
     */
    private String layerMetaTableName;

    /**
     * 主题标签表
     */
    private String layerMetaTagtable;

    /**
     * 查询过滤可选字段
     */
    List<FactorFieldVo> filterFieldList;

    /**
     * 查询过滤可选标签
     */
    List<AppTagEntity> filterTagList;

    /**
     * 查询过滤字段
     */
    List<FactorFieldVo> filterList;

    /**
     * 查询结果字段
     */
    List<FactorFieldVo> showList;

    /**
     * 查询结果可选字段
     */
    List<FactorFieldVo> showFieldList;

    /**
     * 查询结果可选标签
     */
    List<AppTagEntity> showTagList;
}

   @Override
    public FactorMetaVo getFieldByMeta(FactorMetaQuery factorMetaQuery) {
        UserLoginVo userLoginVo = userSystemService.getUserByToken();
        if (userLoginVo == null) {
            throw new BusinessException("当前登录用户信息为空!");

        }
        if (StringUtils.isBlank(factorMetaQuery.getLayerMetaLayername())) {
            throw new BusinessException("要素主题不能为空!");
        }
        String factorType = factorMetaQuery.getLayerMetaLayername();
        FactorPlan factorPlan = factorPlanMapper.getUserByLayer(userLoginVo.getUserId(), factorMetaQuery.getLayerMetaLayername());
        if (StringUtils.isBlank(FmTcBelongTypeEnum.getValueByCode(factorMetaQuery.getLayerMetaLayername()))) {
            throw new BusinessException("参数错误!");
        } else {
            factorMetaQuery.setLayerMetaLayername(FmTcBelongTypeEnum.getValueByCode(factorMetaQuery.getLayerMetaLayername()));
        }
        AnalysisLayerMetaEntity analysisLayerMeta = analysisLayerMetafieldMapper.getViewNameByLayerName(factorMetaQuery.getLayerMetaLayername());
        if (Objects.isNull(analysisLayerMeta)) {
            return null;
        }

        FactorMetaVo result = new FactorMetaVo();
        // 设置视图表名
        result.setLayerMetaTagView(analysisLayerMeta.getLayerMetaTagview());
        result.setLayerMetaTableName(analysisLayerMeta.getLayerMetaTablename());
        result.setLayerMetaTagtable(analysisLayerMeta.getLayerMetaTagtable());
        // 获取必选和可选字段 (包括查询条件和结果字段)
        List<AnalysisLayerMetafield> metafieldEntityList = analysisLayerMetafieldMapper.getFactorByMeta(analysisLayerMeta.getLayerMetaId());
        // 获取必选和可选标签 (包括查询条件和结果标签)
        List<AppTag> appTagList = appTagMapper.getFactorTagByTable(analysisLayerMeta.getLayerMetaTagtable());
        // 设置查询必选条件字段
        // 查询过滤可选字段
        List<FactorFieldVo> filterFieldList = new ArrayList<>();
        // 查询过滤可选标签
        List<AppTag> filterTagList = new ArrayList<>();
        // 查询过滤字段
        List<FactorFieldVo> filterList = new ArrayList<>();
        // 查询结果字段
        List<FactorFieldVo> showList = new ArrayList<>();
        // 查询结果可选字段
        List<FactorFieldVo> showFieldList = new ArrayList<>();
        // 查询结果可选标签
        List<AppTag> showTagList = new ArrayList<>();
        if (Objects.nonNull(factorPlan)) {
            if (Objects.nonNull(factorPlan.getFilterContent())) {
                String filterStr = factorPlan.getFilterContent();
                List<FactorFieldVo> fieldVoList = JSON.parseArray(JSON.toJSON(filterStr).toString(), FactorFieldVo.class);

                Set<String> fieldNames = fieldVoList.stream().filter(s -> Objects.equals("1", s.getType()) && !Objects.equals(1, s.getLayerFactorShow()))
                        .map(FactorFieldVo::getFieldName)
                        .collect(Collectors.toSet());
                Set<String> tagNames = fieldVoList.stream().filter(s -> Objects.equals("2", s.getType()) && !Objects.equals(1, s.getLayerFactorShow()))
                        .map(FactorFieldVo::getFieldName)
                        .collect(Collectors.toSet());
                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                    metafieldEntityList.stream().forEach(metafield -> {
                        Integer index = metafield.getLayerFactorIsStat();
                        if(null!=index) {
                            if (fieldNames.contains(metafield.getLayerMetafieldName())) {
                                // 在必选字段
                                index = 2;
                            }
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, index, null);
                            factorFieldVo.setLayerFactorShow(index);
                            factorFieldVo.setFactorType(factorType);
                            filterFieldList.add(factorFieldVo);
                        }
                    });
                }
                if (CollectionUtils.isNotEmpty(appTagList)) {
                    appTagList.stream().forEach(appTag -> {
                        Integer index = appTag.getTagFactorIsStat();
                                if(null!=index) {
                                    if (tagNames.contains(appTag.getTagCol())) {
                                        // 在必选字段
                                        index = 2;
                                    }
                                    // 这里注意(直接在app_tag中赋值,是弱引用,会在下一个循环中值覆盖,所以这里new了一个新对象,不会被下面的show循环覆盖值)
                                    AppTag filterTag = getAppTag(appTag, index);
                                    filterTag.setFactorType(factorType);
                                    filterTagList.add(filterTag);
                                }
                    });
                }
                filterList.addAll(fieldVoList);
//                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
//                    // 默认字段也自动显示
//                    metafieldEntityList.forEach(metafield -> {
//                        if (Objects.equals(1, metafield.getLayerFactorIsStat())) {
//                            if (filterList.stream().noneMatch(show -> show.getFieldName().equals(metafield.getLayerMetafieldName()))) {
//                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 1, null);
//                                factorFieldVo.setFactorType(factorType);
//                                filterList.add(factorFieldVo);
//                            }
//                            if (filterFieldList.stream().noneMatch(show -> show.getFieldName().equals(metafield.getLayerMetafieldName()))) {
//                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 1, null);
//                                factorFieldVo.setFactorType(factorType);
//                                factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
//                                filterFieldList.add(factorFieldVo);
//                            }
//                        }
//                    });
//                }
            } else {
                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                    metafieldEntityList.stream().forEach(metafield -> {
                        if (Objects.equals(1, metafield.getLayerFactorIsStat())) {
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 1, null);
                            factorFieldVo.setFactorType(factorType);
                            filterList.add(factorFieldVo);
                            factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                            filterFieldList.add(factorFieldVo);
                        } else if (Objects.equals(0, metafield.getLayerFactorIsStat())) {
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 0, null);
                            factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                            factorFieldVo.setFactorType(factorType);
                            filterFieldList.add(factorFieldVo);
                        }
                    });
                }
                if (CollectionUtils.isNotEmpty(appTagList)) {
                    appTagList.stream().forEach(appTag -> {
                        if (Objects.equals(0, appTag.getTagFactorIsStat())) {
                            appTag.setTagFactorShow(appTag.getTagFactorIsStat());
                            appTag.setFactorType(factorType);
                            filterTagList.add(appTag);
                        } else if (Objects.equals(1, appTag.getTagFactorIsStat())) {
                            FactorFieldVo factorFieldVo = getFactorTag(appTag, 1, 1);
                            factorFieldVo.setFactorType(factorType);
                            filterList.add(factorFieldVo);
                            appTag.setTagFactorShow(appTag.getTagFactorIsStat());
                            appTag.setFactorType(factorType);
                            filterTagList.add(appTag);
                        }
                    });
                }

            }
            if (Objects.nonNull(factorPlan.getShowContent())) {
                String showStr = factorPlan.getShowContent();
                showStr = JSON.parse(showStr).toString();
                List<FactorFieldVo> fieldVoList = JSON.parseArray(JSON.toJSON(showStr).toString(), FactorFieldVo.class);

                Set<String> fieldNames = fieldVoList.stream().filter(s -> Objects.equals("1", s.getType()) && !Objects.equals(1, s.getLayerFactorShow()))
                        .map(FactorFieldVo::getFieldName)
                        .collect(Collectors.toSet());
                Set<String> tagNames = fieldVoList.stream().filter(s -> Objects.equals("2", s.getType()) && !Objects.equals(1, s.getLayerFactorShow()))
                        .map(FactorFieldVo::getFieldName)
                        .collect(Collectors.toSet());
                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                    metafieldEntityList.stream().forEach(metafield -> {
                        Integer index = metafield.getLayerFactorShow();
                        if(null!=index) {
                            if (fieldNames.contains(metafield.getLayerMetafieldName())) {
                                // 在必选字段
                                index = 2;
                            }
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, index, null);
                            factorFieldVo.setLayerFactorShow(index);
                            showFieldList.add(factorFieldVo);
                        }
                    });
                }
                if (CollectionUtils.isNotEmpty(appTagList)) {
                    appTagList.stream().forEach(appTag -> {
                        Integer index = appTag.getTagFactorShow();
                                if(null!=index) {
                                    if (tagNames.contains(appTag.getTagCol())) {
                                        // 在必选字段
                                        index = 2;
                                    }
                                    AppTag showTag = getAppTag(appTag, index);
                                    showTagList.add(showTag);
                                }
                    });
                }
                showList.addAll(fieldVoList);
//                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
//                    // 默认字段也自动显示
//                    metafieldEntityList.forEach(metafield -> {
//                        if (Objects.equals(1, metafield.getLayerFactorShow())) {
//                            if (showList.stream().noneMatch(show -> show.getFieldName().equals(metafield.getLayerMetafieldName()))) {
//                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 1);
//                                showList.add(factorFieldVo);
//                                showFieldList.add(factorFieldVo);
//                            }
//                            if (showFieldList.stream().noneMatch(show -> show.getFieldName().equals(metafield.getLayerMetafieldName()))) {
//                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 1);
//                                showFieldList.add(factorFieldVo);
//                            }
//                        }
//                    });
//                }
            } else {
                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                    metafieldEntityList.stream().forEach(metafield -> {
                        if (Objects.equals(1, metafield.getLayerFactorShow())) {
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 1);
                            showList.add(factorFieldVo);
                            showFieldList.add(factorFieldVo);
                        } else if (Objects.equals(0, metafield.getLayerFactorShow())) {
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 0);
                            showFieldList.add(factorFieldVo);
                        }
                    });
                }
                if (CollectionUtils.isNotEmpty(appTagList)) {
                    appTagList.stream().forEach(appTag -> {
                        if (Objects.equals(0, appTag.getTagFactorShow())) {
                            showTagList.add(appTag);
                        } else if (Objects.equals(1, appTag.getTagFactorShow())) {
                            FactorFieldVo factorFieldVo = getFactorTag(appTag, 1, 1);
                            showList.add(factorFieldVo);
                            showTagList.add(appTag);
                        }
                    });
                }

            }
        } else {
            if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                metafieldEntityList.stream().forEach(metafield -> {
                    if (Objects.equals(1, metafield.getLayerFactorIsStat())) {
                        FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 1, null);
                        factorFieldVo.setFactorType(factorType);
                        filterList.add(factorFieldVo);
                        factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                        filterFieldList.add(factorFieldVo);
                    } else if (Objects.equals(0, metafield.getLayerFactorIsStat())) {
                        FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 0, null);
                        factorFieldVo.setFactorType(factorType);
                        factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                        filterFieldList.add(factorFieldVo);
                    }
                    if (Objects.equals(1, metafield.getLayerFactorShow())) {
                        FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 1);
                        showList.add(factorFieldVo);
                        showFieldList.add(factorFieldVo);
                    } else if (Objects.equals(0, metafield.getLayerFactorShow())) {
                        FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 0);
                        showFieldList.add(factorFieldVo);
                    }
                });
            }
            if (CollectionUtils.isNotEmpty(appTagList)) {
                appTagList.stream().forEach(appTag -> {
                    if (Objects.equals(0, appTag.getTagFactorIsStat())) {
                        appTag.setTagFactorShow(appTag.getTagFactorIsStat());
                        appTag.setFactorType(factorType);
                        filterTagList.add(appTag);
                    } else if (Objects.equals(1, appTag.getTagFactorIsStat())) {
                        FactorFieldVo factorFieldVo = getFactorTag(appTag, 1, 1);
                        factorFieldVo.setFactorType(factorType);
                        filterList.add(factorFieldVo);
                        appTag.setTagFactorShow(appTag.getTagFactorIsStat());
                        appTag.setFactorType(factorType);
                        filterTagList.add(appTag);
                    }
                    if (Objects.equals(0, appTag.getTagFactorShow())) {
                        showTagList.add(appTag);
                    } else if (Objects.equals(1, appTag.getTagFactorShow())) {
                        FactorFieldVo factorFieldVo = getFactorTag(appTag, 1, 1);
                        showList.add(factorFieldVo);
                        showTagList.add(appTag);
                    }
                });
            }
        }
        if (Objects.isNull(factorPlan) || Objects.isNull(factorPlan.getFilterContent())) {
            FactorFieldVo regionFieldVo = getFactorRegionFieldVo();
            regionFieldVo.setFactorType(factorType);
            filterList.add(regionFieldVo);
        }
        if(factorType.equals(FmTcBelongTypeEnum.APP_GRIDER.getCode())){
            FactorFieldVo regionFieldVo = getFactorRegionFieldVo();
            regionFieldVo.setFactorType(factorType);
            filterList.remove(regionFieldVo);
            filterList.add(0,regionFieldVo);
        }
        result.setFilterList(filterList);
        result.setFilterFieldList(filterFieldList);
        result.setShowList(showList);
        if (CollectionUtils.isNotEmpty(showFieldList)) {
            boolean match = showFieldList.stream().anyMatch(a -> a.getLayerFactorOrder() == null);
            if (!match) {
                showFieldList.sort(Comparator.comparingInt(FactorFieldVo::getLayerFactorOrder));
            }
        }
        result.setShowFieldList(showFieldList);
        if (CollectionUtils.isNotEmpty(filterTagList)) {
            List<AppTagEntity> appTagEntities = filterTagList.stream()
                    .collect(Collectors.groupingBy(AppTag::getTagCatalog1))
                    .entrySet().stream()
                    .map(entry -> {
                        AppTagEntity entity = new AppTagEntity();
                        entity.setTagCatalog(entry.getKey());
                        entity.setTagChildCatalog(
                                entry.getValue().stream()
                                        .collect(Collectors.groupingBy(AppTag::getTagCatalog2))
                                        .entrySet().stream()
                                        .map(childEntry -> {
                                            AppTagEntity childEntity = new AppTagEntity();
                                            childEntity.setTagCatalog(childEntry.getKey());
                                            List<AppTag> appTags = childEntry.getValue();
                                            List<FactorFieldVo> tagList = getTagList(appTags);
                                            childEntity.setAppTagList(tagList);
                                            return childEntity;
                                        })
                                        .collect(Collectors.toList()));
                        return entity;
                    })
                    .collect(Collectors.toList());
            result.setFilterTagList(appTagEntities);
        }
        if (CollectionUtils.isNotEmpty(showTagList)) {
            List<AppTagEntity> appTagEntities = showTagList.stream()
                    .collect(Collectors.groupingBy(AppTag::getTagCatalog1))
                    .entrySet().stream()
                    .map(entry -> {
                        AppTagEntity entity = new AppTagEntity();
                        entity.setTagCatalog(entry.getKey());
                        entity.setTagChildCatalog(
                                entry.getValue().stream()
                                        .collect(Collectors.groupingBy(AppTag::getTagCatalog2))
                                        .entrySet().stream()
                                        .map(childEntry -> {
                                            AppTagEntity childEntity = new AppTagEntity();
                                            childEntity.setTagCatalog(childEntry.getKey());
                                            List<AppTag> appTags = childEntry.getValue();
                                            List<FactorFieldVo> tagList = getTagList(appTags);
                                            childEntity.setAppTagList(tagList);
                                            return childEntity;
                                        })
                                        .collect(Collectors.toList()));
                        return entity;
                    })
                    .collect(Collectors.toList());
            result.setShowTagList(appTagEntities);
        }
        return result;
    }

333333333333333333

package com.sf.gis.taskmanage.factor.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.gis.common.constants.CommonConstant;
import com.sf.gis.common.constants.RedisConstant;
import com.sf.gis.common.domain.dto.factor.*;
import com.sf.gis.common.domain.dto.user.UserMenu;
import com.sf.gis.common.domain.dto.user.UserRole;
import com.sf.gis.common.domain.vo.AppGriderTransitionStatVo;
import com.sf.gis.common.domain.vo.AppTagVo;
import com.sf.gis.common.domain.vo.SendSmsVo;
import com.sf.gis.common.domain.vo.TaskPlanDataVo;
import com.sf.gis.common.domain.vo.factor.*;
import com.sf.gis.common.domain.vo.user.UserLoginVo;
import com.sf.gis.common.domain.vo.user.UserRoleVo;
import com.sf.gis.common.entity.AppDicts;
import com.sf.gis.common.entity.AppTag;
import com.sf.gis.common.entity.FactorPlan;
import com.sf.gis.common.entity.SystemCommonConfig;
import com.sf.gis.common.entity.base.AppConfigAccess;
import com.sf.gis.common.entity.base.AppTagEntity;
import com.sf.gis.common.entity.base.GridInfo;
import com.sf.gis.common.entity.task.AnalysisLayerMetaEntity;
import com.sf.gis.common.entity.task.AnalysisLayerMetafield;
import com.sf.gis.common.enums.FmTcBelongTypeEnum;
import com.sf.gis.common.enums.JumpKeyEnum;
import com.sf.gis.common.enums.LegalCollectionEnum;
import com.sf.gis.common.exceprtion.BusinessException;
import com.sf.gis.common.mapper.AppDictsMapper;
import com.sf.gis.common.mapper.AppTagMapper;
import com.sf.gis.common.mapper.GridInfoMapper;
import com.sf.gis.common.service.PermissionService;
import com.sf.gis.common.service.SmsService;
import com.sf.gis.common.service.SystemCommonConfigService;
import com.sf.gis.common.service.UserSystemService;
import com.sf.gis.common.utils.*;
import com.sf.gis.taskmanage.factor.mapper.FactorPlanMapper;
import com.sf.gis.taskmanage.factor.service.FactorService;
import com.sf.gis.taskmanage.task.mapper.AnalysisLayerMetafieldMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.sf.gis.common.constants.RedisConstant.VERIFICATION_CODE;

@Service
@Slf4j
public class FactorServiceImpl extends ServiceImpl<FactorPlanMapper, FactorPlan> implements FactorService {


    @Autowired
    private AnalysisLayerMetafieldMapper analysisLayerMetafieldMapper;

    @Autowired
    private AppTagMapper appTagMapper;

    @Autowired
    private AppDictsMapper appDictsMapper;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private GridInfoMapper gridInfoMapper;

    @Autowired
    private UserSystemService userSystemService;

    @Autowired
    private FactorPlanMapper factorPlanMapper;

    @Autowired
    private SmsService smsService;

    @Value("${spring.profiles.active}")
    private String activeProfile;

    @Resource(name = "redisTemplateSelf")
    RedisTemplate<String, Object> redisTemplate;

    private static final Integer EXPORT_PAGE_SIZE = 10000;

    @Autowired
    private SystemCommonConfigService systemCommonConfigService;


    @Override
    public List<FactorFieldValueDicVo> getOuterTableEnumValue(FactorFieldQuery query) {
        return analysisLayerMetafieldMapper.getOuterTableEnumValue(query);
    }


    @Override
    public FactorMetaVo getFieldByMeta(FactorMetaQuery factorMetaQuery) {
        UserLoginVo userLoginVo = userSystemService.getUserByToken();
        if (userLoginVo == null) {
            throw new BusinessException("当前登录用户信息为空!");

        }
        if (StringUtils.isBlank(factorMetaQuery.getLayerMetaLayername())) {
            throw new BusinessException("要素主题不能为空!");
        }
        String factorType = factorMetaQuery.getLayerMetaLayername();
        FactorPlan factorPlan = factorPlanMapper.getUserByLayer(userLoginVo.getUserId(), factorMetaQuery.getLayerMetaLayername());
        if (StringUtils.isBlank(FmTcBelongTypeEnum.getValueByCode(factorMetaQuery.getLayerMetaLayername()))) {
            throw new BusinessException("参数错误!");
        } else {
            factorMetaQuery.setLayerMetaLayername(FmTcBelongTypeEnum.getValueByCode(factorMetaQuery.getLayerMetaLayername()));
        }
        AnalysisLayerMetaEntity analysisLayerMeta = analysisLayerMetafieldMapper.getViewNameByLayerName(factorMetaQuery.getLayerMetaLayername());
        if (Objects.isNull(analysisLayerMeta)) {
            return null;
        }

        FactorMetaVo result = new FactorMetaVo();
        // 设置视图表名
        result.setLayerMetaTagView(analysisLayerMeta.getLayerMetaTagview());
        result.setLayerMetaTableName(analysisLayerMeta.getLayerMetaTablename());
        result.setLayerMetaTagtable(analysisLayerMeta.getLayerMetaTagtable());
        // 获取必选和可选字段 (包括查询条件和结果字段)
        List<AnalysisLayerMetafield> metafieldEntityList = analysisLayerMetafieldMapper.getFactorByMeta(analysisLayerMeta.getLayerMetaId());
        // 获取必选和可选标签 (包括查询条件和结果标签)
        List<AppTag> appTagList = appTagMapper.getFactorTagByTable(analysisLayerMeta.getLayerMetaTagtable());
        // 设置查询必选条件字段
        // 查询过滤可选字段
        List<FactorFieldVo> filterFieldList = new ArrayList<>();
        // 查询过滤可选标签
        List<AppTag> filterTagList = new ArrayList<>();
        // 查询过滤字段
        List<FactorFieldVo> filterList = new ArrayList<>();
        // 查询结果字段
        List<FactorFieldVo> showList = new ArrayList<>();
        // 查询结果可选字段
        List<FactorFieldVo> showFieldList = new ArrayList<>();
        // 查询结果可选标签
        List<AppTag> showTagList = new ArrayList<>();
        if (Objects.nonNull(factorPlan)) {
            if (Objects.nonNull(factorPlan.getFilterContent())) {
                String filterStr = factorPlan.getFilterContent();
                List<FactorFieldVo> fieldVoList = JSON.parseArray(JSON.toJSON(filterStr).toString(), FactorFieldVo.class);

                Set<String> fieldNames = fieldVoList.stream().filter(s -> Objects.equals("1", s.getType()) && !Objects.equals(1, s.getLayerFactorShow()))
                        .map(FactorFieldVo::getFieldName)
                        .collect(Collectors.toSet());
                Set<String> tagNames = fieldVoList.stream().filter(s -> Objects.equals("2", s.getType()) && !Objects.equals(1, s.getLayerFactorShow()))
                        .map(FactorFieldVo::getFieldName)
                        .collect(Collectors.toSet());
                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                    metafieldEntityList.stream().forEach(metafield -> {
                        Integer index = metafield.getLayerFactorIsStat();
                        if(null!=index) {
                            if (fieldNames.contains(metafield.getLayerMetafieldName())) {
                                // 在必选字段
                                index = 2;
                            }
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, index, null);
                            factorFieldVo.setLayerFactorShow(index);
                            factorFieldVo.setFactorType(factorType);
                            filterFieldList.add(factorFieldVo);
                        }
                    });
                }
                if (CollectionUtils.isNotEmpty(appTagList)) {
                    appTagList.stream().forEach(appTag -> {
                        Integer index = appTag.getTagFactorIsStat();
                                if(null!=index) {
                                    if (tagNames.contains(appTag.getTagCol())) {
                                        // 在必选字段
                                        index = 2;
                                    }
                                    // 这里注意(直接在app_tag中赋值,是弱引用,会在下一个循环中值覆盖,所以这里new了一个新对象,不会被下面的show循环覆盖值)
                                    AppTag filterTag = getAppTag(appTag, index);
                                    filterTag.setFactorType(factorType);
                                    filterTagList.add(filterTag);
                                }
                    });
                }
                filterList.addAll(fieldVoList);
//                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
//                    // 默认字段也自动显示
//                    metafieldEntityList.forEach(metafield -> {
//                        if (Objects.equals(1, metafield.getLayerFactorIsStat())) {
//                            if (filterList.stream().noneMatch(show -> show.getFieldName().equals(metafield.getLayerMetafieldName()))) {
//                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 1, null);
//                                factorFieldVo.setFactorType(factorType);
//                                filterList.add(factorFieldVo);
//                            }
//                            if (filterFieldList.stream().noneMatch(show -> show.getFieldName().equals(metafield.getLayerMetafieldName()))) {
//                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 1, null);
//                                factorFieldVo.setFactorType(factorType);
//                                factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
//                                filterFieldList.add(factorFieldVo);
//                            }
//                        }
//                    });
//                }
            } else {
                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                    metafieldEntityList.stream().forEach(metafield -> {
                        if (Objects.equals(1, metafield.getLayerFactorIsStat())) {
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 1, null);
                            factorFieldVo.setFactorType(factorType);
                            filterList.add(factorFieldVo);
                            factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                            filterFieldList.add(factorFieldVo);
                        } else if (Objects.equals(0, metafield.getLayerFactorIsStat())) {
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 0, null);
                            factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                            factorFieldVo.setFactorType(factorType);
                            filterFieldList.add(factorFieldVo);
                        }
                    });
                }
                if (CollectionUtils.isNotEmpty(appTagList)) {
                    appTagList.stream().forEach(appTag -> {
                        if (Objects.equals(0, appTag.getTagFactorIsStat())) {
                            appTag.setTagFactorShow(appTag.getTagFactorIsStat());
                            appTag.setFactorType(factorType);
                            filterTagList.add(appTag);
                        } else if (Objects.equals(1, appTag.getTagFactorIsStat())) {
                            FactorFieldVo factorFieldVo = getFactorTag(appTag, 1, 1);
                            factorFieldVo.setFactorType(factorType);
                            filterList.add(factorFieldVo);
                            appTag.setTagFactorShow(appTag.getTagFactorIsStat());
                            appTag.setFactorType(factorType);
                            filterTagList.add(appTag);
                        }
                    });
                }

            }
            if (Objects.nonNull(factorPlan.getShowContent())) {
                String showStr = factorPlan.getShowContent();
                showStr = JSON.parse(showStr).toString();
                List<FactorFieldVo> fieldVoList = JSON.parseArray(JSON.toJSON(showStr).toString(), FactorFieldVo.class);

                Set<String> fieldNames = fieldVoList.stream().filter(s -> Objects.equals("1", s.getType()) && !Objects.equals(1, s.getLayerFactorShow()))
                        .map(FactorFieldVo::getFieldName)
                        .collect(Collectors.toSet());
                Set<String> tagNames = fieldVoList.stream().filter(s -> Objects.equals("2", s.getType()) && !Objects.equals(1, s.getLayerFactorShow()))
                        .map(FactorFieldVo::getFieldName)
                        .collect(Collectors.toSet());
                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                    metafieldEntityList.stream().forEach(metafield -> {
                        Integer index = metafield.getLayerFactorShow();
                        if(null!=index) {
                            if (fieldNames.contains(metafield.getLayerMetafieldName())) {
                                // 在必选字段
                                index = 2;
                            }
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, index, null);
                            factorFieldVo.setLayerFactorShow(index);
                            showFieldList.add(factorFieldVo);
                        }
                    });
                }
                if (CollectionUtils.isNotEmpty(appTagList)) {
                    appTagList.stream().forEach(appTag -> {
                        Integer index = appTag.getTagFactorShow();
                                if(null!=index) {
                                    if (tagNames.contains(appTag.getTagCol())) {
                                        // 在必选字段
                                        index = 2;
                                    }
                                    AppTag showTag = getAppTag(appTag, index);
                                    showTagList.add(showTag);
                                }
                    });
                }
                showList.addAll(fieldVoList);
//                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
//                    // 默认字段也自动显示
//                    metafieldEntityList.forEach(metafield -> {
//                        if (Objects.equals(1, metafield.getLayerFactorShow())) {
//                            if (showList.stream().noneMatch(show -> show.getFieldName().equals(metafield.getLayerMetafieldName()))) {
//                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 1);
//                                showList.add(factorFieldVo);
//                                showFieldList.add(factorFieldVo);
//                            }
//                            if (showFieldList.stream().noneMatch(show -> show.getFieldName().equals(metafield.getLayerMetafieldName()))) {
//                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 1);
//                                showFieldList.add(factorFieldVo);
//                            }
//                        }
//                    });
//                }
            } else {
                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                    metafieldEntityList.stream().forEach(metafield -> {
                        if (Objects.equals(1, metafield.getLayerFactorShow())) {
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 1);
                            showList.add(factorFieldVo);
                            showFieldList.add(factorFieldVo);
                        } else if (Objects.equals(0, metafield.getLayerFactorShow())) {
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 0);
                            showFieldList.add(factorFieldVo);
                        }
                    });
                }
                if (CollectionUtils.isNotEmpty(appTagList)) {
                    appTagList.stream().forEach(appTag -> {
                        if (Objects.equals(0, appTag.getTagFactorShow())) {
                            showTagList.add(appTag);
                        } else if (Objects.equals(1, appTag.getTagFactorShow())) {
                            FactorFieldVo factorFieldVo = getFactorTag(appTag, 1, 1);
                            showList.add(factorFieldVo);
                            showTagList.add(appTag);
                        }
                    });
                }

            }
        } else {
            if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                metafieldEntityList.stream().forEach(metafield -> {
                    if (Objects.equals(1, metafield.getLayerFactorIsStat())) {
                        FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 1, null);
                        factorFieldVo.setFactorType(factorType);
                        filterList.add(factorFieldVo);
                        factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                        filterFieldList.add(factorFieldVo);
                    } else if (Objects.equals(0, metafield.getLayerFactorIsStat())) {
                        FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 0, null);
                        factorFieldVo.setFactorType(factorType);
                        factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                        filterFieldList.add(factorFieldVo);
                    }
                    if (Objects.equals(1, metafield.getLayerFactorShow())) {
                        FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 1);
                        showList.add(factorFieldVo);
                        showFieldList.add(factorFieldVo);
                    } else if (Objects.equals(0, metafield.getLayerFactorShow())) {
                        FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 0);
                        showFieldList.add(factorFieldVo);
                    }
                });
            }
            if (CollectionUtils.isNotEmpty(appTagList)) {
                appTagList.stream().forEach(appTag -> {
                    if (Objects.equals(0, appTag.getTagFactorIsStat())) {
                        appTag.setTagFactorShow(appTag.getTagFactorIsStat());
                        appTag.setFactorType(factorType);
                        filterTagList.add(appTag);
                    } else if (Objects.equals(1, appTag.getTagFactorIsStat())) {
                        FactorFieldVo factorFieldVo = getFactorTag(appTag, 1, 1);
                        factorFieldVo.setFactorType(factorType);
                        filterList.add(factorFieldVo);
                        appTag.setTagFactorShow(appTag.getTagFactorIsStat());
                        appTag.setFactorType(factorType);
                        filterTagList.add(appTag);
                    }
                    if (Objects.equals(0, appTag.getTagFactorShow())) {
                        showTagList.add(appTag);
                    } else if (Objects.equals(1, appTag.getTagFactorShow())) {
                        FactorFieldVo factorFieldVo = getFactorTag(appTag, 1, 1);
                        showList.add(factorFieldVo);
                        showTagList.add(appTag);
                    }
                });
            }
        }
        if (Objects.isNull(factorPlan) || Objects.isNull(factorPlan.getFilterContent())) {
            FactorFieldVo regionFieldVo = getFactorRegionFieldVo();
            regionFieldVo.setFactorType(factorType);
            filterList.add(regionFieldVo);
        }
        if(factorType.equals(FmTcBelongTypeEnum.APP_GRIDER.getCode())){
            FactorFieldVo regionFieldVo = getFactorRegionFieldVo();
            regionFieldVo.setFactorType(factorType);
            filterList.remove(regionFieldVo);
            filterList.add(0,regionFieldVo);
        }
        result.setFilterList(filterList);
        result.setFilterFieldList(filterFieldList);
        result.setShowList(showList);
        if (CollectionUtils.isNotEmpty(showFieldList)) {
            boolean match = showFieldList.stream().anyMatch(a -> a.getLayerFactorOrder() == null);
            if (!match) {
                showFieldList.sort(Comparator.comparingInt(FactorFieldVo::getLayerFactorOrder));
            }
        }
        result.setShowFieldList(showFieldList);
        if (CollectionUtils.isNotEmpty(filterTagList)) {
            List<AppTagEntity> appTagEntities = filterTagList.stream()
                    .collect(Collectors.groupingBy(AppTag::getTagCatalog1))
                    .entrySet().stream()
                    .map(entry -> {
                        AppTagEntity entity = new AppTagEntity();
                        entity.setTagCatalog(entry.getKey());
                        entity.setTagChildCatalog(
                                entry.getValue().stream()
                                        .collect(Collectors.groupingBy(AppTag::getTagCatalog2))
                                        .entrySet().stream()
                                        .map(childEntry -> {
                                            AppTagEntity childEntity = new AppTagEntity();
                                            childEntity.setTagCatalog(childEntry.getKey());
                                            List<AppTag> appTags = childEntry.getValue();
                                            List<FactorFieldVo> tagList = getTagList(appTags);
                                            childEntity.setAppTagList(tagList);
                                            return childEntity;
                                        })
                                        .collect(Collectors.toList()));
                        return entity;
                    })
                    .collect(Collectors.toList());
            result.setFilterTagList(appTagEntities);
        }
        if (CollectionUtils.isNotEmpty(showTagList)) {
            List<AppTagEntity> appTagEntities = showTagList.stream()
                    .collect(Collectors.groupingBy(AppTag::getTagCatalog1))
                    .entrySet().stream()
                    .map(entry -> {
                        AppTagEntity entity = new AppTagEntity();
                        entity.setTagCatalog(entry.getKey());
                        entity.setTagChildCatalog(
                                entry.getValue().stream()
                                        .collect(Collectors.groupingBy(AppTag::getTagCatalog2))
                                        .entrySet().stream()
                                        .map(childEntry -> {
                                            AppTagEntity childEntity = new AppTagEntity();
                                            childEntity.setTagCatalog(childEntry.getKey());
                                            List<AppTag> appTags = childEntry.getValue();
                                            List<FactorFieldVo> tagList = getTagList(appTags);
                                            childEntity.setAppTagList(tagList);
                                            return childEntity;
                                        })
                                        .collect(Collectors.toList()));
                        return entity;
                    })
                    .collect(Collectors.toList());
            result.setShowTagList(appTagEntities);
        }
        return result;
    }

    @Override
    public FactorMetaNewVo getFieldByMetaNew(FactorMetaQuery factorMetaQuery) {
        UserLoginVo userLoginVo = userSystemService.getUserByToken();
        if (userLoginVo == null) {
            throw new BusinessException("当前登录用户信息为空!");

        }
        if (StringUtils.isBlank(factorMetaQuery.getLayerMetaLayername())) {
            throw new BusinessException("要素主题不能为空!");
        }
        String factorType = factorMetaQuery.getLayerMetaLayername();
        String personVo= FmTcBelongTypeEnum.PERSON.getCode();// 人口要素标识
        String buildingVo = FmTcBelongTypeEnum.BUILDING.getCode();//楼栋要素标识
        String houseVo = FmTcBelongTypeEnum.HOUSE.getCode();//房屋要素标识
        FactorMetaVo factorMetaNewVo_person = getFieldByMetaForMain(personVo,userLoginVo,factorType);
        FactorMetaVo factorMetaNewVo_building = getFieldByMetaForMain(buildingVo,userLoginVo,factorType);
        FactorMetaVo factorMetaNewVo_house = getFieldByMetaForMain(houseVo,userLoginVo,factorType);
        FactorMetaNewVo result = new FactorMetaNewVo();
        if(factorType.equals(personVo)){
            BeanUtils.copyProperties(factorMetaNewVo_person,result);
        }else{
            return null;
        }
        //整合查询过滤可选字段
        Map<String,List<FactorFieldVo>> filterFieldListMap = new HashMap<>();
        filterFieldListMap.put(personVo,factorMetaNewVo_person.getFilterFieldList());
        filterFieldListMap.put(buildingVo,factorMetaNewVo_building.getFilterFieldList());
        filterFieldListMap.put(houseVo,factorMetaNewVo_house.getFilterFieldList());
        result.setFilterFieldListMap(filterFieldListMap);
        //整合查询过滤字段
        Map<String,List<AppTagEntity>> filterTagListMap = new HashMap<>();
        filterTagListMap.put(personVo,factorMetaNewVo_person.getFilterTagList());
        filterTagListMap.put(buildingVo,factorMetaNewVo_building.getFilterTagList());
        filterTagListMap.put(houseVo,factorMetaNewVo_house.getFilterTagList());
        result.setFilterTagListMap(filterTagListMap);
        //整合查询过滤字段
        Map<String,List<FactorFieldVo>> filterListMap = new HashMap<>();
        filterListMap.put(personVo,factorMetaNewVo_person.getFilterList());
        filterListMap.put(buildingVo,factorMetaNewVo_building.getFilterList());
        filterListMap.put(houseVo,factorMetaNewVo_house.getFilterList());
        result.setFilterListMap(filterListMap);
        return result;
    }

    public FactorMetaVo getFieldByMetaForMain(String layerMetaLayername,UserLoginVo userLoginVo,String mainLayerName) {
        String factorType = layerMetaLayername;
        FactorPlan factorPlan = factorPlanMapper.getUserByLayer(userLoginVo.getUserId(), mainLayerName);
        if (StringUtils.isBlank(FmTcBelongTypeEnum.getValueByCode(layerMetaLayername))) {
            throw new BusinessException("参数错误!");
        } else {
            layerMetaLayername = FmTcBelongTypeEnum.getValueByCode(layerMetaLayername);
        }
        AnalysisLayerMetaEntity analysisLayerMeta = analysisLayerMetafieldMapper.getViewNameByLayerName(layerMetaLayername);
        if (Objects.isNull(analysisLayerMeta)) {
            return null;
        }

        FactorMetaVo result = new FactorMetaVo();
        // 设置视图表名
        result.setLayerMetaTagView(analysisLayerMeta.getLayerMetaTagview());
        result.setLayerMetaTableName(analysisLayerMeta.getLayerMetaTablename());
        result.setLayerMetaTagtable(analysisLayerMeta.getLayerMetaTagtable());
        // 获取必选和可选字段 (包括查询条件和结果字段)
        List<AnalysisLayerMetafield> metafieldEntityList = analysisLayerMetafieldMapper.getFactorByMeta(analysisLayerMeta.getLayerMetaId());
        // 获取必选和可选标签 (包括查询条件和结果标签)
        List<AppTag> appTagList = appTagMapper.getFactorTagByTable(analysisLayerMeta.getLayerMetaTagtable());
        // 设置查询必选条件字段
        // 查询过滤可选字段
        List<FactorFieldVo> filterFieldList = new ArrayList<>();
        // 查询过滤可选标签
        List<AppTag> filterTagList = new ArrayList<>();
        // 查询过滤字段
        List<FactorFieldVo> filterList = new ArrayList<>();
        // 查询结果字段
        List<FactorFieldVo> showList = new ArrayList<>();
        // 查询结果可选字段
        List<FactorFieldVo> showFieldList = new ArrayList<>();
        boolean ismain = true;//待添加---性能优化,非主题show类可以不用管
        //非主题要素初始化取消所有必选
        if(!Objects.equals(factorType,mainLayerName))
        {
            metafieldEntityList.stream().forEach(metafield -> {
                if (Objects.equals(1, metafield.getLayerFactorIsStat())) {
                    metafield.setLayerFactorIsStat(0);
                }
            });
            appTagList.stream().forEach(appTag -> {
                if (Objects.equals(1, appTag.getTagFactorIsStat())) {
                    appTag.setTagFactorIsStat(0);
                }
            });
            ismain=false;
        }
        // 查询结果可选标签
        List<AppTag> showTagList = new ArrayList<>();
        if (Objects.nonNull(factorPlan)) {
            if (Objects.nonNull(factorPlan.getFilterContent())) {
                String filterStr = factorPlan.getFilterContent();
                List<FactorFieldVo> fieldVoListALl = JSON.parseArray(JSON.toJSON(filterStr).toString(), FactorFieldVo.class);
                List<FactorFieldVo> fieldVoList = new ArrayList<>();
                if(Objects.equals(factorType,mainLayerName)) {
                     fieldVoList = fieldVoListALl.stream().filter(s -> Objects.equals(factorType, s.getFactorType())||StringUtils.isBlank(s.getFactorType())).collect(Collectors.toList());
                }else{
                     fieldVoList = fieldVoListALl.stream().filter(s -> Objects.equals(factorType, s.getFactorType())).collect(Collectors.toList());
                }
                Set<String> fieldNames = fieldVoList.stream().filter(s -> Objects.equals("1", s.getType()) && !Objects.equals(1, s.getLayerFactorShow()))
                        .map(FactorFieldVo::getFieldName)
                        .collect(Collectors.toSet());
                Set<String> tagNames = fieldVoList.stream().filter(s -> Objects.equals("2", s.getType()) && !Objects.equals(1, s.getLayerFactorShow()))
                        .map(FactorFieldVo::getFieldName)
                        .collect(Collectors.toSet());
                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                    metafieldEntityList.stream().forEach(metafield -> {
                        Integer index = metafield.getLayerFactorIsStat();
                        if(null!=index) {
                            if (fieldNames.contains(metafield.getLayerMetafieldName())) {
                                // 在必选字段
                                index = 2;
                            }
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, index, null);
                            factorFieldVo.setLayerFactorShow(index);
                            factorFieldVo.setFactorType(factorType);
                            filterFieldList.add(factorFieldVo);
                        }
                    });
                }
                if (CollectionUtils.isNotEmpty(appTagList)) {
                    appTagList.stream().forEach(appTag -> {
                        Integer index = appTag.getTagFactorIsStat();
                        if(null!=index) {
                            if (tagNames.contains(appTag.getTagCol())) {
                                // 在必选字段
                                index = 2;
                            }
                            // 这里注意(直接在app_tag中赋值,是弱引用,会在下一个循环中值覆盖,所以这里new了一个新对象,不会被下面的show循环覆盖值)
                            AppTag filterTag = getAppTag(appTag, index);
                            filterTag.setFactorType(factorType);
                            filterTagList.add(filterTag);
                        }
                    });
                }
                filterList.addAll(fieldVoList);
                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                    // 默认字段也自动显示
                    metafieldEntityList.forEach(metafield -> {
                        if (Objects.equals(1, metafield.getLayerFactorIsStat())) {
                            if (filterList.stream().noneMatch(show -> show.getFieldName().equals(metafield.getLayerMetafieldName()))) {
                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 1, null);
                                factorFieldVo.setFactorType(factorType);
                                filterList.add(factorFieldVo);
                            }
                            if (filterFieldList.stream().noneMatch(show -> show.getFieldName().equals(metafield.getLayerMetafieldName()))) {
                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 1, null);
                                factorFieldVo.setFactorType(factorType);
                                factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                                filterFieldList.add(factorFieldVo);
                            }
                        }
                    });
                }
            } else {
                if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                    metafieldEntityList.stream().forEach(metafield -> {
                        if (Objects.equals(1, metafield.getLayerFactorIsStat())) {
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 1, null);
                            factorFieldVo.setFactorType(factorType);
                            filterList.add(factorFieldVo);
                            factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                            filterFieldList.add(factorFieldVo);
                        } else if (Objects.equals(0, metafield.getLayerFactorIsStat())) {
                            FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 0, null);
                            factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                            factorFieldVo.setFactorType(factorType);
                            filterFieldList.add(factorFieldVo);
                        }
                    });
                }
                if (CollectionUtils.isNotEmpty(appTagList)) {
                    appTagList.stream().forEach(appTag -> {
                        if (Objects.equals(0, appTag.getTagFactorIsStat())) {
                            appTag.setTagFactorShow(appTag.getTagFactorIsStat());
                            appTag.setFactorType(factorType);
                            filterTagList.add(appTag);
                        } else if (Objects.equals(1, appTag.getTagFactorIsStat())) {
                            FactorFieldVo factorFieldVo = getFactorTag(appTag, 1, 1);
                            factorFieldVo.setFactorType(factorType);
                            filterList.add(factorFieldVo);
                            appTag.setTagFactorShow(appTag.getTagFactorIsStat());
                            appTag.setFactorType(factorType);
                            filterTagList.add(appTag);
                        }
                    });
                }

            }
            if(ismain) {
                if (Objects.nonNull(factorPlan.getShowContent())) {
                    String showStr = factorPlan.getShowContent();
                    showStr = JSON.parse(showStr).toString();
                    List<FactorFieldVo> fieldVoList = JSON.parseArray(JSON.toJSON(showStr).toString(), FactorFieldVo.class);

                    Set<String> fieldNames = fieldVoList.stream().filter(s -> Objects.equals("1", s.getType()) && !Objects.equals(1, s.getLayerFactorShow()))
                            .map(FactorFieldVo::getFieldName)
                            .collect(Collectors.toSet());
                    Set<String> tagNames = fieldVoList.stream().filter(s -> Objects.equals("2", s.getType()) && !Objects.equals(1, s.getLayerFactorShow()))
                            .map(FactorFieldVo::getFieldName)
                            .collect(Collectors.toSet());
                    if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                        metafieldEntityList.stream().forEach(metafield -> {
                            Integer index = metafield.getLayerFactorShow();
                            if (null != index) {
                                if (fieldNames.contains(metafield.getLayerMetafieldName())) {
                                    // 在必选字段
                                    index = 2;
                                }
                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, index, null);
                                factorFieldVo.setLayerFactorShow(index);
                                showFieldList.add(factorFieldVo);
                            }
                        });
                    }
                    if (CollectionUtils.isNotEmpty(appTagList)) {
                        appTagList.stream().forEach(appTag -> {
                            Integer index = appTag.getTagFactorShow();
                            if (null != index) {
                                if (tagNames.contains(appTag.getTagCol())) {
                                    // 在必选字段
                                    index = 2;
                                }
                                AppTag showTag = getAppTag(appTag, index);
                                showTagList.add(showTag);
                            }
                        });
                    }
                    showList.addAll(fieldVoList);
                    if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                        // 默认字段也自动显示
                        metafieldEntityList.forEach(metafield -> {
                            if (Objects.equals(1, metafield.getLayerFactorShow())) {
                                if (showList.stream().noneMatch(show -> show.getFieldName().equals(metafield.getLayerMetafieldName()))) {
                                    FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 1);
                                    showList.add(factorFieldVo);
//                                    showFieldList.add(factorFieldVo);
                                }
                                if (showFieldList.stream().noneMatch(show -> show.getFieldName().equals(metafield.getLayerMetafieldName()))) {
                                    FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 1);
                                    showFieldList.add(factorFieldVo);
                                }
                            }
                        });
                    }
                } else {
                    if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                        metafieldEntityList.stream().forEach(metafield -> {
                            if (Objects.equals(1, metafield.getLayerFactorShow())) {
                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 1);
                                showList.add(factorFieldVo);
                                showFieldList.add(factorFieldVo);
                            } else if (Objects.equals(0, metafield.getLayerFactorShow())) {
                                FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 0);
                                showFieldList.add(factorFieldVo);
                            }
                        });
                    }
                    if (CollectionUtils.isNotEmpty(appTagList)) {
                        appTagList.stream().forEach(appTag -> {
                            if (Objects.equals(0, appTag.getTagFactorShow())) {
                                showTagList.add(appTag);
                            } else if (Objects.equals(1, appTag.getTagFactorShow())) {
                                FactorFieldVo factorFieldVo = getFactorTag(appTag, 1, 1);
                                showList.add(factorFieldVo);
                                showTagList.add(appTag);
                            }
                        });
                    }

                }
            }
        } else {
            if (CollectionUtils.isNotEmpty(metafieldEntityList)) {
                metafieldEntityList.stream().forEach(metafield -> {
                    if (Objects.equals(1, metafield.getLayerFactorIsStat())) {
                        FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 1, null);
                        factorFieldVo.setFactorType(factorType);
                        filterList.add(factorFieldVo);
                        factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                        filterFieldList.add(factorFieldVo);
                    } else if (Objects.equals(0, metafield.getLayerFactorIsStat())) {
                        FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, 0, null);
                        factorFieldVo.setFactorType(factorType);
                        factorFieldVo.setLayerFactorShow(metafield.getLayerFactorIsStat());
                        filterFieldList.add(factorFieldVo);
                    }
                    if (Objects.equals(1, metafield.getLayerFactorShow())) {
                        FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 1);
                        showList.add(factorFieldVo);
                        showFieldList.add(factorFieldVo);
                    } else if (Objects.equals(0, metafield.getLayerFactorShow())) {
                        FactorFieldVo factorFieldVo = getFactorFieldVo(metafield, null, 0);
                        showFieldList.add(factorFieldVo);
                    }
                });
            }
            if (CollectionUtils.isNotEmpty(appTagList)) {
                appTagList.stream().forEach(appTag -> {
                    if (Objects.equals(0, appTag.getTagFactorIsStat())) {
                        appTag.setTagFactorShow(appTag.getTagFactorIsStat());
                        appTag.setFactorType(factorType);
                        filterTagList.add(appTag);
                    } else if (Objects.equals(1, appTag.getTagFactorIsStat())) {
                        FactorFieldVo factorFieldVo = getFactorTag(appTag, 1, 1);
                        factorFieldVo.setFactorType(factorType);
                        filterList.add(factorFieldVo);
                        appTag.setTagFactorShow(appTag.getTagFactorIsStat());
                        appTag.setFactorType(factorType);
                        filterTagList.add(appTag);
                    }
                    if (Objects.equals(0, appTag.getTagFactorShow())) {
                        showTagList.add(appTag);
                    } else if (Objects.equals(1, appTag.getTagFactorShow())) {
                        FactorFieldVo factorFieldVo = getFactorTag(appTag, 1, 1);
                        showList.add(factorFieldVo);
                        showTagList.add(appTag);
                    }
                });
            }
        }
        if(ismain) {
            if (Objects.isNull(factorPlan) || Objects.isNull(factorPlan.getFilterContent())) {
                FactorFieldVo regionFieldVo = getFactorRegionFieldVo();
                regionFieldVo.setFactorType(factorType);
                filterList.add(regionFieldVo);
            }
        }
        result.setFilterList(filterList);
        result.setFilterFieldList(filterFieldList);

        // 排序 TODO
        if (CollectionUtils.isNotEmpty(showList)) {
            showList.sort(Comparator.comparing(FactorFieldVo::getLayerFactorOrder, Comparator.nullsLast(Comparator.naturalOrder())));
        }
        if (CollectionUtils.isNotEmpty(showFieldList)) {
            showFieldList.sort(Comparator.comparing(FactorFieldVo::getLayerFactorOrder, Comparator.nullsLast(Comparator.naturalOrder())));
        }
        result.setShowList(showList);
        result.setShowFieldList(showFieldList);
        if (CollectionUtils.isNotEmpty(filterTagList)) {
            List<AppTagEntity> appTagEntities = filterTagList.stream()
                    .collect(Collectors.groupingBy(AppTag::getTagCatalog1))
                    .entrySet().stream()
                    .map(entry -> {
                        AppTagEntity entity = new AppTagEntity();
                        entity.setTagCatalog(entry.getKey());
                        entity.setTagChildCatalog(
                                entry.getValue().stream()
                                        .collect(Collectors.groupingBy(AppTag::getTagCatalog2))
                                        .entrySet().stream()
                                        .map(childEntry -> {
                                            AppTagEntity childEntity = new AppTagEntity();
                                            childEntity.setTagCatalog(childEntry.getKey());
                                            List<AppTag> appTags = childEntry.getValue();
                                            List<FactorFieldVo> tagList = getTagList(appTags);
                                            childEntity.setAppTagList(tagList);
                                            return childEntity;
                                        })
                                        .collect(Collectors.toList()));
                        return entity;
                    })
                    .collect(Collectors.toList());
            result.setFilterTagList(appTagEntities);
        }
        if (CollectionUtils.isNotEmpty(showTagList)&&ismain) {
            List<AppTagEntity> appTagEntities = showTagList.stream()
                    .collect(Collectors.groupingBy(AppTag::getTagCatalog1))
                    .entrySet().stream()
                    .map(entry -> {
                        AppTagEntity entity = new AppTagEntity();
                        entity.setTagCatalog(entry.getKey());
                        entity.setTagChildCatalog(
                                entry.getValue().stream()
                                        .collect(Collectors.groupingBy(AppTag::getTagCatalog2))
                                        .entrySet().stream()
                                        .map(childEntry -> {
                                            AppTagEntity childEntity = new AppTagEntity();
                                            childEntity.setTagCatalog(childEntry.getKey());
                                            List<AppTag> appTags = childEntry.getValue();
                                            List<FactorFieldVo> tagList = getTagList(appTags);
                                            childEntity.setAppTagList(tagList);
                                            return childEntity;
                                        })
                                        .collect(Collectors.toList()));
                        return entity;
                    })
                    .collect(Collectors.toList());
            result.setShowTagList(appTagEntities);
        }
        return result;
    }

    private AppTag getAppTag(AppTag appTag, Integer index) {
        AppTag filterTag = new AppTag();
        filterTag.setTagCatalog1(appTag.getTagCatalog1());
        filterTag.setTagCatalog2(appTag.getTagCatalog2());
        filterTag.setTagCol(appTag.getTagCol());
        filterTag.setTagCode(appTag.getTagCode());
        filterTag.setTagId(appTag.getTagId());
        filterTag.setTagDictLevelCode(appTag.getTagDictLevelCode());
        filterTag.setTagDictTypeCode(appTag.getTagDictTypeCode());
        filterTag.setTagDictTable(appTag.getTagDictTable());
        filterTag.setTagFieldType(appTag.getTagFieldType());
        filterTag.setTagTable(appTag.getTagTable());
        filterTag.setTagName(appTag.getTagName());
        filterTag.setTagCatalog3(appTag.getTagCatalog3());
        filterTag.setTagCutMulti(appTag.getTagCutMulti());
        filterTag.setTagId(appTag.getTagId());
        filterTag.setTagFactorIsStat(appTag.getTagFactorIsStat());
        filterTag.setTagIndexType(appTag.getTagIndexType());
        filterTag.setTagObjectMain(appTag.getTagObjectMain());
        filterTag.setTagObjectSub(appTag.getTagObjectSub());
        filterTag.setTagFactorShow(index);
        return filterTag;
    }

    @NotNull
    private static List<FactorFieldVo> getTagList(List<AppTag> appTags) {
        List<FactorFieldVo> tagList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(appTags)) {
            appTags.stream().forEach(tag -> {
                FactorFieldVo fieldVo = new FactorFieldVo();
                if (StringUtils.isEmpty(tag.getTagFieldType())) {
                    fieldVo.setFieldType("varchar");
                    fieldVo.setIsPullDown("1");
                    fieldVo.setDicLevelCode(tag.getTagDictLevelCode());
                    fieldVo.setDicTable(tag.getTagDictTable());
                    fieldVo.setDicTypeCode(tag.getTagDictTypeCode());
                } else {
                    fieldVo.setFieldType(tag.getTagFieldType());
                    fieldVo.setIsPullDown("0");

                    fieldVo.setDicLevelCode(tag.getTagDictLevelCode());
                    fieldVo.setDicTable(tag.getTagDictTable());
                    fieldVo.setDicTypeCode(tag.getTagDictTypeCode());
                    if (StringUtils.isNotBlank(tag.getTagDictTable())) {
                        fieldVo.setIsPullDown("1");
                    }
                }
                fieldVo.setTagCutMulti(tag.getTagCutMulti());
                fieldVo.setFieldName(tag.getTagCol());
                fieldVo.setType("2");
                fieldVo.setTitle(tag.getTagName());
                fieldVo.setLayerFactorShow(tag.getTagFactorShow());
                fieldVo.setLayerFactorIsStat(tag.getTagFactorIsStat());
                fieldVo.setFactorType(tag.getFactorType());
                tagList.add(fieldVo);
            });
        }
        return tagList;
    }

    @Override
    public FactorListVo getFactorList(FactorQuery query) {
        FactorListVo result = new FactorListVo();
        List<FactorShowVo> showList = query.getShowList();
        Map<String, String> keyMap = new LinkedHashMap<>();
        Map<String, String> keyTypeMap = new LinkedHashMap<>();
        String keyCode = JumpKeyEnum.getValueByCode(query.getLayerMetaTagView());
        if (StringUtils.isEmpty(keyCode)) {
            throw new BusinessException("请选择正确的主题");
        }
        String zzKeyCode = StrUtil.toCamelCase(keyCode);
        result.setJumpKey(zzKeyCode);
        String jumpId = null;
        if (Objects.equals(FactorUtil.PERSON_CANCEL_VIEW_TABLE, query.getLayerMetaTagView())) {
            jumpId = FactorUtil.getPrimary(query.getLayerMetaTagView());
            result.setJumpId(StrUtil.toCamelCase(FactorUtil.PERSON_KEY));
        }
        String legalCode = JumpKeyEnum.LEGAL.getValue();//法人code
        if (StringUtils.equals(legalCode, keyCode) && CollectionUtils.isNotEmpty(showList)) {
            FactorShowVo factorShowVo = new FactorShowVo();
            factorShowVo.setFieldName("opt_type");
            factorShowVo.setFieldType("varchar");
            factorShowVo.setTitle("操作类型");
            showList.add(factorShowVo);
        }
        String querySql = "";
        String orderBy = "";
        String filterSql = "";
        if (Objects.equals(1, query.getIsDeWeight()) && Objects.equals("bz_person_collect_latest_tagview", query.getLayerMetaTagView())) {
            // 人口查询特殊要求,勾选去重后,根据身份证号去重查询
            querySql += "DISTINCT ON (cardno)";
            orderBy += "ORDER BY cardno, personcollect_latest_id,opt_time";
            filterSql += "and living_status = '1' ";
        } else {
            String primary = FactorUtil.getPrimary(query.getLayerMetaTagView());
            orderBy += "ORDER BY "+primary ;
        }
        StringBuilder builder = new StringBuilder();
        //Map <String,String>original = new HashMap<>();
        Map<String, String> caseTo = new HashMap<>();
        caseTo.put(zzKeyCode, zzKeyCode);
        List<String> dateList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(showList)) {
            showList.stream().forEach(factorShowVo -> {
                String caseKey = getCase(factorShowVo.getFieldName());
                //original.put(factorShowVo.getFieldName(),caseKey);
                caseTo.put(caseKey, factorShowVo.getFieldName());
                keyMap.put(factorShowVo.getFieldName(), factorShowVo.getTitle());
                if(StringUtils.isNotBlank(factorShowVo.getEncryptionType())) {
                    keyTypeMap.put(factorShowVo.getFieldName(), factorShowVo.getEncryptionType());
                    keyTypeMap.put(caseKey,factorShowVo.getEncryptionType()); // 同时存一份转换的名称
                }
                builder.append(factorShowVo.getFieldName()).append(" as ").append(caseKey).append(" , ");
                if (Objects.equals("date", factorShowVo.getFieldType())) {
                    dateList.add(caseKey);
                }
            });

            querySql += builder.toString();
            if (StrUtil.isNotBlank(jumpId)) {
                querySql += jumpId + " as personcollect_latest_id , " + keyCode + " ";
            } else {
                querySql += keyCode + " ";
            }
        }
        result.setKeyMap(keyMap);
        List<FactorFilterVo> filterList = query.getFilterList();
        StringBuilder stringBuilder = new StringBuilder();
        List<String> gridCodes = permissionService.getPermissionLevelByGridCode();

        if (CollectionUtils.isNotEmpty(filterList)) {
            List<FactorFilterVo> regionFilterList = filterList.stream().filter(s -> Objects.equals("区域范围", s.getFieldName()) && Objects.equals("region", s.getFieldType())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(regionFilterList)) {
                FactorFilterVo regionFilter = regionFilterList.get(0);
                gridCodes = getGridCodes(regionFilter);
                filterList.removeAll(regionFilterList);
            }

            // 获取加密的字段
            List<FactorFilterVo> encryptList = filterList.stream().filter(s -> EncryptFieldUtil.encrypt(s.getFieldName())).collect(Collectors.toList());
            filterList.removeAll(encryptList);

            // 获取字典翻译的字段
            List<FactorFilterVo> dictList = filterList.stream().filter(s -> StringUtils.isNotEmpty(s.getDicTable()) && StringUtils.isNotEmpty(s.getDicTypeCode()) && StringUtils.isNotEmpty(s.getDicLevelCode())).collect(Collectors.toList());
            filterList.removeAll(dictList);

            List<FactorFilterVo> varcharFilterList = filterList.stream().filter(s -> Objects.equals("varchar", s.getFieldType())).collect(Collectors.toList());
            List<FactorFilterVo> intFilterList = filterList.stream().filter(s -> Objects.equals("int", s.getFieldType()) || Objects.equals("double", s.getFieldType())).collect(Collectors.toList());
            List<FactorFilterVo> datetimeFilterList = filterList.stream().filter(s -> Objects.equals("datetime", s.getFieldType()) || Objects.equals("date", s.getFieldType())).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(encryptList)) {
                encryptList.stream().forEach(filter -> {
                    String str = null;
                    try {
                        str = SM4Utils.getsM4Utils().strEncode(filter.getCalValue(), SM4Utils.getsM4Utils().getSecretKey());
                        stringBuilder.append(" and ").append(filter.getFieldName()).append(" = '").append(str).append("' ");
                    } catch (Exception e) {
                        log.error("加密失败", e);
                        throw new BusinessException("系统错误");
                    }
                });
            }

            if (CollectionUtils.isNotEmpty(dictList)) {
                dictList.stream().forEach(filter -> {
                    if (CollectionUtils.isNotEmpty(filter.getCalValueList())) {
                        String inSql = filter.getCalValueList().stream()
                                .map(s -> "'" + s + "'")
                                .collect(Collectors.joining(","));
                        stringBuilder.append(" and  ").append(filter.getFieldName()).append(" in ( ").append(inSql).append(" )");
                    } else if (StringUtils.isNotEmpty(filter.getCalValue())) {
                        stringBuilder.append(" and ( CAST( ").append(filter.getFieldName()).append(" AS varchar) = '").append(filter.getCalValue()).append("' )");
                    }
                });
            }

            if (CollectionUtils.isNotEmpty(varcharFilterList)) {
                varcharFilterList.stream().forEach(filter -> {
                    stringBuilder.append(" and ( CAST( ").append(filter.getFieldName()).append(" AS varchar) like '%").append(filter.getCalValue()).append("%' )");

                });
            }
            if (CollectionUtils.isNotEmpty(intFilterList)) {
                intFilterList.stream().forEach(filter -> {
                    if(StringUtils.isNotBlank(filter.getStartValue())) {
                        stringBuilder.append(" and ( CAST( ").append(filter.getFieldName()).append(" AS NUMERIC ) >=  ").append(filter.getStartValue()).append(" )");
                    }
                    if(StringUtils.isNotBlank(filter.getEndValue())) {
                        stringBuilder.append(" and ( CAST( ").append(filter.getFieldName()).append(" AS NUMERIC ) <=  ").append(filter.getEndValue()).append(" )");
                    }
                    });
            }
            if (CollectionUtils.isNotEmpty(datetimeFilterList)) {
                datetimeFilterList.stream().forEach(filter -> {
                    if(StringUtils.isNotBlank(filter.getStartValue())) {
                    stringBuilder.append(" and ( ").append(filter.getFieldName()).append(" >=  '").append(filter.getStartValue()).append("')");
                    }
                    if(StringUtils.isNotBlank(filter.getEndValue())) {
                        stringBuilder.append(" and ( ").append(filter.getFieldName()).append(" <=  '").append(filter.getEndValue()).append("' )");
                    }
                    });
            }
        }
        filterSql += stringBuilder.toString();

        if (CollectionUtils.isEmpty(gridCodes)) {
            return null;
        } else if (gridCodes.size() == 1 && "南山区".equals(gridCodes.get(0))) {
            gridCodes = null;
        }

        Page<Map<String, Object>> page = new Page<>(query.getPageNo(), query.getPageSize());
        Page<Map<String, Object>> resultPage = analysisLayerMetafieldMapper.getFactorPage(page, querySql, filterSql, orderBy, query.getLayerMetaTagView(), gridCodes);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (CollectionUtils.isNotEmpty(resultPage.getRecords())) {
            List<String> typeCodeList = query.getShowList().stream()
                    .map(FactorShowVo::getDicTypeCode)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());
            List<String> levelCodeList = query.getShowList().stream()
                    .map(FactorShowVo::getDicLevelCode)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());
            List<AppDicts> appDictsList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(typeCodeList) && CollectionUtils.isNotEmpty(levelCodeList)) {
                appDictsList = appDictsMapper.getAppDictsByTypeCodeList(typeCodeList, levelCodeList);
                Map<String, Map<String, String>> dictMap = DictUtil.getDictMap(appDictsList, query.getShowList());
                List<Map<String, Object>> records = resultPage.getRecords();
                records.stream().forEach(map -> {
                    map.entrySet().stream()
                            .map(entry -> {
                                if (Objects.nonNull(dictMap.get(entry.getKey()))) {
                                    if (Objects.nonNull(entry.getValue())) {
                                        String newValue = dictMap.get(entry.getKey()).get(String.valueOf(entry.getValue()));
                                        if (Objects.nonNull(newValue)) {
                                            entry.setValue(newValue);
                                        }
                                    }
                                }
                                if (dateList.contains(entry.getKey())) {
                                    Object value = entry.getValue();
                                    if (value instanceof Date) {
                                        // 可以转换为Date对象
                                        Date date = (Date) value;
                                        // 继续进行相应的操作
                                        String formattedDate = format.format(date);
                                        entry.setValue(formattedDate);
                                    }
                                }
                                return entry;
                            })
                            .collect(Collectors.toList());
                });
                List<Map<String, Object>> modifiedList = records.stream()
                        .map(mapObj -> {
                            Map<String, Object> modifiedMap = new HashMap<>();
                            mapObj.forEach((key, value) -> {
                                if (caseTo.containsKey(key)) {
                                    modifiedMap.put(caseTo.get(key), value);
                                } else {
                                    modifiedMap.put(key, value);
                                }
                                // 检查字段是否要进行非脱敏操作
                                if(!keyTypeMap.isEmpty() && keyTypeMap.containsKey(key)) {
                                    String val = ObjectUtils.isNotEmpty(value) ? value.toString() : "";
                                    if(caseTo.containsKey(key)) {
                                        modifiedMap.put(caseTo.get(key), EncryptFieldUtil.mask(val, keyTypeMap.get(key), true, false));
                                    } else {
                                        modifiedMap.put(key, EncryptFieldUtil.mask(val, keyTypeMap.get(key), true, false));
                                    }
                                }
                            });
                            return modifiedMap;
                        })
                        .collect(Collectors.toList());

                resultPage.setRecords(modifiedList);
            } else {
                List<Map<String, Object>> records = resultPage.getRecords();
                records.stream().forEach(map -> {
                    map.entrySet().stream()
                            .map(entry -> {
                                if (dateList.contains(entry.getKey())) {
                                    Object value = entry.getValue();
                                    if (value instanceof Date) {
                                        // 可以转换为Date对象
                                        Date date = (Date) value;
                                        // 继续进行相应的操作
                                        String formattedDate = format.format(date);
                                        entry.setValue(formattedDate);
                                    }
                                }
                                return entry;
                            })
                            .collect(Collectors.toList());
                });
                List<Map<String, Object>> modifiedList = records.stream()
                        .map(mapObj -> {
                            Map<String, Object> modifiedMap = new HashMap<>();
                            mapObj.forEach((key, value) -> {
                                if (caseTo.containsKey(key)) {
                                    modifiedMap.put(caseTo.get(key), value);
                                } else {
                                    modifiedMap.put(key, value);
                                }
                                // 检查字段是否要进行非脱敏操作
                                if(!keyTypeMap.isEmpty() && keyTypeMap.containsKey(key)) {
                                    String val = ObjectUtils.isNotEmpty(value) ? value.toString() : "";
                                    if(caseTo.containsKey(key)) {
                                        modifiedMap.put(caseTo.get(key), EncryptFieldUtil.mask(val, keyTypeMap.get(key), true, false));
                                    } else {
                                        modifiedMap.put(key, EncryptFieldUtil.mask(val, keyTypeMap.get(key), true, false));
                                    }
                                }
                            });
                            return modifiedMap;
                        })
                        .collect(Collectors.toList());
                if (StringUtils.equals(legalCode, keyCode)) {
                    modifiedList.forEach(info -> {
                        String optType = info.get("opt_type").toString();
                        if (!StringUtils.equals(LegalCollectionEnum.INTERVIEW.getCode(), optType)) {
                            info.put("opt_time", null);
                        }
                    });
                }
                resultPage.setRecords(modifiedList);
            }
        }
        if (StringUtils.equals(legalCode, keyCode)) {
            Map<String, String> keyMap1 = result.getKeyMap();
            keyMap1.remove("opt_type");
        }
        result.setListPage(resultPage);
        return result;
    }

    @Override
    public FactorListVo getFactorListNew(FactorQuery query) {



        FactorListVo result = new FactorListVo();
        List<FactorShowVo> showList = query.getShowList();
        Map<String, String> keyMap = new LinkedHashMap<>();
        Map<String, String> keyTypeMap = new LinkedHashMap<>();
        String keyCode = JumpKeyEnum.getValueByCode(query.getLayerMetaTagView());
        if (StringUtils.isEmpty(keyCode)) {
            throw new BusinessException("请选择正确的主题");
        }
        String zzKeyCode = StrUtil.toCamelCase(keyCode);
        String jumpId = FactorUtil.getPrimary(query.getLayerMetaTagView());
        result.setJumpKey(zzKeyCode);
        result.setJumpId(StrUtil.toCamelCase(jumpId));
        String legalCode = JumpKeyEnum.LEGAL.getValue();//法人code
        if (StringUtils.equals(legalCode, keyCode) && CollectionUtils.isNotEmpty(showList)) {
            FactorShowVo factorShowVo = new FactorShowVo();
            factorShowVo.setFieldName("opt_type");
            factorShowVo.setFieldType("varchar");
            factorShowVo.setTitle("操作类型");
            showList.add(factorShowVo);
        }
        String querySql = "";
        String orderBy = "";
        String filterSql = "";
        if (Objects.equals(1, query.getIsDeWeight()) && Objects.equals("bz_person_collect_latest_tagview", query.getLayerMetaTagView())) {
            // 人口查询特殊要求,勾选去重后,根据身份证号去重查询
            querySql += "DISTINCT ON (cardno)";
            orderBy += "ORDER BY cardno, personcollect_latest_id,opt_time";
            filterSql += "and living_status = '1' ";
        } else {
            String primary = FactorUtil.getPrimary(query.getLayerMetaTagView());
            orderBy += "ORDER BY "+primary ;
        }
        StringBuilder builder = new StringBuilder();
        //Map <String,String>original = new HashMap<>();
        Map<String, String> caseTo = new HashMap<>();
        caseTo.put(zzKeyCode, zzKeyCode);
        List<String> dateList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(showList)) {
            showList.stream().forEach(factorShowVo -> {
                String caseKey = getCase(factorShowVo.getFieldName());
                //original.put(factorShowVo.getFieldName(),caseKey);
                caseTo.put(caseKey, factorShowVo.getFieldName());
                keyMap.put(factorShowVo.getFieldName(), factorShowVo.getTitle());
                if(StringUtils.isNotBlank(factorShowVo.getEncryptionType())) {
                    keyTypeMap.put(factorShowVo.getFieldName(), factorShowVo.getEncryptionType());
                    keyTypeMap.put(caseKey,factorShowVo.getEncryptionType()); // 同时存一份转换的名称
                }
                builder.append(factorShowVo.getFieldName()).append(" as ").append(caseKey).append(" , ");
                if (Objects.equals("date", factorShowVo.getFieldType())) {
                    dateList.add(caseKey);
                }
            });

            querySql += builder.toString();
            querySql += jumpId + " , " + keyCode + " ";
        }
        result.setKeyMap(keyMap);
        List<FactorFilterVo> filterList = query.getFilterList();
        StringBuilder stringBuilder = new StringBuilder();
        List<String> gridCodes = permissionService.getPermissionLevelByGridCode();
        //组合视图查询
        String mainView = query.getLayerMetaTagView();
        String personView = JumpKeyEnum.PERSON.getCode();
        String buildingView = JumpKeyEnum.BUILDING.getCode();
        String houseView = JumpKeyEnum.HOUSE.getCode();
        String queryViewSql; //查询视图组合
        String mainViewType;//查找主表别名
        if(mainView.equals(personView)){
            //人口查询
            queryViewSql = personView + " person left join " + buildingView +" building on person.building_code=building.bd_code left join " +
                    houseView + " house on person.house_code=house.house_code  ";
            mainViewType = "person";
        }else{
            //暂时先只做人口试用看效果
            return null;
        }
        if (CollectionUtils.isNotEmpty(filterList)) {
            List<FactorFilterVo> regionFilterList = filterList.stream().filter(s -> Objects.equals("区域范围", s.getFieldName()) && Objects.equals("region", s.getFieldType())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(regionFilterList)) {
                FactorFilterVo regionFilter = regionFilterList.get(0);
                gridCodes = getGridCodes(regionFilter);
                filterList.removeAll(regionFilterList);
            }


            // 获取加密的字段
            List<FactorFilterVo> encryptList = filterList.stream().filter(s -> EncryptFieldUtil.encrypt(s.getFieldName())).collect(Collectors.toList());
            filterList.removeAll(encryptList);

            // 获取字典翻译的字段
            List<FactorFilterVo> dictList = filterList.stream().filter(s -> StringUtils.isNotEmpty(s.getDicTable()) && StringUtils.isNotEmpty(s.getDicTypeCode()) && StringUtils.isNotEmpty(s.getDicLevelCode())).collect(Collectors.toList());
            filterList.removeAll(dictList);

            List<FactorFilterVo> varcharFilterList = filterList.stream().filter(s -> Objects.equals("varchar", s.getFieldType())).collect(Collectors.toList());
            List<FactorFilterVo> intFilterList = filterList.stream().filter(s -> Objects.equals("int", s.getFieldType()) || Objects.equals("double", s.getFieldType())).collect(Collectors.toList());
            List<FactorFilterVo> datetimeFilterList = filterList.stream().filter(s -> Objects.equals("datetime", s.getFieldType()) || Objects.equals("date", s.getFieldType())).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(encryptList)) {
                encryptList.stream().forEach(filter -> {
                    String str = null;
                    try {
                        str = SM4Utils.getsM4Utils().strEncode(filter.getCalValue(), SM4Utils.getsM4Utils().getSecretKey());
                        stringBuilder.append(" and ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" = '").append(str).append("' ");
                    } catch (Exception e) {
                        log.error("加密失败", e);
                        throw new BusinessException("系统错误");
                    }
                });
            }

            if (CollectionUtils.isNotEmpty(dictList)) {
                dictList.stream().forEach(filter -> {
                    if (CollectionUtils.isNotEmpty(filter.getCalValueList())) {
                        if (StringUtils.isNotBlank(filter.getTagCutMulti())) {
                            stringBuilder.append(" and ( ");
                            filter.getCalValueList().forEach(s ->
                                    stringBuilder.append(" CAST( ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" AS varchar) like '%").append(s).append("%' or ")
                            );
                            stringBuilder.append(" 1=0 )");
                        } else {
                            String inSql = filter.getCalValueList().stream()
                                    .map(s -> "'" + s + "'")
                                    .collect(Collectors.joining(","));
                            stringBuilder.append(" and  ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" in ( ").append(inSql).append(" )");
                        }
                    } else if (StringUtils.isNotEmpty(filter.getCalValue())) {
                        stringBuilder.append(" and ( CAST( ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" AS varchar) = '").append(filter.getCalValue()).append("' )");
                    }
                });
            }

            if (CollectionUtils.isNotEmpty(varcharFilterList)) {
                varcharFilterList.stream().forEach(filter -> {
                    if (StringUtils.isNotBlank(filter.getCalValue())) {
                        stringBuilder.append(" and ( CAST( ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" AS varchar) like '%").append(filter.getCalValue()).append("%' )");
                    }

                    if (CollectionUtils.isNotEmpty(filter.getCalValueList())) {
                        stringBuilder.append(" and ( ");
                        filter.getCalValueList().forEach(s ->
                                stringBuilder.append(" CAST( ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" AS varchar) like '%").append(s).append("%' or ")
                        );
                        stringBuilder.append(" 1=0 )");
                    }
                });
            }
            if (CollectionUtils.isNotEmpty(intFilterList)) {
                intFilterList.stream().forEach(filter -> {
                    if(mainViewType.equals("person")&&"age".equals(filter.getFieldName())){
                        if(Objects.nonNull(filter.getStartValue())) {
                            stringBuilder.append(" and ( CAST( EXTRACT(YEAR FROM AGE(CAST(person.birthday AS DATE)))  AS NUMERIC ) >=  ").append(filter.getStartValue()).append(" )");
                        }
                        if(Objects.nonNull(filter.getEndValue())) {
                            stringBuilder.append(" and ( CAST( EXTRACT(YEAR FROM AGE(CAST(person.birthday AS DATE)))  AS NUMERIC ) <=  ").append(filter.getEndValue()).append(" )");
                        }
                        }else {
                        if(Objects.nonNull(filter.getStartValue())) {
                            stringBuilder.append(" and ( CAST( ").append(filter.getFactorType() == null ? mainViewType : filter.getFactorType()).append(".").append(filter.getFieldName()).append(" AS NUMERIC ) >=  ").append(filter.getStartValue()).append(" )");
                        }
                        if(Objects.nonNull(filter.getEndValue())) {
                            stringBuilder.append(" and ( CAST( ").append(filter.getFactorType() == null ? mainViewType : filter.getFactorType()).append(".").append(filter.getFieldName()).append(" AS NUMERIC ) <=  ").append(filter.getEndValue()).append(" )");
                        }
                        }
                });
            }
            if (CollectionUtils.isNotEmpty(datetimeFilterList)) {
                datetimeFilterList.stream().forEach(filter -> {
                    if(Objects.nonNull(filter.getStartValue())) {
                        stringBuilder.append(" and ( ").append(filter.getFactorType() == null ? mainViewType : filter.getFactorType()).append(".").append(filter.getFieldName()).append(" >=  '").append(filter.getStartValue()).append("')");
                    }
                    if(Objects.nonNull(filter.getEndValue())) {
                        stringBuilder.append(" and ( ").append(filter.getFactorType() == null ? mainViewType : filter.getFactorType()).append(".").append(filter.getFieldName()).append(" <=  '").append(filter.getEndValue()).append("' )");
                    }
                    });
            }
        }
        filterSql += stringBuilder.toString();

        if (CollectionUtils.isEmpty(gridCodes)) {
            return null;
        } else if (gridCodes.size() == 1 && "南山区".equals(gridCodes.get(0))) {
            gridCodes = null;
        }


        Page<Map<String, Object>> page = new Page<>(query.getPageNo(), query.getPageSize());
        Page<Map<String, Object>> resultPage = analysisLayerMetafieldMapper.getFactorPageNew(page, querySql, filterSql, orderBy, queryViewSql, gridCodes,mainViewType);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (CollectionUtils.isNotEmpty(resultPage.getRecords())) {
            List<String> typeCodeList = query.getShowList().stream()
                    .map(FactorShowVo::getDicTypeCode)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());
            List<String> levelCodeList = query.getShowList().stream()
                    .map(FactorShowVo::getDicLevelCode)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());
            List<AppDicts> appDictsList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(typeCodeList) && CollectionUtils.isNotEmpty(levelCodeList)) {
                appDictsList = appDictsMapper.getAppDictsByTypeCodeList(typeCodeList, levelCodeList);
                Map<String, Map<String, String>> dictMap = DictUtil.getDictMap(appDictsList, query.getShowList());
                List<Map<String, Object>> records = resultPage.getRecords();
                records.stream().forEach(map -> {
                    map.entrySet().stream()
                            .map(entry -> {
                                if (Objects.nonNull(dictMap.get(entry.getKey()))) {
                                    if (Objects.nonNull(entry.getValue())) {
                                        String newValue = dictMap.get(entry.getKey()).get(String.valueOf(entry.getValue()));
                                        if (Objects.nonNull(newValue)) {
                                            entry.setValue(newValue);
                                        }
                                    }
                                }
                                if (dateList.contains(entry.getKey())) {
                                    Object value = entry.getValue();
                                    if (value instanceof Date) {
                                        // 可以转换为Date对象
                                        Date date = (Date) value;
                                        // 继续进行相应的操作
                                        String formattedDate = format.format(date);
                                        entry.setValue(formattedDate);
                                    }
                                }
                                return entry;
                            })
                            .collect(Collectors.toList());
                });
                List<Map<String, Object>> modifiedList = records.stream()
                        .map(mapObj -> {
                            Map<String, Object> modifiedMap = new HashMap<>();
                            mapObj.forEach((key, value) -> {
                                if (caseTo.containsKey(key)) {
                                    modifiedMap.put(caseTo.get(key), value);
                                } else {
                                    modifiedMap.put(key, value);
                                }

                                // 检查字段是否要进行非脱敏操作
                                if(!keyTypeMap.isEmpty() && keyTypeMap.containsKey(key)) {
                                    String val = ObjectUtils.isNotEmpty(value) ? value.toString() : "";
                                    if(caseTo.containsKey(key)) {
                                        modifiedMap.put(caseTo.get(key), EncryptFieldUtil.mask(val, keyTypeMap.get(key), true, false));
                                    } else {
                                        modifiedMap.put(key, EncryptFieldUtil.mask(val, keyTypeMap.get(key), true, false));
                                    }
                                }
                            });
                            return modifiedMap;
                        })
                        .collect(Collectors.toList());

                resultPage.setRecords(modifiedList);
            } else {
                List<Map<String, Object>> records = resultPage.getRecords();
                records.stream().forEach(map -> {
                    map.entrySet().stream()
                            .map(entry -> {
                                if (dateList.contains(entry.getKey())) {
                                    Object value = entry.getValue();
                                    if (value instanceof Date) {
                                        // 可以转换为Date对象
                                        Date date = (Date) value;
                                        // 继续进行相应的操作
                                        String formattedDate = format.format(date);
                                        entry.setValue(formattedDate);
                                    }
                                }
                                return entry;
                            })
                            .collect(Collectors.toList());
                });
                List<Map<String, Object>> modifiedList = records.stream()
                        .map(mapObj -> {
                            Map<String, Object> modifiedMap = new HashMap<>();
                            mapObj.forEach((key, value) -> {
                                if (caseTo.containsKey(key)) {
                                    modifiedMap.put(caseTo.get(key), value);
                                } else {
                                    modifiedMap.put(key, value);
                                }
                                // 检查字段是否要进行非脱敏操作
                                if(!keyTypeMap.isEmpty() && keyTypeMap.containsKey(key)) {
                                    String val = ObjectUtils.isNotEmpty(value) ? value.toString() : "";
                                    if(caseTo.containsKey(key)) {
                                        modifiedMap.put(caseTo.get(key), EncryptFieldUtil.mask(val, keyTypeMap.get(key), true, false));
                                    } else {
                                        modifiedMap.put(key, EncryptFieldUtil.mask(val, keyTypeMap.get(key), true, false));
                                    }
                                }
                            });
                            return modifiedMap;
                        })
                        .collect(Collectors.toList());
                if (StringUtils.equals(legalCode, keyCode)) {
                    modifiedList.forEach(info -> {
                        String optType = info.get("opt_type").toString();
                        if (!StringUtils.equals(LegalCollectionEnum.INTERVIEW.getCode(), optType)) {
                            info.put("opt_time", null);
                        }
                    });
                }
                resultPage.setRecords(modifiedList);
            }
        }
        if (StringUtils.equals(legalCode, keyCode)) {
            Map<String, String> keyMap1 = result.getKeyMap();
            keyMap1.remove("opt_type");
        }
        result.setListPage(resultPage);
        return result;
    }

    @Override
    public List<FactorFieldValueDicVo> getValuesByFieldName(FactorFieldQuery query) {
        List<String> valueList = new ArrayList<>();
        if(StringUtils.isNotBlank(query.getFactorType())){
            AnalysisLayerMetaEntity analysisLayerMeta = analysisLayerMetafieldMapper.getViewNameByLayerName(FmTcBelongTypeEnum.getValueByCode(query.getFactorType()));

            // 设置视图表名
            query.setLayerMetaTagView(analysisLayerMeta.getLayerMetaTagview());
            query.setLayerMetaTableName(analysisLayerMeta.getLayerMetaTablename());
            query.setLayerMetaTagtable(analysisLayerMeta.getLayerMetaTagtable());
        }
        if (Objects.equals("1", query.getType())) {
            valueList = analysisLayerMetafieldMapper.getValuesByFieldName(query.getLayerMetaTableName(), query.getFieldName());
        } else if (Objects.equals("2", query.getType())) {
            valueList = appTagMapper.getTagValues(query.getLayerMetaTagtable(), query.getFieldName());

            // 使用分隔符
            if (StringUtils.isNotBlank(query.getTagCutMulti())) {
                if (CollectionUtils.isNotEmpty(valueList)) {
                    valueList = valueList.stream().filter(StringUtils::isNotBlank).flatMap(value -> {
                        String[] split = value.split(query.getTagCutMulti());
                        return Stream.of(split);
                    }).distinct().collect(Collectors.toList());
                }
            }

        }
        List<FactorFieldValueDicVo> factorFieldValueDicVos = new ArrayList<>();
        if (StringUtils.isNotEmpty(query.getDicTable()) && StringUtils.isNotEmpty(query.getDicTypeCode())
                && StringUtils.isNotEmpty(query.getDicLevelCode()) && CollectionUtil.isNotEmpty(valueList)) {
            List<Map<String, Object>> dicCodeNameMapList = analysisLayerMetafieldMapper.getDicByTypeCodeAndLevelCode(query.getDicTable(), query.getDicTypeCode(), query.getDicLevelCode());
            if (CollectionUtils.isNotEmpty(dicCodeNameMapList)) {
                for (Map<String, Object> dict: dicCodeNameMapList) {
                    FactorFieldValueDicVo factorFieldValueDicVo = new FactorFieldValueDicVo();
                    factorFieldValueDicVo.setCode(dict.get("code").toString());
                    factorFieldValueDicVo.setName(dict.get("name").toString());
                    factorFieldValueDicVos.add(factorFieldValueDicVo);
                }
            }
//            for (String strCode : valueList) {
//                List<Map<String, Object>> dicTempList = dicCodeNameMapList.stream().filter(s -> s.get("code").toString().equals(strCode)).collect(Collectors.toList());
//                if (CollectionUtil.isNotEmpty(dicTempList)) {
//                    FactorFieldValueDicVo factorFieldValueDicVo = new FactorFieldValueDicVo();
//                    factorFieldValueDicVo.setCode(strCode);
//                    factorFieldValueDicVo.setName(dicTempList.get(0).get("name").toString());
//                    factorFieldValueDicVos.add(factorFieldValueDicVo);
//                }
//            }
        } else {
            for (String strCode : valueList) {
                if (StringUtils.isNotEmpty(strCode)) {
                    FactorFieldValueDicVo factorFieldValueDicVo = new FactorFieldValueDicVo();
                    factorFieldValueDicVo.setCode(strCode);
                    factorFieldValueDicVo.setName(strCode);
                    factorFieldValueDicVos.add(factorFieldValueDicVo);
                }
            }
        }

        return factorFieldValueDicVos;
    }

    @Override
    public List<AppTagVo> getTags(String tagTable) {
        return this.appTagMapper.getTags(tagTable);
    }

    @Override
    public void updateField(FactorUpdateParam param) {
        UserLoginVo userLoginVo = userSystemService.getUserByToken();
        if (userLoginVo == null) {
            throw new BusinessException("当前登录用户信息为空!");

        }
        String userId = userLoginVo.getUserId();
        List<FactorFieldVo> fieldVoList = param.getFieldVoList();
        String context = JSON.toJSONString(fieldVoList);
        FactorPlan factorPlan = factorPlanMapper.getUserByLayer(userId, param.getLayerMetaLayername());
        if (Objects.nonNull(factorPlan)) {
            if (Objects.equals("filter", param.getType())) {
                factorPlan.setFilterContent(context);
            } else if (Objects.equals("show", param.getType())) {
                factorPlan.setShowContent(context);
            }
            factorPlan.setUpdatetime(new Date());
            factorPlanMapper.updateById(factorPlan);
        } else {
            factorPlan = new FactorPlan();
            factorPlan.setLayer(param.getLayerMetaLayername());
            if (Objects.equals("filter", param.getType())) {
                factorPlan.setFilterContent(context);
            } else if (Objects.equals("show", param.getType())) {
                factorPlan.setShowContent(context);
            }
            factorPlan.setUserId(userId);
            factorPlan.setCreatetime(new Date());
            factorPlan.setUpdatetime(new Date());
            factorPlanMapper.insert(factorPlan);
        }
    }

    @Override
    public Object sendVerificationCode() {
        UserLoginVo userLoginVo = userSystemService.getUserByToken();
        if (userLoginVo == null) {
            throw new BusinessException("当前登录用户信息为空!");

        }
        String phone = userLoginVo.getPhone();
        if (StringUtils.isBlank(phone)) {
            throw new BusinessException("当前登录用户手机号为空!");
        }
        // 先从缓存取,缓存有就不再生成
        Object obj = redisTemplate.opsForValue().get(userLoginVo.getUserId() + VERIFICATION_CODE);
        if (obj != null) {
            return obj;
        }
        // 生成验证码
        String code = generateVerificationCode(6);


        // 放入缓存,缓存1分钟
        redisTemplate.opsForValue().set(userLoginVo.getUserId() + VERIFICATION_CODE, code, 1, TimeUnit.MINUTES);
        if (Objects.equals("config-sharding-test", activeProfile)) {
            // 测试环境返回验证码
            return code;
        } else {
            // 发送短信
            SendSmsVo smsVo = new SendSmsVo();
            smsVo.setMobile(phone);
            smsVo.setContent(code);
            smsService.sendSms(smsVo);
        }
        return null;
    }

    @Override
    public void exportFactorList(HttpServletResponse response, FactorExportParam param) throws Exception {
        UserLoginVo userLoginVo = userSystemService.getUserByToken();
        if (userLoginVo == null) {
            throw new BusinessException("当前登录用户信息为空!");

        }
        String phone = userLoginVo.getPhone();
        if (StringUtils.isBlank(phone)) {
            throw new BusinessException("当前登录用户手机号为空!");
        }

        FactorQuery query = param.getFactorQuery();
        String code = param.getCode();
        Object obj = redisTemplate.opsForValue().get(userLoginVo.getUserId() + VERIFICATION_CODE);
        if (obj != null) {
            if (!Objects.equals(obj.toString(), code)) {
                throw new BusinessException("验证码输入有误,请重新输入!");
            }
        } else {
            throw new BusinessException("验证码输入有误,请重新输入!");
        }

        // 如果不脱敏,检查当前用户是否有对应的角色权限
        boolean desensitization = false;
        if("0".equals(param.getIsDesensitization())) {
            SystemCommonConfig config = systemCommonConfigService.selectSystemCommonConfigByMc("comprehensive_query", "desensitizationRole");
            if(config == null) {
                throw new BusinessException("当前非脱敏角色配置误,请检查!");
            }
            String menuCode = config.getConfigValue();
            List<UserMenu> menuList = userLoginVo.getMenuList();
            if(CollectionUtils.isEmpty(menuList) || StringUtils.isBlank(menuCode)) {
                throw new BusinessException("当前非脱敏角色配置误,请检查!");
            }
            // 获取菜单信息
            List<String> codes = UserUtils.getUserAllMenuCodes(menuList);
            desensitization = codes.contains(menuCode);
            if(!desensitization) {
                throw new BusinessException("您当前没有权限进行非脱敏导出!");
            }
        }

        String filename = "人口";
        OutputStream outputStream = HttpResponseUtil.excelOutput(response, filename);
        try (ExcelWriter excelWriter = EasyExcel.write(outputStream).build()) {
            // 只查询总数
            String querySql;
            if (Objects.equals("bz_person_collect_latest_tagview", query.getLayerMetaTagView())) {

                querySql = getQuerySqlNew(query);;
            } else {
                querySql = getQuerySql(query);
            }
            String queryCountSql = getQueryCountSql(querySql);
            int selectCount = factorPlanMapper.selectCountBySql(queryCountSql);
//                int selectCount = SqlRunner.db().selectCount(analysisSqlVo.getStrQueryCountSql());
            Map<String, String> keyTypeMap = new LinkedHashMap<>();
            List<String> dataList = getDataList(query.getShowList());
            List<String> doubleList = getDoubleList(query.getShowList());
            Map<String, String> caseTo = getCaseTo(query.getShowList());
            Map<String, Map<String, String>> dictMap = getDictMap(query);
            Map<String, String> keyMap = getKeyMap(query.getShowList());
            List<FactorShowVo> showList = query.getShowList();
            if (CollectionUtils.isNotEmpty(showList)) {
                showList.stream().forEach(factorShowVo -> {
                    if(StringUtils.isNotBlank(factorShowVo.getEncryptionType())) {
                        String caseKey = getCase(factorShowVo.getFieldName());
                        keyTypeMap.put(factorShowVo.getFieldName(), factorShowVo.getEncryptionType());
                        keyTypeMap.put(caseKey, factorShowVo.getEncryptionType()); // 如果有转换的名称也存一份
                    }
                });
            }

            IPage<Map<String, Object>> countPage = new Page<>(0, EXPORT_PAGE_SIZE, selectCount);
            if (countPage.getPages() < 1) {
                return;
            }
            runExport(excelWriter, querySql,keyMap,dictMap,dataList,doubleList,caseTo, countPage.getPages(), keyTypeMap,desensitization);
        }
    }

    /**
     * 通过泛型设置通用导出模板
     */
    private <T> void runExport(ExcelWriter excelWriter, String querySql, Map<String, String> headerMap, Map<String, Map<String, String>> dictMap, List<String> dataList,
                               List<String> doubleList,Map<String, String> caseTo, long totalPage,Map<String, String> keyTypeMap,boolean desensitization) throws ExecutionException, InterruptedException {
        // 获取header
        List<ExcelHeader> headers = new ArrayList<>();
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            ExcelHeader header = new ExcelHeader();
            header.setHeadName(entry.getValue());
            header.setFieldName(entry.getKey());
            headers.add(header);
        }
        ExcelUtil.pageDynamicExcelWriterXParallelManyClass(excelWriter, 8, totalPage, pageNo -> {
            List<Map<String, Object>> records = factorPlanMapper.selectListBySql(querySql + " limit " + EXPORT_PAGE_SIZE + " OFFSET " + ((pageNo - 1) * EXPORT_PAGE_SIZE));
            records = handlerData(dictMap, records, dataList,doubleList, caseTo, keyTypeMap, desensitization);
            return records;
        }, "", 0, headers);
    }


    private String getQueryCountSql(String querySql) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("select count(1) from (").append(querySql).append(" ) AS TOTAL");
        return stringBuilder.toString();
    }

    private String getQuerySql(FactorQuery query) {
        FactorListVo result = new FactorListVo();
        List<FactorShowVo> showList = query.getShowList();
        Map<String, String> keyMap = new LinkedHashMap<>();
        String keyCode = JumpKeyEnum.getValueByCode(query.getLayerMetaTagView());
        if (StringUtils.isEmpty(keyCode)) {
            throw new BusinessException("请选择正确的主题");
        }
        String zzKeyCode = StrUtil.toCamelCase(keyCode);
        result.setJumpKey(zzKeyCode);
        // 导出接口暂时去除opt_type
//        String legalCode = JumpKeyEnum.LEGAL.getValue();//法人code
//        if (StringUtils.equals(legalCode, keyCode) && CollectionUtils.isNotEmpty(showList)) {
//            FactorShowVo factorShowVo = new FactorShowVo();
//            factorShowVo.setFieldName("opt_type");
//            factorShowVo.setFieldType("varchar");
//            factorShowVo.setTitle("操作类型");
//            showList.add(factorShowVo);
//        }
        String querySql = "";
        String orderBy = "";
        String filterSql = "";
        if (Objects.equals(1, query.getIsDeWeight()) && Objects.equals("bz_person_collect_latest_tagview", query.getLayerMetaTagView())) {
            // 人口查询特殊要求,勾选去重后,根据身份证号去重查询
            querySql += "DISTINCT ON (cardno)";
            orderBy += "ORDER BY cardno, personcollect_latest_id,opt_time";
            filterSql += "and living_status = '1' ";

        } else {
            String primary = FactorUtil.getPrimary(query.getLayerMetaTagView());
            orderBy += "ORDER BY "+primary ;
        }
        StringBuilder builder = new StringBuilder();
        //Map <String,String>original = new HashMap<>();
        Map<String, String> caseTo = new HashMap<>();
        caseTo.put(zzKeyCode, zzKeyCode);
        List<String> dateList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(showList)) {
            showList.stream().forEach(factorShowVo -> {
                String caseKey = getCase(factorShowVo.getFieldName());
                //original.put(factorShowVo.getFieldName(),caseKey);
                caseTo.put(caseKey, factorShowVo.getFieldName());
                keyMap.put(factorShowVo.getFieldName(), factorShowVo.getTitle());
                builder.append(factorShowVo.getFieldName()).append(" as ").append(caseKey).append(" , ");
                if (Objects.equals("date", factorShowVo.getFieldType())) {
                    dateList.add(caseKey);
                }
            });

            querySql += builder.toString();
            querySql += keyCode + " ";
        }
        result.setKeyMap(keyMap);
        List<FactorFilterVo> filterList = query.getFilterList();
        StringBuilder stringBuilder = new StringBuilder();
        List<String> gridCodes = permissionService.getPermissionLevelByGridCode();

        if (CollectionUtils.isNotEmpty(filterList)) {
            List<FactorFilterVo> regionFilterList = filterList.stream().filter(s -> Objects.equals("区域范围", s.getFieldName()) && Objects.equals("region", s.getFieldType())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(regionFilterList)) {
                FactorFilterVo regionFilter = regionFilterList.get(0);
                gridCodes = getGridCodes(regionFilter);
                filterList.removeAll(regionFilterList);
            }

            // 获取加密的字段
            List<FactorFilterVo> encryptList = filterList.stream().filter(s -> EncryptFieldUtil.encrypt(s.getFieldName())).collect(Collectors.toList());
            filterList.removeAll(encryptList);

            // 获取字典翻译的字段
            List<FactorFilterVo> dictList = filterList.stream().filter(s -> StringUtils.isNotEmpty(s.getDicTable()) && StringUtils.isNotEmpty(s.getDicTypeCode()) && StringUtils.isNotEmpty(s.getDicLevelCode())).collect(Collectors.toList());
            filterList.removeAll(dictList);

            List<FactorFilterVo> varcharFilterList = filterList.stream().filter(s -> Objects.equals("varchar", s.getFieldType())).collect(Collectors.toList());
            List<FactorFilterVo> intFilterList = filterList.stream().filter(s -> Objects.equals("int", s.getFieldType()) || Objects.equals("double", s.getFieldType())).collect(Collectors.toList());
            List<FactorFilterVo> datetimeFilterList = filterList.stream().filter(s -> Objects.equals("datetime", s.getFieldType()) || Objects.equals("date", s.getFieldType())).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(encryptList)) {
                encryptList.stream().forEach(filter -> {
                    String str = null;
                    try {
                        str = SM4Utils.getsM4Utils().strEncode(filter.getCalValue(), SM4Utils.getsM4Utils().getSecretKey());
                        stringBuilder.append(" and ").append(filter.getFieldName()).append(" = '").append(str).append("' ");
                    } catch (Exception e) {
                        log.error("加密失败", e);
                        throw new BusinessException("系统错误");
                    }
                });
            }

            if (CollectionUtils.isNotEmpty(dictList)) {
                dictList.stream().forEach(filter -> {
                    if (CollectionUtils.isNotEmpty(filter.getCalValueList())) {
                        String inSql = filter.getCalValueList().stream()
                                .map(s -> "'" + s + "'")
                                .collect(Collectors.joining(","));
                        stringBuilder.append(" and  ").append(filter.getFieldName()).append(" in ( ").append(inSql).append(" )");
                    } else if (StringUtils.isNotEmpty(filter.getCalValue())) {
                        stringBuilder.append(" and ( CAST( ").append(filter.getFieldName()).append(" AS varchar) = '").append(filter.getCalValue()).append("' )");
                    }
                });
            }

            if (CollectionUtils.isNotEmpty(varcharFilterList)) {
                varcharFilterList.stream().forEach(filter -> {
                    stringBuilder.append(" and ( CAST( ").append(filter.getFieldName()).append(" AS varchar) like '%").append(filter.getCalValue()).append("%' )");

                });
            }
            if (CollectionUtils.isNotEmpty(intFilterList)) {
                intFilterList.stream().forEach(filter -> {
                    stringBuilder.append(" and ( CAST( ").append(filter.getFieldName()).append(" AS NUMERIC ) >=  ").append(filter.getStartValue()).append(" )");
                    stringBuilder.append(" and ( CAST( ").append(filter.getFieldName()).append(" AS NUMERIC ) <=  ").append(filter.getEndValue()).append(" )");
                });
            }
            if (CollectionUtils.isNotEmpty(datetimeFilterList)) {
                datetimeFilterList.stream().forEach(filter -> {
                    stringBuilder.append(" and ( ").append(filter.getFieldName()).append(" >=  '").append(filter.getStartValue()).append("'");
                    stringBuilder.append(" and ").append(filter.getFieldName()).append(" <=  '").append(filter.getEndValue()).append("' )");
                });
            }
        }
        filterSql += stringBuilder.toString();

        if (CollectionUtils.isEmpty(gridCodes)) {
            return null;
        } else if (gridCodes.size() == 1 && "南山区".equals(gridCodes.get(0))) {
            gridCodes = null;
        }

        StringBuilder sqlBuilding = new StringBuilder();
        sqlBuilding.append("select ").append(querySql).append("  from ").append(query.getLayerMetaTagView()).append(" where 1=1 ");
        sqlBuilding.append(filterSql);
        if (CollectionUtils.isNotEmpty(gridCodes)) {
            sqlBuilding.append(" and grid_code in ( ");
            String codeInSql = gridCodes.stream()
                    .map(s -> "'" + s + "'")
                    .collect(Collectors.joining(","));
            sqlBuilding.append(codeInSql);
            sqlBuilding.append(" ) ");
        }
        if (StringUtils.isNotEmpty(orderBy)) {
            sqlBuilding.append(orderBy);
        }
        return sqlBuilding.toString();
    }

    private String getQuerySqlNew(FactorQuery query) {
        FactorListVo result = new FactorListVo();
        List<FactorShowVo> showList = query.getShowList();
        Map<String, String> keyMap = new LinkedHashMap<>();
        String keyCode = JumpKeyEnum.getValueByCode(query.getLayerMetaTagView());
        if (StringUtils.isEmpty(keyCode)) {
            throw new BusinessException("请选择正确的主题");
        }
        String zzKeyCode = StrUtil.toCamelCase(keyCode);
        result.setJumpKey(zzKeyCode);
        String querySql = "";
        String orderBy = "";
        String filterSql = "";
        if (Objects.equals(1, query.getIsDeWeight()) && Objects.equals("bz_person_collect_latest_tagview", query.getLayerMetaTagView())) {
            // 人口查询特殊要求,勾选去重后,根据身份证号去重查询
            querySql += "DISTINCT ON (cardno)";
            orderBy += "ORDER BY cardno, personcollect_latest_id,opt_time";
            filterSql += "and living_status = '1' ";

        } else {
            String primary = FactorUtil.getPrimary(query.getLayerMetaTagView());
            orderBy += "ORDER BY "+primary ;
        }
        StringBuilder builder = new StringBuilder();
        //Map <String,String>original = new HashMap<>();
        Map<String, String> caseTo = new HashMap<>();
        caseTo.put(zzKeyCode, zzKeyCode);
        List<String> dateList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(showList)) {
            showList.stream().forEach(factorShowVo -> {
                String caseKey = getCase(factorShowVo.getFieldName());
                //original.put(factorShowVo.getFieldName(),caseKey);
                caseTo.put(caseKey, factorShowVo.getFieldName());
                keyMap.put(factorShowVo.getFieldName(), factorShowVo.getTitle());
                builder.append(factorShowVo.getFieldName()).append(" as ").append(caseKey).append(" , ");
                if (Objects.equals("date", factorShowVo.getFieldType())) {
                    dateList.add(caseKey);
                }
            });

            querySql += builder.toString();
            querySql += keyCode + " ";
        }
        result.setKeyMap(keyMap);
        List<FactorFilterVo> filterList = query.getFilterList();
        StringBuilder stringBuilder = new StringBuilder();
        List<String> gridCodes = permissionService.getPermissionLevelByGridCode();

        //组合视图查询
        String mainView = query.getLayerMetaTagView();
        String personView = JumpKeyEnum.PERSON.getCode();
        String buildingView = JumpKeyEnum.BUILDING.getCode();
        String houseView = JumpKeyEnum.HOUSE.getCode();
        String queryViewSql; //查询视图组合
        String mainViewType;//查找主表别名
        if(mainView.equals(personView)){
            //人口查询
            queryViewSql = personView + " person left join " + buildingView +" building on person.building_code=building.bd_code left join " +
                    houseView + " house on person.house_code=house.house_code  ";
            mainViewType = "person";
        }else{
            //暂时先只做人口试用看效果
            return null;
        }

        if (CollectionUtils.isNotEmpty(filterList)) {
            List<FactorFilterVo> regionFilterList = filterList.stream().filter(s -> Objects.equals("区域范围", s.getFieldName()) && Objects.equals("region", s.getFieldType())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(regionFilterList)) {
                FactorFilterVo regionFilter = regionFilterList.get(0);
                gridCodes = getGridCodes(regionFilter);
                filterList.removeAll(regionFilterList);
            }

            // 获取加密的字段
            List<FactorFilterVo> encryptList = filterList.stream().filter(s -> EncryptFieldUtil.encrypt(s.getFieldName())).collect(Collectors.toList());
            filterList.removeAll(encryptList);

            // 获取字典翻译的字段
            List<FactorFilterVo> dictList = filterList.stream().filter(s -> StringUtils.isNotEmpty(s.getDicTable()) && StringUtils.isNotEmpty(s.getDicTypeCode()) && StringUtils.isNotEmpty(s.getDicLevelCode())).collect(Collectors.toList());
            filterList.removeAll(dictList);

            List<FactorFilterVo> varcharFilterList = filterList.stream().filter(s -> Objects.equals("varchar", s.getFieldType())).collect(Collectors.toList());
            List<FactorFilterVo> intFilterList = filterList.stream().filter(s -> Objects.equals("int", s.getFieldType()) || Objects.equals("double", s.getFieldType())).collect(Collectors.toList());
            List<FactorFilterVo> datetimeFilterList = filterList.stream().filter(s -> Objects.equals("datetime", s.getFieldType()) || Objects.equals("date", s.getFieldType())).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(encryptList)) {
                encryptList.stream().forEach(filter -> {
                    String str = null;
                    try {
                        str = SM4Utils.getsM4Utils().strEncode(filter.getCalValue(), SM4Utils.getsM4Utils().getSecretKey());
                        stringBuilder.append(" and ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" = '").append(str).append("' ");
                    } catch (Exception e) {
                        log.error("加密失败", e);
                        throw new BusinessException("系统错误");
                    }
                });
            }

            if (CollectionUtils.isNotEmpty(dictList)) {
                dictList.stream().forEach(filter -> {
                    if (CollectionUtils.isNotEmpty(filter.getCalValueList())) {
                        String inSql = filter.getCalValueList().stream()
                                .map(s -> "'" + s + "'")
                                .collect(Collectors.joining(","));
                        stringBuilder.append(" and  ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" in ( ").append(inSql).append(" )");
                    } else if (StringUtils.isNotEmpty(filter.getCalValue())) {
                        stringBuilder.append(" and ( CAST( ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" AS varchar) = '").append(filter.getCalValue()).append("' )");
                    }
                });
            }

            if (CollectionUtils.isNotEmpty(varcharFilterList)) {
                varcharFilterList.stream().forEach(filter -> {
                    stringBuilder.append(" and ( CAST( ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" AS varchar) like '%").append(filter.getCalValue()).append("%' )");

                });
            }
            if (CollectionUtils.isNotEmpty(intFilterList)) {
                intFilterList.stream().forEach(filter -> {
                    stringBuilder.append(" and ( CAST( ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" AS NUMERIC ) >=  ").append(filter.getStartValue()).append(" )");
                    stringBuilder.append(" and ( CAST( ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" AS NUMERIC ) <=  ").append(filter.getEndValue()).append(" )");
                });
            }
            if (CollectionUtils.isNotEmpty(datetimeFilterList)) {
                datetimeFilterList.stream().forEach(filter -> {
                    stringBuilder.append(" and ( ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" >=  '").append(filter.getStartValue()).append("'");
                    stringBuilder.append(" and ").append(filter.getFactorType()==null?mainViewType:filter.getFactorType()).append(".").append(filter.getFieldName()).append(" <=  '").append(filter.getEndValue()).append("' )");
                });
            }
        }
        filterSql += stringBuilder.toString();

        if (CollectionUtils.isEmpty(gridCodes)) {
            return null;
        } else if (gridCodes.size() == 1 && "南山区".equals(gridCodes.get(0))) {
            gridCodes = null;
        }

        StringBuilder sqlBuilding = new StringBuilder();
        sqlBuilding.append("select ").append(querySql).append("  from (select ").append(mainViewType).append(".* from ").append(queryViewSql).append(" where 1=1 ");
        sqlBuilding.append(filterSql).append(") t where 1=1");
        if (CollectionUtils.isNotEmpty(gridCodes)) {
            sqlBuilding.append(" and grid_code in ( ");
            String codeInSql = gridCodes.stream()
                    .map(s -> "'" + s + "'")
                    .collect(Collectors.joining(","));
            sqlBuilding.append(codeInSql);
            sqlBuilding.append(" ) ");
        }
        if (StringUtils.isNotEmpty(orderBy)) {
            sqlBuilding.append(orderBy);
        }
        return sqlBuilding.toString();
    }

    private List<Map<String, Object>> handlerData(Map<String, Map<String, String>> dictMap, List<Map<String, Object>> records, List<String> dateList,List<String> doubleList, Map<String, String> caseTo,Map<String, String> keyTypeMap,boolean desensitization) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (CollectionUtils.isNotEmpty(records)) {
            records.stream().forEach(map -> {
                map.entrySet().stream()
                        .map(entry -> {
                            if (Objects.nonNull(dictMap.get(entry.getKey()))) {
                                if (Objects.nonNull(entry.getValue())) {
                                    String newValue = dictMap.get(entry.getKey()).get(String.valueOf(entry.getValue()));
                                    if (Objects.nonNull(newValue)) {
                                        entry.setValue(newValue);
                                    }
                                }
                            }
                            if (dateList.contains(entry.getKey())) {
                                Object value = entry.getValue();
                                if (value instanceof Date) {
                                    // 可以转换为Date对象
                                    Date date = (Date) value;
                                    // 继续进行相应的操作
                                    String formattedDate = format.format(date);
                                    entry.setValue(formattedDate);
                                }
                            }
                            if (doubleList.contains(entry.getKey())) {
                                Object value = entry.getValue();
                                if(Objects.nonNull(value)){
                                    String doubleValue = value.toString();
                                    BigDecimal number = new BigDecimal(doubleValue);
                                    BigDecimal scaledNumber = number.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    String formatValue = scaledNumber.toString();
                                    entry.setValue(formatValue);
                                }
                            }
                            return entry;
                        })
                        .collect(Collectors.toList());
            });
            List<Map<String, Object>> modifiedList = records.stream()
                    .map(mapObj -> {
                        Map<String, Object> modifiedMap = new HashMap<>();
                        mapObj.forEach((key, value) -> {
                            if (caseTo.containsKey(key)) {
                                modifiedMap.put(caseTo.get(key), value);
                            } else {
                                modifiedMap.put(key, value);
                            }
                            // 检查字段是否要进行非脱敏操作
                            if(!keyTypeMap.isEmpty() && keyTypeMap.containsKey(key)) {
                                String val = ObjectUtils.isNotEmpty(value) ? value.toString() : "";
                                if(caseTo.containsKey(key)) {
                                    modifiedMap.put(caseTo.get(key), EncryptFieldUtil.mask(val, keyTypeMap.get(key), true, desensitization));
                                } else {
                                    modifiedMap.put(key, EncryptFieldUtil.mask(val, keyTypeMap.get(key), true, desensitization));
                                }
                            }
                        });
                        return modifiedMap;
                    })
                    .collect(Collectors.toList());

            return modifiedList;
        } else {
            records.stream().forEach(map -> {
                map.entrySet().stream()
                        .map(entry -> {
                            if (dateList.contains(entry.getKey())) {
                                Object value = entry.getValue();
                                if (value instanceof Date) {
                                    // 可以转换为Date对象
                                    Date date = (Date) value;
                                    // 继续进行相应的操作
                                    String formattedDate = format.format(date);
                                    entry.setValue(formattedDate);
                                }
                            }
                            return entry;
                        })
                        .collect(Collectors.toList());
            });
            List<Map<String, Object>> modifiedList = records.stream()
                    .map(mapObj -> {
                        Map<String, Object> modifiedMap = new HashMap<>();
                        mapObj.forEach((key, value) -> {
                            if (caseTo.containsKey(key)) {
                                modifiedMap.put(caseTo.get(key), value);
                            } else {
                                modifiedMap.put(key, value);
                            }
                            // 检查字段是否要进行非脱敏操作
                            if(!keyTypeMap.isEmpty() && keyTypeMap.containsKey(key)) {
                                String val = ObjectUtils.isNotEmpty(value) ? value.toString() : "";
                                if(caseTo.containsKey(key)) {
                                    modifiedMap.put(caseTo.get(key), EncryptFieldUtil.mask(val, keyTypeMap.get(key), true, desensitization));
                                } else {
                                    modifiedMap.put(key, EncryptFieldUtil.mask(val, keyTypeMap.get(key), true, desensitization));
                                }
                            }
                        });
                        return modifiedMap;
                    })
                    .collect(Collectors.toList());
            return modifiedList;
        }
    }

    private List<String> getDoubleList(List<FactorShowVo> showList) {
        List<String> doubleList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(showList)) {
            showList.stream().forEach(factorShowVo -> {
                String caseKey = getCase(factorShowVo.getFieldName());
                if (Objects.equals("double", factorShowVo.getFieldType())) {
                    doubleList.add(caseKey);
                }
            });
        }
        return doubleList;
    }

    private List<String> getDataList(List<FactorShowVo> showList) {
        List<String> dateList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(showList)) {
            showList.stream().forEach(factorShowVo -> {
                String caseKey = getCase(factorShowVo.getFieldName());
                if (Objects.equals("date", factorShowVo.getFieldType())) {
                    dateList.add(caseKey);
                }
            });
        }
        return dateList;
    }

    private Map<String, String> getKeyMap(List<FactorShowVo> showList) {
        Map<String, String> keyMap = new LinkedHashMap<>();
        if (CollectionUtils.isNotEmpty(showList)) {
            showList.stream().forEach(factorShowVo -> {
                keyMap.put(factorShowVo.getFieldName(), factorShowVo.getTitle());

            });

        }
        return keyMap;
    }

    private Map<String, String> getCaseTo(List<FactorShowVo> showList) {
        Map<String, String> caseTo = new HashMap<>();
        if (CollectionUtils.isNotEmpty(showList)) {
            showList.stream().forEach(factorShowVo -> {
                String caseKey = getCase(factorShowVo.getFieldName());
                caseTo.put(caseKey, factorShowVo.getFieldName());

            });

        }
        return caseTo;
    }

    private Map<String, Map<String, String>> getDictMap(FactorQuery query) {
        Map<String, Map<String, String>> dictMap = new HashMap<>();
        List<String> typeCodeList = query.getShowList().stream()
                .map(FactorShowVo::getDicTypeCode)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        List<String> levelCodeList = query.getShowList().stream()
                .map(FactorShowVo::getDicLevelCode)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        List<AppDicts> appDictsList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(typeCodeList) && CollectionUtils.isNotEmpty(levelCodeList)) {
            appDictsList = appDictsMapper.getAppDictsByTypeCodeList(typeCodeList, levelCodeList);
            dictMap = DictUtil.getDictMap(appDictsList, query.getShowList());
        }
        return dictMap;
    }

    private String generateVerificationCode(int length) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            int digit = random.nextInt(9) + 1; // 生成1到9之间的随机数字
            sb.append(digit);
        }

        return sb.toString();
    }

    private FactorFieldVo getFactorTag(AppTag appTag, Integer factorIsStat, Integer factorIsShow) {
        FactorFieldVo factorFieldVo = new FactorFieldVo();
        factorFieldVo.setType("2");
        factorFieldVo.setFieldName(appTag.getTagCol());
        if (StringUtils.isEmpty(appTag.getTagFieldType())) {
            factorFieldVo.setFieldType("varchar");
        } else {
            factorFieldVo.setFieldType(appTag.getTagFieldType());
        }
        factorFieldVo.setTitle(appTag.getTagName());
        factorFieldVo.setDicTable(appTag.getTagDictTable());
        factorFieldVo.setDicTypeCode(appTag.getTagDictTypeCode());
        factorFieldVo.setDicLevelCode(appTag.getTagDictLevelCode());
        factorFieldVo.setLayerFactorIsStat(factorIsStat);
        factorFieldVo.setLayerFactorShow(factorIsShow);
        factorFieldVo.setTagCutMulti(appTag.getTagCutMulti());
        factorFieldVo.setIsPullDown("1");
        return factorFieldVo;
    }


    private FactorFieldVo getFactorFieldVo(AnalysisLayerMetafield metafield, Integer layerFactorIsStat, Integer layerFactorIsShow) {
        FactorFieldVo factorFieldVo = new FactorFieldVo();
        factorFieldVo.setFieldName(metafield.getLayerMetafieldName());
        factorFieldVo.setType("1");
        factorFieldVo.setFieldType(metafield.getLayerMetafieldType());
        factorFieldVo.setTitle(metafield.getLayerMetafieldTitle());
        factorFieldVo.setDicTable(metafield.getLayerDictTable());
        factorFieldVo.setDicTypeCode(metafield.getLayerDictTypeCode());
        factorFieldVo.setDicLevelCode(metafield.getLayerDictLevelCode());
        factorFieldVo.setLayerFactorIsStat(layerFactorIsStat);
        factorFieldVo.setLayerFactorShow(layerFactorIsShow);
        factorFieldVo.setLayerFactorOrder(metafield.getLayerFactorOrder());
        factorFieldVo.setLayerMetafiledOuterfield(metafield.getLayerMetafiledOuterfield());
        factorFieldVo.setLayerMetafiledOutertable(metafield.getLayerMetafiledOutertable());
        factorFieldVo.setLayerMetafiledOuterfieldCondition(metafield.getLayerMetafiledOuterfieldCondition());
        factorFieldVo.setEncryptionType(metafield.getEncryptionType());
        if (StringUtils.isNotEmpty(metafield.getLayerDictTable()) && StringUtils.isNotEmpty(metafield.getLayerDictTable()) && StringUtils.isNotEmpty(metafield.getLayerDictTable())) {
            factorFieldVo.setIsPullDown("1");
        } else if (StringUtils.isNotBlank(metafield.getLayerMetafiledOutertable())) {
            factorFieldVo.setIsPullDown("3");
        } else {
            factorFieldVo.setIsPullDown("0");
        }
        return factorFieldVo;
    }

    private FactorFieldVo getFactorRegionFieldVo() {
        FactorFieldVo factorFieldVo = new FactorFieldVo();
        factorFieldVo.setFieldName("区域范围");
        factorFieldVo.setType("1");
        factorFieldVo.setFieldType("region");
        factorFieldVo.setTitle("区域范围");
        factorFieldVo.setLayerFactorIsStat(1);
        factorFieldVo.setLayerFactorShow(1);
        factorFieldVo.setIsPullDown("0");
        return factorFieldVo;
    }

    private List<String> getGridCodes(FactorFilterVo regionFilter) {
        List<String> gridCodes = new ArrayList<>();
        String gridLevel = regionFilter.getCalValue();
        List<String> codes = regionFilter.getCalValueList();
        if (Objects.nonNull(gridLevel) && CollectionUtils.isNotEmpty(codes)) {
            if (Objects.equals("8", gridLevel)) {// 网格级
                gridCodes.addAll(codes);
            } else if (Objects.equals("7", gridLevel)) { //社区级别
                QueryWrapper<GridInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("parent_code", codes);
                queryWrapper.select("grid_code");
                List<GridInfo> gridInfoList = gridInfoMapper.selectList(queryWrapper);
                if (CollectionUtils.isNotEmpty(gridInfoList)) {
                    gridCodes = gridInfoList.stream()
                            .map(GridInfo::getGridCode)
                            .distinct()
                            .collect(Collectors.toList());
                }
            } else if (Objects.equals("6", gridLevel)) { // 街道级别
                gridCodes = gridInfoMapper.getGridCodeByJdCodeList(codes);
            } else if (Objects.equals("5", gridLevel)) {
                gridCodes = new ArrayList<>();
                gridCodes.add("南山区");
            }
        }
        return gridCodes;
    }

    private String getCase(String str) {
        return str.replaceAll("_", "").toLowerCase(Locale.ROOT);
    }


}

55555

-- public.bz_legal_collect_latest_tagview source

CREATE OR REPLACE VIEW public.bz_legal_collect_latest_tagview

AS SELECT t1.legalcollect_latest_id,

t1.collect_h5_id,

t1.legal_code,

t1.company_name,

t1.legal_extern_name,

t1.license_type,

t1.license_code,

t1.firm_mobile,

t1.legal_adr,

t1.set_up_date,

t1.approval_date,

t1.legal_representative,

t1.legal_certificate_type,

t1.cardno,

t1.cardno_enc,

t1.corporate_address,

t1.legal_mobile,

t1.enterprise_status,

t1.business_format,

t1.business_premises_photo,

t1.business_scope,

t1.physical_business_address,

t1.unit_business_area,

t1.annual_inspection,

t1.bd_address,

t1.bd_code,

t1.occupied_floors,

t1.house_code,

t1.lat,

t1.lng,

t1.qu_code,

t1.district,

t1.jd_code,

t1.street,

t1.sq_code,

t1.community,

t1.grid_code,

t1.grid,

t1.opt_type,

t1.opt_time,

t1.update_userid,

t1.update_username,

t1.update_deptid,

t1.update_deptname,

t1.update_user_identification,

t1.update_time,

t1.create_userid,

t1.create_user_name,

t1.create_deptid,

t1.create_deptname,

t1.create_user_identification,

t1.create_time,

t1.data_source,

t1.sys_time,

t1.sys_userid,

t1.remark,

t1.deleted,

t1.inc_day,

t1.hot_id,

t1.hot_x,

t1.hot_y,

t1.enterprisetype,

t1.contacts,

t1.contactnumber,

t1.house_name,

t1.house_lc,

t1.jylx,

t1.zc_jd_code,

t1.zc_street,

t1.zc_sq_code,

t1.zc_community,

t1.zc_isns,

t1.zc_grid_code,

t1.zc_grid,

t1.zc_bd_address,

t1.zc_bd_code,

t1.zc_occupied_floors,

t1.zc_house_code,

t1.zc_house_name,

t1.zc_house_lc,

t1.sid,

t1.enterpriseno,

t1.organcode,

t1.creditcode,

t1.operatortype,

t1.operatorplacearea,

t1.pdabusnissallotedtime,

t1.pdatradetype,

t1.pdatradenature,

t1.pdaeconomictype,

t1.pdaenterprisetype,

t1.pdaregisteredcapital,

t1.operatorname,

t1.operatorcardnotype,

t1.operatorcardno,

t1.operatoraddress,

t1.operatortelphone,

t1.opt_userid,

t1.opt_user_name,

t1.opt_deptid,

t1.opt_deptname,

t1.opt_grider_id,

t1.logout_userid,

t1.logout_username,

t1.logout_deptid,

t1.logout_deptname,

t1.logout_remark,

t1.logout_time,

t1.operatorsite,

t1.building_cnt,

t1.buz_address,

t1.firm_mobile_enc,

t1.legal_mobile_enc,

t1.contactnumber_enc,

t1.operatorcardno_enc,

t1.operatortelphone_enc,

t2.legaltag_id,

t2.legaltag_owner_id,

t2.tag_field_1,

t2.tag_field_2,

t2.tag_field_3,

t2.tag_field_4,

t2.tag_field_5,

t2.tag_field_6,

t2.tag_field_7,

t2.tag_field_8,

t2.tag_field_9,

t2.tag_field_10,

t2.tag_field_11,

t2.tag_field_12,

t2.tag_field_13,

t2.tag_field_14,

t2.tag_field_15,

t2.tag_field_16,

t2.tag_field_17,

t2.tag_field_18,

t2.tag_field_19,

t2.tag_field_20,

t2.tag_field_21,

t2.tag_field_22,

t2.tag_field_25,

t2.tag_field_26,

t2.tag_field_27,

t2.tag_field_28,

t2.tag_field_29,

t2.tag_field_30,

( SELECT string_agg(tag.tag_name::text || ''::text, ','::text) AS string_agg

FROM legal_collect_tag tag

WHERE tag.rel_code::text = t1.legal_code::text) AS tag_name

FROM bz_legal_collect_latest t1

LEFT JOIN app_legal_tag t2 ON t1.legal_code::text = t2.legaltag_owner_id::text AND t2.inc_day::text = ((( SELECT app_table_inc_day.inc_day

FROM app_table_inc_day

WHERE app_table_inc_day.table_name::text = 'app_legal_tag'::text))::text)

WHERE t1.inc_day::text = ((( SELECT app_table_inc_day.inc_day

FROM app_table_inc_day

WHERE app_table_inc_day.table_name::text = 'bz_legal_collect_latest'::text))::text);

-- public.bz_person_collect_latest_tagview source

CREATE OR REPLACE VIEW public.bz_person_collect_latest_tagview

AS SELECT t1.personcollect_latest_id,

t1.person_code,

t1.name,

t1.enname,

t1.rk_type,

t1.house_code,

t1.firstname,

t1.nationality,

t1.sex,

t1.age,

t1.nationid,

t1.cardtypeid,

t1.cardno,

t1.cardno_enc,

t1.linkphone,

t1.linkphone_enc,

t1.marryid,

t1.politicsid,

t1.living_method,

t1.householder_relation,

t1.householder_name,

t1.householder_cardno,

t1.householder_cardno_enc,

t1.residential_address,

t1.domicile_type,

t1.renter,

t1.commencement_date,

t1.lease_reason,

t1.attribution_police_station,

t1.household_registration_type,

t1.arrival_date,

t1.duration,

t1.tradeid,

t1.company,

t1.companyaddress,

t1.occupation,

t1.is_insured,

t1.sl_payment_type,

t1.insured_enterprises,

t1.data_source,

t1.temporary_leavedate,

t1.temporary_reason,

t1.temp_leave_direction,

t1.return_time,

t1.deregistration,

t1.logout_time,

t1.visit_time,

t1.deleted,

t1.create_time,

t1.update_time,

t1.lng,

t1.lat,

t1.qu_code,

t1.jd_code,

t1.sq_code,

t1.grid_code,

t1.district,

t1.street,

t1.community,

t1.grid,

t1.inc_day,

t1.name_enc,

t1.enname_enc,

t1.building_code,

t1.key_personnel_type,

t1.birthday,

t1.address_compare,

t1.istransact,

t1.transacttime,

t1.leave_date,

t1.checkin_date,

t1.move_destination,

t1.is_leave,

t1.jzzcardno,

t1.jzzcardno_enc,

t1.lease_situation,

t1.off_lease_date,

t1.edulevelid,

t1.isonly,

t1.salary,

t1.singlekid,

t1.cardholders,

t1.techtitleid,

t1.district_new,

t1.rommno,

t1.lastname,

t1.nationalitycode,

t1.renewalnum,

t1.validdate,

t1.marryidtime,

t1.companytel,

t1.height,

t1.bycs,

t1.procreatedynamic,

t1.leave_registered_address,

t1.emerging_industries,

t1.wzrk_schoolstate,

t1.wzrk_schoolname,

t1.remarks,

t1.photopath,

t1.create_userid,

t1.create_deptid,

t1.create_deptname,

t1.create_user_identification,

t1.update_userid,

t1.update_username,

t1.update_deptid,

t1.update_deptname,

t1.update_user_identification,

t1.child_dilemma,

t1.move_areaid,

t1.temp_leave_areaid,

t1.chronic_basic_diseases,

t1.sync_status,

t1.is_czc,

t1.is_repers,

t1.grider_id,

t1.grider_name,

t1.opt_time,

t1.opt_type,

t1.remark,

t1.unitcode,

t1.unit_name,

t1.native_city_code,

t1.native_city_name,

t1.native_province_code,

t1.native_province_name,

t1.register_city_code,

t1.register_city_name,

t1.register_place_type,

t1.register_province_code,

t1.register_province_name,

t1.registera_address,

t1.area_city_code,

t1.area_city_name,

t1.area_province_code,

t1.area_province_name,

t1.area_region_code,

t1.area_region_name,

t1.area_street_code,

t1.area_street_name,

t1.area_community_code,

t1.area_community_name,

t1.photo_base_str,

t1.create_user_name,

t1.hot_id,

t1.hot_x,

t1.hot_y,

t1.sid,

t1.native_region_code,

t1.native_region_name,

t1.task_state,

t1.process_desc,

t1.process_time,

t1.living_status,

t2.personneltag_id,

t2.personneltag_owner_id,

t2.tag_field_1,

t2.tag_field_2,

t2.tag_field_3,

t2.tag_field_4,

t2.tag_field_5,

t2.tag_field_6,

t2.tag_field_7,

t2.tag_field_8,

t2.tag_field_9,

t2.tag_field_10,

t2.tag_field_11,

t2.tag_field_12,

t2.tag_field_13,

t2.tag_field_14,

t2.tag_field_15,

t2.tag_field_16,

t2.tag_field_17,

t2.tag_field_18,

t2.tag_field_19,

t2.tag_field_20,

t2.tag_field_21,

t2.tag_field_22,

t2.tag_field_23,

t2.tag_field_24,

t2.tag_field_25,

t2.tag_field_26,

t2.tag_field_27,

t2.tag_field_28,

t2.tag_field_29,

t2.tag_field_30,

t2.tag_field_31,

t2.tag_field_32,

t2.tag_field_33,

t2.tag_field_34,

t2.tag_field_35,

t2.tag_field_36,

t2.tag_field_37,

t2.tag_field_38,

t2.tag_field_39,

t2.tag_field_40,

t2.tag_field_41,

t2.tag_field_42,

t2.tag_field_43,

t2.tag_field_44,

t2.tag_field_45,

t2.tag_field_46,

t2.tag_field_47,

t2.tag_field_48,

t2.tag_field_49,

t2.tag_field_50,

t2.tag_field_51,

t2.tag_field_52,

t2.tag_field_53,

t2.tag_field_54,

t2.tag_field_55,

t2.tag_field_56,

t2.tag_field_57,

t2.tag_field_58,

t2.tag_field_59,

t2.tag_field_60,

t2.tag_field_61,

t2.tag_field_62,

t2.tag_field_63,

t2.tag_field_64,

t2.tag_field_65,

t2.tag_field_66,

t2.tag_field_67,

t2.tag_field_68,

t2.tag_field_69,

t2.tag_field_70,

t2.tag_field_71,

t2.tag_field_72,

t2.tag_field_73,

t2.tag_field_74,

t2.tag_field_75,

t2.tag_field_76,

t2.tag_field_77,

t2.tag_field_78,

t2.tag_field_79,

t2.tag_field_80,

t2.tag_field_81,

t2.tag_field_82,

t2.tag_field_83,

t2.tag_field_84,

t2.tag_field_85,

t2.tag_field_86,

t2.tag_field_87,

t2.tag_field_88,

t2.tag_field_89,

t2.tag_field_90,

t2.tag_field_91,

t2.tag_field_92,

t2.tag_field_93,

t2.tag_field_94,

t2.tag_field_95,

t2.tag_field_96,

t2.tag_field_97,

t2.tag_field_98,

t2.tag_field_99,

t2.tag_field_100,

st_point(t1.lng::double precision, t1.lat::double precision) AS geom,

EXTRACT(year FROM age(t1.birthday::date::timestamp with time zone)) AS ages,

CASE

WHEN t1.opt_type = 14 AND t1.living_status::text = '3'::text AND t1.opt_time IS NOT NULL AND t1.create_time IS NOT NULL THEN (t1.opt_time::date - t1.create_time::date)::numeric

WHEN t1.opt_type = 9999 AND t1.living_status::text = '3'::text AND t1.logout_time IS NOT NULL AND t1.create_time IS NOT NULL THEN (t1.logout_time::date - t1.create_time::date)::numeric

WHEN t1.living_status::text <> '3'::text AND t1.create_time IS NOT NULL THEN (now()::date - t1.create_time::date)::numeric

ELSE NULL::numeric

END AS live_days,

CASE

WHEN t1.rk_type = 3 THEN t1.enname

ELSE t1.name

END AS pname,

CASE

WHEN t1.opt_type = 14 AND t1.living_status::text = '3'::text THEN t1.opt_time

WHEN t1.opt_type = 9999 AND t1.living_status::text = '3'::text THEN t1.logout_time

ELSE NULL::timestamp without time zone

END AS v_logout_time

FROM bz_person_collect_latest t1

LEFT JOIN app_personnel_tag t2 ON t1.person_code::text = t2.personneltag_owner_id::text AND t2.inc_day::text = ((( SELECT app_table_inc_day.inc_day

FROM app_table_inc_day

WHERE app_table_inc_day.table_name::text = 'app_personnel_tag'::text))::text)

WHERE t1.inc_day::text = ((( SELECT app_table_inc_day.inc_day

FROM app_table_inc_day

WHERE app_table_inc_day.table_name::text = 'bz_person_collect_latest'::text))::text);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值