package com.artfess.cqxy.ledger.manager.impl;


import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.cqxy.ledger.dao.MenuFieldTempDao;
import com.artfess.cqxy.ledger.manager.MenuCustomizeFieldManager;
import com.artfess.cqxy.ledger.manager.MenuFieldTempManager;
import com.artfess.cqxy.ledger.model.MenuCustomizeField;
import com.artfess.cqxy.ledger.model.MenuFieldTemp;
import com.artfess.cqxy.ledger.vo.MenuCustomizeParamVo;
import com.artfess.cqxy.ledger.vo.MenuCustomizeVo;
import com.artfess.cqxy.utils.BizUtils;
import com.artfess.poi.util.ExcelUtil;
import com.artfess.sysConfig.persistence.manager.SysDictionaryManager;
import com.artfess.sysConfig.persistence.param.DictModel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
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.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;


/**
 * @author baseli
 * @date 2022年6月5日20:15:27
 */
@Service
public class MenuFieldTempManagerImpl extends BaseManagerImpl<MenuFieldTempDao, MenuFieldTemp> implements MenuFieldTempManager {

    @Resource
    private MenuCustomizeFieldManager menuCustomizeFieldManager;

    @Autowired
    private SysDictionaryManager sdm;

    @Override
    @Transactional(readOnly = true)
    public MenuCustomizeVo getDataById(MenuCustomizeParamVo menuCustomizeParamVo) {
        // 模板ID
        String id = menuCustomizeParamVo.getId();
        String queryProjectId = menuCustomizeParamVo.getProjectId();
        String projectType = menuCustomizeParamVo.getProjectType();
        String startMoney = menuCustomizeParamVo.getStartMoney();
        String endMoney = menuCustomizeParamVo.getEndMoney();
        String startTime = menuCustomizeParamVo.getStartTime();
        String endTime = menuCustomizeParamVo.getEndTime();
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("queryProjectId", StringUtils.isBlank(queryProjectId)?null:"'"+queryProjectId+"'");
        paramMap.put("projectType", StringUtils.isBlank(projectType)?null:"'"+projectType+"'");
        paramMap.put("startMoney", StringUtils.isBlank(startMoney)?null:"'"+startMoney+"'");
        paramMap.put("endMoney", StringUtils.isBlank(endMoney)?null:"'"+endMoney+"'");
        paramMap.put("startTime", StringUtils.isBlank(startTime)?null:"'"+startTime+"'");
        paramMap.put("endTime", StringUtils.isBlank(endTime)?null:"'"+endTime+"'");

        MenuCustomizeVo menuCustomizeVo = new MenuCustomizeVo();
        List<Object[]> dataList = new ArrayList<>();
        List<String> header = new ArrayList<>();
        // 1.查询模板，及配置信息
        MenuFieldTemp menuFieldTemp = baseMapper.selectById(id);
        QueryWrapper<MenuCustomizeField> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("TEMP_ID_", id);
//        queryWrapper.orderByAsc("MENU_ALIAS_");
        queryWrapper.orderByAsc("SN_");
        List<MenuCustomizeField> menuCustomizeFieldList = menuCustomizeFieldManager.list(queryWrapper);
        menuFieldTemp.setMenuCustomizeFieldList(menuCustomizeFieldList);
        // 2.根据配置的字段、表名查询数据，
        header.add("序号");
        // 字段索引从第一列开始，第0列为序号，跳过
        int fieldIndex = 1;
        // 序号
        int num = 1;
        if (null != menuCustomizeFieldList && menuCustomizeFieldList.size() > 0) {
            int columnSize = menuCustomizeFieldList.size() + 1;
            for (MenuCustomizeField menuCustomizeField : menuCustomizeFieldList) {
//                String head = menuCustomizeField.getTableName() + "-" + menuCustomizeField.getFieldName();
                String head = menuCustomizeField.getFieldName();
                header.add(head);
                String field = menuCustomizeField.getField();
                String table = menuCustomizeField.getTable();
                String isDele = null;
                String projectManagement = null;
                String projectId = null;
                isDele = haveColumn(table, "IS_DELE_") ? "0" : null;
                if("BIZ_PROJECT_MANAGEMENT".equalsIgnoreCase(table)){
//                    projectManagement = menuCustomizeField.getProjectId();
                    projectManagement = StringUtils.isBlank(queryProjectId)?null:"'"+queryProjectId+"'";
                }else {
                    paramMap = null;
//                    projectId = menuCustomizeField.getProjectId();
                    projectId = StringUtils.isBlank(queryProjectId)?null:"'"+queryProjectId+"'";
                }
                List<Object> fieldDataList = baseMapper.getDataById(field, table, isDele, projectManagement, projectId, paramMap);
                String fieldTypeValue = menuCustomizeField.getFieldTypeValue();
                // 如果没有查询到对应的项目，则直接终止字段的查询
                if("BIZ_PROJECT_MANAGEMENT".equalsIgnoreCase(table) && (null == fieldDataList || fieldDataList.size() == 0)){
                    break;
                }
                // 3.组装数据
                //如果字段数据为空，则跳过
                if (null == fieldDataList || fieldDataList.size() == 0) {
                    // 如果没有查询到数据
//                    for (Object[] o :dataList) {
//                    }
                    fieldIndex += 1;
                    continue;
                } else {
                    int dataListSize = dataList.size();
                    if (fieldDataList.size() <= dataListSize) {
                        for (int i = 0, j = fieldDataList.size(); i < j; i++) {
                            Object[] arr = dataList.get(i);
//                            arr[0] = menuCustomizeField.getProjectName();
                            arr[0] = num;
                            num += 1;
                            arr[fieldIndex] = dataFormat(fieldDataList.get(i), fieldTypeValue, menuCustomizeField.getDicKey(), field);
                        }
                    } else {
                        for (int i = 0, j = fieldDataList.size(); i < j; i++) {
                            Object[] arr = null;
                            if (i >= dataList.size()) {
                                arr = new Object[columnSize];
//                                arr[0] = menuCustomizeField.getProjectName();
                                arr[fieldIndex] = dataFormat(fieldDataList.get(i), fieldTypeValue, menuCustomizeField.getDicKey(), field);
                                dataList.add(arr);
                            } else {
                                arr = dataList.get(i);
                                arr[fieldIndex] = dataFormat(fieldDataList.get(i), fieldTypeValue, menuCustomizeField.getDicKey(), field);
                            }
                            arr[0] = num;
                            num += 1;
                        }
                    }
                    fieldIndex += 1;
                }
//                splicingData(data, dataList, menuCustomizeField);
            }
        }
        menuCustomizeVo.setDataList(dataList);
        menuCustomizeVo.setHeader(header);
        return menuCustomizeVo;
    }

    @Override
    @Transactional(readOnly = true)
    public MenuCustomizeVo getDataByIds(MenuCustomizeParamVo menuCustomizeParamVo) {
        // 模板ID
        String id = menuCustomizeParamVo.getId();
        String queryProjectId = menuCustomizeParamVo.getProjectId();
        String projectType = menuCustomizeParamVo.getProjectType();
        String startMoney = menuCustomizeParamVo.getStartMoney();
        String endMoney = menuCustomizeParamVo.getEndMoney();
        String startTime = menuCustomizeParamVo.getStartTime();
        String endTime = menuCustomizeParamVo.getEndTime();
        Map<String, Object> paramMap = new HashMap<>();
        if(StringUtils.isBlank(queryProjectId)){
            paramMap.put("queryProjectId", null);
        }else {
            String[] split = queryProjectId.split(",");
            List queryProjectIdList = new ArrayList(split.length);
            for (String str : split){
                queryProjectIdList.add("'"+str+"'");
            }
            paramMap.put("queryProjectId", queryProjectIdList);
        }
//        paramMap.put("queryProjectId", StringUtils.isBlank(queryProjectId)?null:"'"+queryProjectId+"'");
        paramMap.put("projectType", StringUtils.isBlank(projectType)?null:"'"+projectType+"'");

        paramMap.put("startMoney", StringUtils.isBlank(startMoney)?null:"'"+startMoney+"'");
        paramMap.put("endMoney", StringUtils.isBlank(endMoney)?null:"'"+endMoney+"'");
        paramMap.put("startTime", StringUtils.isBlank(startTime)?null:"'"+startTime+"'");
        paramMap.put("endTime", StringUtils.isBlank(endTime)?null:"'"+endTime+"'");

        MenuCustomizeVo menuCustomizeVo = new MenuCustomizeVo();
        List<Object[]> dataList = new ArrayList<>();
        List<String> header = new ArrayList<>();
        // 1.查询模板，及配置信息
        MenuFieldTemp menuFieldTemp = baseMapper.selectById(id);
        QueryWrapper<MenuCustomizeField> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("TEMP_ID_", id);
//        queryWrapper.orderByAsc("MENU_ALIAS_");
        queryWrapper.orderByAsc("SN_");
        List<MenuCustomizeField> menuCustomizeFieldList = menuCustomizeFieldManager.list(queryWrapper);
        menuFieldTemp.setMenuCustomizeFieldList(menuCustomizeFieldList);
        // 2.根据配置的字段、表名查询数据，
        header.add("序号");
        // 字段集合，格式为table.field
        String filedGroup = "";
        // 表名集合
        HashSet<String> set = new HashSet();
        // 关联表名集合，格式化为FULL JOIN table1 ON
        String tableGroup = "";
        String whereGroup = " WHERE 1=1 ";
        // 字典字段
        LinkedHashMap<Integer , MenuCustomizeField> dicFieldMap = new LinkedHashMap<>();
        if (null != menuCustomizeFieldList && menuCustomizeFieldList.size() > 0) {
            for (int i=0,j=menuCustomizeFieldList.size();i<j;i++) {
                MenuCustomizeField menuCustomizeField = menuCustomizeFieldList.get(i);
//                String head = menuCustomizeField.getTableName() + "-" + menuCustomizeField.getFieldName();
                // 组装列表头部信息
                String head = menuCustomizeField.getFieldName();
                header.add(head);
                // 存储所有表
                String table = menuCustomizeField.getTable();
                if(!"biz_project_management".equalsIgnoreCase(table)){
                    set.add(table);
                }
                // 组装字段
                String field = menuCustomizeField.getField();
                if(i == j-1){
                    filedGroup = filedGroup + table + "." + field;
                }else {
                    filedGroup = filedGroup + table + "." + field + ",";
                }
                // 组装字典字段
                dicFieldMap.put(i, menuCustomizeField);
            }
            // 关联表查询sql
            for(String tableName : set){
                tableGroup = tableGroup + " INNER JOIN " + tableName +" ON biz_project_management.ID_ = "+ tableName+".PROJECT_ID_ ";
                // 组装条件
                if(haveColumn(tableName, "IS_DELE_")){
                    whereGroup = whereGroup + " AND " + tableName + ".IS_DELE_=0 ";
                }
            }
            // 查询数据
            List<LinkedHashMap<String, Object>> fieldDataList = baseMapper.getDataByIds(filedGroup, tableGroup, whereGroup, paramMap);
            // 数据转换为数组
            if(null != fieldDataList && fieldDataList.size() >0){
                for (int i = 0,j = fieldDataList.size(); i < j; i++) {
                    LinkedHashMap<String, Object> stringObjectMap = fieldDataList.get(i);
                    Object[] arr = new Object[stringObjectMap.size()+1];
                    int count = 1;
                    arr[0] = i + 1;
                    for(Map.Entry entry : stringObjectMap.entrySet()){
                        MenuCustomizeField menuCustomizeField = dicFieldMap.get(count - 1);
//                        arr[count] = entry.getValue();

                        if(entry.getKey().equals("CONTRACT_AMOUNT_") && entry.getValue()!=null){
                            String valueStr = String.valueOf(entry.getValue());
                            if(StringUtils.isNotBlank(valueStr)){
                                BigDecimal entryValue = new BigDecimal(valueStr);
                                entry.setValue(String.valueOf(entryValue.divide(new BigDecimal(10000),2,BigDecimal.ROUND_HALF_UP)));
                            }
                        }

                        arr[count] = dataFormat(entry.getValue(), menuCustomizeField.getFieldTypeValue(),
                                menuCustomizeField.getDicKey(), menuCustomizeField.getField());
                        count++;
                    }
                    dataList.add(arr);
                }
            }
        }
        menuCustomizeVo.setDataList(dataList);
        menuCustomizeVo.setHeader(header);
        return menuCustomizeVo;
    }


    @Override
    @Transactional(readOnly = true)
    public MenuCustomizeVo getDataByIdss(MenuCustomizeParamVo menuCustomizeParamVo) {
        // 模板ID
        String id = menuCustomizeParamVo.getId();
        String queryProjectId = menuCustomizeParamVo.getProjectId();
        String projectType = menuCustomizeParamVo.getProjectType();
        String startMoney = menuCustomizeParamVo.getStartMoney();
        String endMoney = menuCustomizeParamVo.getEndMoney();
        String startTime = menuCustomizeParamVo.getStartTime();
        String endTime = menuCustomizeParamVo.getEndTime();
        Map<String, Object> paramMap = new HashMap<>();
        List queryProjectIdList = new ArrayList();
        if(StringUtils.isBlank(queryProjectId)){
            paramMap.put("queryProjectId", null);
        }else {
            String[] split = queryProjectId.split(",");
            for (String str : split){
                queryProjectIdList.add("'"+str+"'");
            }
            paramMap.put("queryProjectId", queryProjectIdList);
        }
//        paramMap.put("queryProjectId", StringUtils.isBlank(queryProjectId)?null:"'"+queryProjectId+"'");
        paramMap.put("projectType", StringUtils.isBlank(projectType)?null:"'"+projectType+"'");

        paramMap.put("startMoney", StringUtils.isBlank(startMoney)?null:"'"+startMoney+"'");
        paramMap.put("endMoney", StringUtils.isBlank(endMoney)?null:"'"+endMoney+"'");
        paramMap.put("startTime", StringUtils.isBlank(startTime)?null:"'"+startTime+"'");
        paramMap.put("endTime", StringUtils.isBlank(endTime)?null:"'"+endTime+"'");

        MenuCustomizeVo menuCustomizeVo = new MenuCustomizeVo();
        List<Object[]> dataList = new ArrayList<>();
        List<String> header = new ArrayList<>();
        // 1.查询模板，及配置信息
        MenuFieldTemp menuFieldTemp = baseMapper.selectById(id);
//        String projectId = menuFieldTemp.getProjectId();
//        queryProjectIdList.add("'"+projectId+"'");
        paramMap.put("queryProjectId", queryProjectIdList);
        QueryWrapper<MenuCustomizeField> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("TEMP_ID_", id);
//        queryWrapper.orderByAsc("MENU_ALIAS_");
        queryWrapper.orderByAsc("SN_");
        List<MenuCustomizeField> menuCustomizeFieldList = menuCustomizeFieldManager.list(queryWrapper);
        menuFieldTemp.setMenuCustomizeFieldList(menuCustomizeFieldList);
        // 2.根据配置的字段、表名查询数据，
        header.add("序号");
        // 字段集合，格式为table.field
        String filedGroup = "";
        // 表名集合(根据数据量排序后的集合)
        List<String> set = new ArrayList<>();
        // 关联表名集合，格式化为FULL JOIN table1 ON
        String tableGroup = "";
        // where条件集合
        String whereGroup = " WHERE 1=1 ";
        Map<String, Boolean> haveSubTableMap = new HashMap<>();
        // 字典字段
        LinkedHashMap<Integer , MenuCustomizeField> dicFieldMap = new LinkedHashMap<>();
        if (null != menuCustomizeFieldList && menuCustomizeFieldList.size() > 0) {
            ArrayList<Map<String, Object>> tableList = new ArrayList();
            boolean haveProjectTable = false;
            for (int i=0,j=menuCustomizeFieldList.size();i<j;i++) {
                MenuCustomizeField menuCustomizeField = menuCustomizeFieldList.get(i);
//                String head = menuCustomizeField.getTableName() + "-" + menuCustomizeField.getFieldName();
                // 字段中文名称
                String head = menuCustomizeField.getFieldName();
                // 计算方式
                Integer calculationMethod = menuCustomizeField.getCalculationMethod();
                // 表名
                String tableName = menuCustomizeField.getTable();
                // 字段名称
                String fieldName = menuCustomizeField.getField();
                // 功能Project_id
                String project_id_ = null;
                // 项目ID_
                String id_ = null;
                // 1.组装列表头部信息---------------------------
                header.add(head);
                // 先组装where条件，因为求和时会先使用条件
                String whereSql = " WHERE 1=1 ";
                // 判断表中是否有IS_DELE字段，返回true及时有
                Boolean haveDel =  haveColumn(tableName, "IS_DELE_");
                boolean haveSubTable = false;
                boolean haveProjectParam = null != queryProjectIdList && queryProjectIdList.size() > 0;
                if(haveProjectParam){
                    if("BIZ_PROJECT_MANAGEMENT".equalsIgnoreCase(tableName)){
                        whereSql = whereSql + " AND ID_ IN( " + String.join(",", queryProjectIdList) +")";
                    }else {
                        whereSql = whereSql + " AND PROJECT_ID_ IN( " + String.join(",", queryProjectIdList) +")";
                    }
                }
                if(haveDel){
                    whereSql = whereSql + " AND " + tableName + ".IS_DELE_=0";
                }
                // 2.组装表名---------------------------------
                if(null != calculationMethod && calculationMethod == 2){
                    String subTableAlias =  tableName + "_" + fieldName;
                    String subTableName = "";
                    if("BIZ_PROJECT_MANAGEMENT".equalsIgnoreCase(tableName)){
                        subTableName = " (SELECT SUM(" + fieldName + ") total,ID_ FROM "+ tableName + whereSql + " group by ID_) " + subTableAlias;
                    }else{
                        String fiaryFieldName = fieldName;
                        //如果表名是合同表，字段名是合同金额，将金额单位换算成万元
                        if("BIZ_CONTRACT".equalsIgnoreCase(tableName) && "CONTRACT_AMOUNT_".equalsIgnoreCase(fieldName)){
                            fiaryFieldName = fieldName + "/10000";
                        }

                        subTableName = " (SELECT SUM(" + fiaryFieldName + ") total,PROJECT_ID_ FROM "+ tableName + whereSql + " group by PROJECT_ID_) " + subTableAlias;
                    }
                    tableName = subTableName + "#" + subTableAlias;
//                    fieldName = subFieldName;
                    haveSubTable = true;
                    haveSubTableMap.put(subTableName, haveSubTable);
                }else {
                    haveSubTableMap.put(tableName, haveSubTable);
                }
                  // 将表名放入集合，以便去重和排序
                Map<String, Object> tableNumMap = new HashMap();
                // 查询表中数据数量，以数量来区分表先后顺序
                int num = baseMapper.countNum(tableName, haveSubTable?null:(haveDel?"0":null), haveSubTable? null : project_id_, haveSubTable? null : id_);
                tableNumMap.put("tableName", tableName);
                tableNumMap.put("num", num);
                tableList.add(tableNumMap);
                // 3.组装字段---------------------------
                if(i == j-1){
                    // 计算方式为求和时查询total
                    if(null != calculationMethod && calculationMethod == 2){
                        String[] tableAndAlias = tableName.split("#");
                        filedGroup = filedGroup + tableAndAlias[1] + ".total";
                    }else{
                        filedGroup = filedGroup + tableName + "." + fieldName;
                    }
                }else {
                    // 计算方式为求和时查询total
                    if(null != calculationMethod && calculationMethod == 2){
                        String[] tableAndAlias = tableName.split("#");
                        filedGroup = filedGroup + tableAndAlias[1] + ".total"+ ",";
                    }else{
                        filedGroup = filedGroup + tableName + "." + fieldName + ",";
                    }
                }
                // 组装字典字段
                dicFieldMap.put(i, menuCustomizeField);
            }
            //将合同金额单位换成万元
//            header.remove(6);
//            header.add(6,"合同金额(万元)");

            // 4.组装sql-------------------
             //去重并按照数据量排序
            BizUtils.removeSame(tableList);
            Collections.sort(tableList, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Integer name1 = Integer.valueOf(o1.get("num").toString()) ;//name1是从你list里面拿出来的一个
                    Integer name2 = Integer.valueOf(o2.get("num").toString()) ; //name1是从你list里面拿出来的第二个name
                    return name2.compareTo(name1);
                }
            });
             // 单独存储表名
            for (int i=0,j=tableList.size();i<j;i++){
                Map<String, Object> stringIntegerMap = tableList.get(i);
                set.add(String.valueOf(stringIntegerMap.get("tableName")));
            }
            // 开始关联表查询sql
            int index = 1;
            String firstTable = "";
            for(String tableName : set){
                Boolean haveSubTable = haveSubTableMap.get(tableName);
                String[] tableAndAlias = tableName.split("#");
                String subTableAlias = tableName;
                if(tableAndAlias.length > 1){
                    // tableName 就是子查询集（包括了别名）
                    tableName = tableAndAlias[0];
                    // subTableAlias = 表的别名
                    subTableAlias = tableAndAlias[1];
                }
                Boolean haveSub = null == haveSubTable? false :  haveSubTable;
                String tableFiledSql = subTableAlias+".PROJECT_ID_ ";
                if("BIZ_PROJECT_MANAGEMENT".equalsIgnoreCase(subTableAlias)){
                    tableFiledSql = subTableAlias +".ID_";
                }
                if(index == 1){

                    tableGroup = "select " + filedGroup + " from "+ tableName;

                    if("BIZ_PROJECT_MANAGEMENT".equalsIgnoreCase(subTableAlias)){
                        firstTable = subTableAlias +".ID_";
                        if(!haveSub && null != queryProjectIdList && queryProjectIdList.size() > 0){
                            whereGroup = whereGroup + " AND ID_ IN( " + String.join(",", queryProjectIdList) +")";
                        }
                        haveProjectTable = true;
                    }else {
                        firstTable = subTableAlias+".PROJECT_ID_ ";
                        if(null != haveSubTable && !haveSubTable && null != queryProjectIdList && queryProjectIdList.size() > 0){
//                            whereGroup = whereGroup + " AND PROJECT_ID_ IN( " + String.join(",", queryProjectIdList) +")";
                            whereGroup = whereGroup + " AND "+firstTable+" IN( " + String.join(",", queryProjectIdList) +")";
                        }
                    }
                }else {
                    if("BIZ_PROJECT_MANAGEMENT".equalsIgnoreCase(subTableAlias)){
                        tableGroup = tableGroup + " LEFT JOIN " + tableName + " ON " + tableName + ".ID_ = "+ firstTable ;
                        haveProjectTable = true;
                    }else {
                        tableGroup = tableGroup + " LEFT JOIN " + tableName + " ON " + tableFiledSql + " = "+ firstTable ;
                    }
                }
                // 组装条件
                Boolean isDel = haveColumn(tableName, "IS_DELE_");
                if(null != haveSubTable && !haveSubTable && isDel){
                    whereGroup = whereGroup + " AND (" + tableName + ".IS_DELE_=0 OR ISNULL("+tableName+".IS_DELE_))";
                }
                index++;
            }
            if(!haveProjectTable){
                tableGroup  = tableGroup + " LEFT JOIN biz_project_management ON biz_project_management.ID_ = " + firstTable;
            }
            // 查询数据
            List<LinkedHashMap<String, Object>> fieldDataList = baseMapper.getDataByIdss(tableGroup, whereGroup, paramMap);
            // 数据转换为数组
            if(null != fieldDataList && fieldDataList.size() >0){
                for (int i = 0,j = fieldDataList.size(); i < j; i++) {
                    LinkedHashMap<String, Object> stringObjectMap = fieldDataList.get(i);
                    Object[] arr = new Object[stringObjectMap.size()+1];
                    int count = 1;
                    arr[0] = i + 1;
                    for(Map.Entry entry : stringObjectMap.entrySet()){
                        MenuCustomizeField menuCustomizeField = dicFieldMap.get(count - 1);
//                        arr[count] = entry.getValue();

                        //将合同金额转换为万元
//                        if(entry.getKey().equals("total") && entry.getValue()!=null){
//                            String valueStr = String.valueOf(entry.getValue());
//                            if(StringUtils.isNotBlank(valueStr)){
//                                BigDecimal entryValue = new BigDecimal(valueStr);
//                                entry.setValue(String.valueOf(entryValue.divide(new BigDecimal(10000),2,BigDecimal.ROUND_HALF_UP)));
//                            }
//                        }

                        arr[count] = dataFormat(entry.getValue(), menuCustomizeField.getFieldTypeValue(),
                                menuCustomizeField.getDicKey(), menuCustomizeField.getField());
                        count++;
                    }
                    dataList.add(arr);
                }
            }
        }
        menuCustomizeVo.setDataList(dataList);
        menuCustomizeVo.setHeader(header);
        return menuCustomizeVo;
    }

    @Override
    public void exportDataToExcel(MenuCustomizeParamVo menuCustomizeParamVo, HttpServletResponse response) throws IOException {
        String fileName = "自定义台账导出结果";

        MenuCustomizeVo vo = getDataByIdss(menuCustomizeParamVo);
        List<String> headers = vo.getHeader();
        List<Object[]> data = vo.getDataList();
        HSSFWorkbook wookbook = new HSSFWorkbook();
        HSSFSheet sheet = wookbook.createSheet(fileName);
        HSSFCellStyle style = wookbook.createCellStyle();
        //设置字体
        HSSFFont font = wookbook.createFont();
        //设置字体名称
        font.setFontName("宋体");
        style.setFont(font);

        AtomicInteger headCounter = new AtomicInteger();
        HSSFRow head = sheet.createRow(0);
        headers.forEach(h->{
            BizUtils.handelCell(wookbook, style, fileName, head.createCell(headCounter.get()), h, true);
            headCounter.getAndIncrement();
        });

        AtomicInteger dataCounter = new AtomicInteger(1);
        data.forEach(d->{
            HSSFRow dataRow = sheet.createRow(dataCounter.get());

            AtomicInteger valueCounter = new AtomicInteger();
            for (Object value : d) {
                //解决科学计数法
                Pattern pattern = Pattern.compile("(-?\\d+\\.?\\d*)[Ee]{1}[\\+-]?[0-9]*");
                if(value!=null) {
                    if (pattern.matcher(String.valueOf(value)).matches()) {
                        DecimalFormat df = new DecimalFormat("0.00");
                        value = df.format(Double.parseDouble(String.valueOf(value))).trim();
                    }
                }
                //

                BizUtils.handelCell(wookbook, style, fileName, dataRow.createCell(valueCounter.get()), null == value ? "" : value.toString());
                valueCounter.getAndIncrement();
            }
            dataCounter.getAndIncrement();
        });

        sheet.setColumnWidth(0,1800);
        //设置除序号以外的每列列宽
        for(int i = 1; i < headers.size();i++){
            sheet.setColumnWidth(i,4800);
        }

        ExcelUtil.downloadExcel(wookbook, fileName, response);
    }

    public Object dataFormat(Object o, String type, String dicKey, String field) {
        if(null == o){
            return "";
        }
        //1：字符串，2：整数，3：浮点数，4:大数据，5：日期（年月日），6：日期时间（年月日时分秒），7：时间戳，8：枚举，9：日期（年月）
        SimpleDateFormat sdy = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfsfm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        if ("1".equals(type)) {

        }
        if ("2".equals(type)) {

        }
        if ("3".equals(type) || o instanceof Double) {
            DecimalFormat df = new DecimalFormat("0.00");
            return df.format(Double.parseDouble(String.valueOf(o))).trim();
        }
        if ("4".equals(type)) {
            if (o instanceof BigDecimal) {
                return ((BigDecimal) o).stripTrailingZeros().toPlainString();
            }
        }
        if ("5".equals(type)) {
            if (o instanceof Date) {
                return sdf.format(((Date) o));
            }
            if (o instanceof LocalDate) {
                return o;
            }
        }
        if ("6".equals(type)) {
            if (o instanceof Date) {
                return sdfsfm.format(((Date) o));
            }
            if (o instanceof LocalDateTime) {
                return o;
            }
            if (o instanceof LocalDate) {
                LocalDate d = (LocalDate)o;
                return d.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00:00:00";
            }
        }
        if ("9".equals(type)) {
            if (o instanceof Date) {
                return sdy.format(((Date) o));
            }
            if (o instanceof LocalDate) {
                LocalDate d = (LocalDate)o;
                return d.format(DateTimeFormatter.ofPattern("yyyy-MM"));
            }
        }
        if ("7".equals(type)) {

        }
        if ("8".equals(type)) {
            // 获取字典
            if(ObjectUtils.isNotEmpty(o) && StringUtils.isNotBlank(dicKey)){
                List<DictModel> decisionType = sdm.queryDictListItemsByCode(dicKey);
                if("DECISION_BASIS_TYPE_".equalsIgnoreCase(field)){
                    String[] str = String.valueOf(o).split(",");
                    List val = new ArrayList(str.length);
                    for(String s : str){
                        val.add(BizUtils.getDicValueByCode(decisionType, String.valueOf(s)));
                    }
                    return String.join(",", val);
                }
                return  BizUtils.getDicValueByCode(decisionType, String.valueOf(o));
            }
        }
        return o;
    }

    /**
     * 将不同条数的数据拼装为相同结果的数据集
     *
     * @param result   最终结果
     * @param dataList 数据集
     */
    public void splicingData(List<Map<String, Object>> result, List<Map<String, Object>> dataList, MenuCustomizeField menuCustomizeField) {
        // 拼装数据
        // 表头

        //数据
    }

    /**
     * 根据表名获取列
     *
     * @param tableNmae
     * @return
     */
    @Override
    public List<String> getColumnByTable(String tableNmae) {
        return baseMapper.getColumnByTable(tableNmae);
    }

    /**
     * 判断列名是否存在
     *
     * @param tableNmae
     * @param column
     * @return boolean, false:不存在，true：存在
     */
    @Override
    public boolean haveColumn(String tableNmae, String column) {
        if (StringUtils.isBlank(tableNmae) || StringUtils.isBlank(column)) {
            return false;
        }
        List<String> columnByTable = getColumnByTable(tableNmae);
        if (null != columnByTable && columnByTable.size() > 0) {
            return columnByTable.contains(column.toUpperCase());
        }
        return false;
    }

}
