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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.hygf.api.Enum.CommonEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.BusinessFieldDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.StationFieldDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.HygfBusinessField;
import com.yeejoin.amos.boot.module.hygf.api.mapper.BusinessFieldMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IBusinessFieldService;
import com.yeejoin.amos.boot.module.hygf.api.util.ListUtils;
import com.yeejoin.amos.boot.module.hygf.biz.excel.Enum.BusinessTypeEnum;
import com.yeejoin.amos.boot.module.hygf.biz.excel.Enum.ExportPageEnum;
import com.yeejoin.amos.boot.module.hygf.biz.excel.factory.ExportPageFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BusinessFieldServiceImpl extends BaseService<BusinessFieldDto, HygfBusinessField, BusinessFieldMapper> implements IBusinessFieldService {

    @Autowired
    private ExportPageFactory exportPageFactory;
    @Autowired
    private BusinessFieldMapper businessFieldMapper;

    public Map<String, List<HygfBusinessField>> getAllField() {
        Map<String, List<HygfBusinessField>> map = new HashMap<>();
        List<HygfBusinessField> list = list();
        if (CollectionUtil.isNotEmpty(list)) {
            map = list.stream().collect(Collectors.groupingBy(HygfBusinessField::getBusinessType));
        }
        return map;
    }

    public void exportStationExcelByField(StationFieldDto stationFieldDto, HttpServletResponse response) {
        dealInitData(stationFieldDto);
        List<String> fields = getHeaderFields(stationFieldDto);
        List<String> fieldsFlag = getFieldsFlag(stationFieldDto);
        List<Map<String, Object>> data = getExcelData(stationFieldDto);
        exportFieldExcel(fields, fieldsFlag, data, response);
    }

    /**
     * 获取字段标识
     * @param stationFieldDto
     * @return
     */
    private List<String> getFieldsFlag(StationFieldDto stationFieldDto) {
        List<String> fieldsFlag = new ArrayList<>();
        List<HygfBusinessField> businessFieldList = stationFieldDto.getBusinessFieldList();
        for (HygfBusinessField businessField : businessFieldList) {
            fieldsFlag.add(businessField.getFieldName() + "_" + businessField.getBusinessName());
        }
        return fieldsFlag;
    }

    /**
     * 导出动态字段Excel
     * @param fields
     * @param fieldsFlag
     * @param data
     * @param response
     */
    private void exportFieldExcel(List<String> fields, List<String> fieldsFlag, List<Map<String, Object>> data, HttpServletResponse response) {
        // 创建工作簿和工作表
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("电站统计");
        // 创建表头
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < fields.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(fields.get(i));
        }
        // 设置表头样式
        if (headerRow != null) {
            CellStyle headerStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setBold(true); // 加粗
            headerStyle.setFont(font);
            headerStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex()); // 背景色
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 填充模式
            // 设置居中对齐
            headerStyle.setAlignment(HorizontalAlignment.LEFT);
            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            // 设置表头每个单元格的样式
            for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell != null) {
                    cell.setCellStyle(headerStyle);
                }
            }
        }
        // 调整列宽
        for (int colNum = 0; colNum < sheet.getRow(0).getPhysicalNumberOfCells(); colNum++) {
            sheet.setColumnWidth(colNum, 25 * 256);
        }
        // 填充数据
        for (int i = 0; i < data.size(); i++) {
            Row row = sheet.createRow(i + 1);
            for (int j = 0; j < fieldsFlag.size(); j++) {
                Object value = data.get(i).get(fieldsFlag.get(j));
                if (Objects.nonNull(value) && value.toString().length() >= 32767) {
                    value = value.toString().substring(0, 32766);
                }
                row.createCell(j).setCellValue(value != null ? value.toString() : "");
            }
        }
        try {
            String fileName = "电站详情信息导出" + DateUtils.dateFormat(new Date(), "YYYY-MM-dd-HH-mm") + ".xlsx";
            downLoadExcel(fileName, response, workbook);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BadRequest("导出excel失败");
        }
    }

    /**
     * 处理初始数据
     * @param stationFieldDto
     */
    private void dealInitData(StationFieldDto stationFieldDto) {
        if (CollectionUtil.isEmpty(stationFieldDto.getStationIdList())) {
            stationFieldDto.setStationIdList(exportPageFactory.getExportPage(ExportPageEnum.getEnumByCode(stationFieldDto.getExportPageCode())).getStationId(stationFieldDto.getFilters()));
        }
        if (CollectionUtil.isEmpty(stationFieldDto.getBusinessIdList())) {
            stationFieldDto.setBusinessFieldList(list());
        } else {
            stationFieldDto.setBusinessFieldList(this.baseMapper.selectBatchIds(stationFieldDto.getBusinessIdList()));
        }
    }

    private void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        workbook.write(response.getOutputStream());
    }

    /**
     * 获取excel第一行数据
     * @param stationFieldDto
     * @return
     */
    private List<String> getHeaderFields(StationFieldDto stationFieldDto) {
        List<String> headerFields = new ArrayList<>();
        List<HygfBusinessField> businessFieldList = stationFieldDto.getBusinessFieldList();
        for (HygfBusinessField businessField : businessFieldList) {
            headerFields.add(businessField.getFieldName());
        }
        return headerFields;
    }

    /**
     * 获取Excel数据
     * @param stationFieldDto
     * @return
     */
    private List<Map<String, Object>> getExcelData(StationFieldDto stationFieldDto) {
        List<Map<String, Object>> data = new ArrayList<>();
        Map<String, List<HygfBusinessField>> businessTypeMap = stationFieldDto.getBusinessFieldList().stream().collect(Collectors.groupingBy(HygfBusinessField::getBusinessName));
        List<String> stationIdList = stationFieldDto.getStationIdList();
        if (CollectionUtil.isEmpty(stationIdList)) {
            return data;
        }
        List<Long> sequenceNbrListLong = stationIdList.stream()
                .map(Long::valueOf)  // 将字符串转换为Long
                .collect(Collectors.toList());
        Map<String, Map<String, Object>> basicInformation = new HashMap<>();
        Map<String, Map<String, Object>> surveyInformation = new HashMap<>();
        Map<String, Map<String, Object>> designInformation = new HashMap<>();
        Map<String, Map<String, Object>> businessInformation = new HashMap<>();
        Map<String, Map<String, Object>> extendedInformation = new HashMap<>();
        Map<String, Map<String, Object>> archivingInformation = new HashMap<>();
        Map<String, Map<String, Object>> engineeringInformation = new HashMap<>();
        Map<String, Map<String, Object>> gridInformation = new HashMap<>();
        Map<String, Map<String, Object>> dispatchOrderInformation = new HashMap<>();
        if (sequenceNbrListLong.size() < 1000) {
            basicInformation = getBasicInformation(sequenceNbrListLong, businessTypeMap.get(BusinessTypeEnum.BASIC_INFORMATION.getName()));
            surveyInformation = getSurveyInformation(sequenceNbrListLong, businessTypeMap.get(BusinessTypeEnum.SURVEY_INFORMATION.getName()));
            designInformation = getDesignInformation(sequenceNbrListLong, businessTypeMap.get(BusinessTypeEnum.DESIGN_INFORMATION.getName()));
            businessInformation = getBusinessInformation(sequenceNbrListLong, businessTypeMap.get(BusinessTypeEnum.BUSINESS_INFORMATION.getName()));
            extendedInformation = getExtendedInformation(sequenceNbrListLong, businessTypeMap.get(BusinessTypeEnum.EXTENDED_INFORMATION.getName()));
            archivingInformation = getArchivingInformation(sequenceNbrListLong, businessTypeMap.get(BusinessTypeEnum.ARCHIVING_INFORMATION.getName()));
            engineeringInformation = getEngineeringInformation(sequenceNbrListLong, businessTypeMap.get(BusinessTypeEnum.ENGINEERING_INFORMATION.getName()));
            gridInformation = getGridInformation(sequenceNbrListLong, businessTypeMap.get(BusinessTypeEnum.GRID_INFORMATION.getName()));
            dispatchOrderInformation = getDispatchOrderInformation(sequenceNbrListLong, businessTypeMap.get(BusinessTypeEnum.DISPATCH_ORDER_INFORMATION.getName()));
        } else {
            List<List<Long>> lists = ListUtils.splitList(sequenceNbrListLong, 1000);
            for (List<Long> list : lists) {
                basicInformation.putAll(getBasicInformation(list, businessTypeMap.get(BusinessTypeEnum.BASIC_INFORMATION.getName())));
                surveyInformation.putAll(getSurveyInformation(list, businessTypeMap.get(BusinessTypeEnum.SURVEY_INFORMATION.getName())));
                designInformation.putAll(getDesignInformation(list, businessTypeMap.get(BusinessTypeEnum.DESIGN_INFORMATION.getName())));
                businessInformation.putAll(getBusinessInformation(list, businessTypeMap.get(BusinessTypeEnum.BUSINESS_INFORMATION.getName())));
                extendedInformation.putAll(getExtendedInformation(list, businessTypeMap.get(BusinessTypeEnum.EXTENDED_INFORMATION.getName())));
                archivingInformation.putAll(getArchivingInformation(list, businessTypeMap.get(BusinessTypeEnum.ARCHIVING_INFORMATION.getName())));
                engineeringInformation.putAll(getEngineeringInformation(list, businessTypeMap.get(BusinessTypeEnum.ENGINEERING_INFORMATION.getName())));
                gridInformation.putAll(getGridInformation(list, businessTypeMap.get(BusinessTypeEnum.GRID_INFORMATION.getName())));
                dispatchOrderInformation.putAll(getDispatchOrderInformation(list, businessTypeMap.get(BusinessTypeEnum.DISPATCH_ORDER_INFORMATION.getName())));
            }
        }
        for (String s : stationIdList) {
            Map<String, Object> map = new HashMap<>();
            if (Objects.nonNull(basicInformation.get(s))) {
                map.putAll(basicInformation.get(s));
            }
            if (Objects.nonNull(surveyInformation.get(s))) {
                map.putAll(surveyInformation.get(s));
            }
            if (Objects.nonNull(designInformation.get(s))) {
                map.putAll(designInformation.get(s));
            }
            if (Objects.nonNull(businessInformation.get(s))) {
                map.putAll(businessInformation.get(s));
            }
            if (Objects.nonNull(extendedInformation.get(s))) {
                map.putAll(extendedInformation.get(s));
            }
            if (Objects.nonNull(archivingInformation.get(s))) {
                map.putAll(archivingInformation.get(s));
            }
            if (Objects.nonNull(engineeringInformation.get(s))) {
                map.putAll(engineeringInformation.get(s));
            }
            if (Objects.nonNull(gridInformation.get(s))) {
                map.putAll(gridInformation.get(s));
            }
            if (Objects.nonNull(dispatchOrderInformation.get(s))) {
                map.putAll(dispatchOrderInformation.get(s));
            }
            data.add(map);
        }
        return data;
    }

    /**
     * 获取派工单信息
     * @param stationIdList
     * @param fields
     * @return
     */
    private Map<String, Map<String, Object>> getDispatchOrderInformation(List<Long> stationIdList, List<HygfBusinessField> fields) {
        return dealFields(businessFieldMapper.getDispatchOrderInformation(stationIdList), fields);
    }

    /**
     * 获取并网信息
     * @param stationIdList
     * @param fields
     * @return
     */
    private Map<String, Map<String, Object>> getGridInformation(List<Long> stationIdList, List<HygfBusinessField> fields) {
        return dealFields(businessFieldMapper.getGridInformation(stationIdList), fields);
    }

    /**
     * 获取工程信息
     * @param stationIdList
     * @param fields
     * @return
     */
    private Map<String, Map<String, Object>> getEngineeringInformation(List<Long> stationIdList, List<HygfBusinessField> fields) {
        List<Map<String, Object>> dataMap = businessFieldMapper.getEngineeringInformation(stationIdList);
        if (CollectionUtil.isNotEmpty(dataMap)) {
            for (Map<String, Object> item : dataMap) {
                if (Objects.nonNull(item.get("completion_date"))) {
                    item.put("completion_date", DateUtils.dateStringFormat(item.get("completion_date")));
                }
                //处理组件序列号
                dealConstructionComponentInfo(item);
                //处理逆变器序列号
                dealConstructionInverterInfo(item);
                //处理采集器序列号
                dealConstructionCollectorBoxInfo(item);
                //处理并网箱序列号
                dealConstructionGridBoxInfo(item);
            }
        }
        return dealFields(dataMap, fields);
    }

    private void dealConstructionGridBoxInfo(Map<String, Object> item) {
        if (Objects.nonNull(item.get("construction_grid_box_info"))) {
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("construction_grid_box_info")));
            StringBuilder stringBuilder = new StringBuilder();
            int index = 0;
            for (Object o : jsonArray) {
                if (o instanceof JSONObject) {
                    index++;
                    JSONObject jsonObject = (JSONObject) o;
                    stringBuilder.append("序号:");
                    stringBuilder.append(index);
                    stringBuilder.append("序列号:");
                    stringBuilder.append(jsonObject.get("xlh") == null ? "" : jsonObject.get("xlh"));
                    stringBuilder.append("功率:");
                    stringBuilder.append(jsonObject.get("gl") == null ? "" : jsonObject.get("gl"));
                    stringBuilder.append("物料编码:");
                    stringBuilder.append(jsonObject.get("wlbm") == null ? "" : jsonObject.get("wlbm"));
                    stringBuilder.append("物料名称:");
                    stringBuilder.append(jsonObject.get("wlmc") == null ? "" : jsonObject.get("wlmc"));
                    stringBuilder.append("材质:");
                    stringBuilder.append(jsonObject.get("cz") == null ? "" : jsonObject.get("cz"));
                    stringBuilder.append("类型:");
                    stringBuilder.append(jsonObject.get("lx") == null ? "" : jsonObject.get("lx"));
                    stringBuilder.append("功能:");
                    stringBuilder.append(jsonObject.get("gn") == null ? "" : jsonObject.get("gn"));
                    stringBuilder.append("相位:");
                    stringBuilder.append(jsonObject.get("xw") == null ? "" : jsonObject.get("xw"));
                    stringBuilder.append("\n");
                }
            }
            item.put("construction_grid_box_info", stringBuilder.toString());
        }
    }

    private void dealConstructionCollectorBoxInfo(Map<String, Object> item) {
        if (Objects.nonNull(item.get("construction_collector_box_info"))) {
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("construction_collector_box_info")));
            StringBuilder stringBuilder = new StringBuilder();
            int index = 0;
            for (Object o : jsonArray) {
                if (o instanceof JSONObject) {
                    index++;
                    JSONObject jsonObject = (JSONObject) o;
                    stringBuilder.append("序号:");
                    stringBuilder.append(index);
                    stringBuilder.append("序列号:");
                    stringBuilder.append(jsonObject.get("xlh") == null ? "" : jsonObject.get("xlh"));
                    stringBuilder.append("\n");
                }
            }
            item.put("construction_collector_box_info", stringBuilder.toString());
        }
    }

    private void dealConstructionInverterInfo(Map<String, Object> item) {
        if (Objects.nonNull(item.get("construction_inverter_info"))) {
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("construction_inverter_info")));
            StringBuilder stringBuilder = new StringBuilder();
            int index = 0;
            for (Object o : jsonArray) {
                if (o instanceof JSONObject) {
                    index++;
                    JSONObject jsonObject = (JSONObject) o;
                    stringBuilder.append("序号:");
                    stringBuilder.append(index);
                    stringBuilder.append("序列号:");
                    stringBuilder.append(jsonObject.get("xlh") == null ? "" : jsonObject.get("xlh"));
                    stringBuilder.append("验证码:");
                    stringBuilder.append(jsonObject.get("yzm") == null ? "" : jsonObject.get("yzm"));
                    stringBuilder.append("功率:");
                    stringBuilder.append(jsonObject.get("gl") == null ? "" : jsonObject.get("gl"));
                    stringBuilder.append("物料编码:");
                    stringBuilder.append(jsonObject.get("wlbm") == null ? "" : jsonObject.get("wlbm"));
                    stringBuilder.append("物料名称:");
                    stringBuilder.append(jsonObject.get("wlmc") == null ? "" : jsonObject.get("wlmc"));
                    stringBuilder.append("系列:");
                    stringBuilder.append(jsonObject.get("xl") == null ? "" : jsonObject.get("xl"));
                    stringBuilder.append("相位:");
                    stringBuilder.append(jsonObject.get("xw") == null ? "" : jsonObject.get("xw"));
                    stringBuilder.append("\n");
                }
            }
            item.put("construction_inverter_info", stringBuilder.toString());
        }
    }

    private void dealConstructionComponentInfo(Map<String, Object> item) {
        if (Objects.nonNull(item.get("construction_component_info"))) {
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("construction_component_info")));
            StringBuilder stringBuilder = new StringBuilder();
            int index = 0;
            for (Object o : jsonArray) {
                if (o instanceof JSONObject) {
                    index++;
                    JSONObject jsonObject = (JSONObject) o;
                    stringBuilder.append("序号:");
                    stringBuilder.append(index);
                    stringBuilder.append("序列号:");
                    stringBuilder.append(jsonObject.get("xlh") == null ? "" : jsonObject.get("xlh"));
                    stringBuilder.append("功率:");
                    stringBuilder.append(jsonObject.get("gl") == null ? "" : jsonObject.get("gl"));
                    stringBuilder.append("物料编码:");
                    stringBuilder.append(jsonObject.get("wlbm") == null ? "" : jsonObject.get("wlbm"));
                    stringBuilder.append("物料名称:");
                    stringBuilder.append(jsonObject.get("wlmc") == null ? "" : jsonObject.get("wlmc"));
                    stringBuilder.append("电池片规格:");
                    stringBuilder.append(jsonObject.get("dcpgg") == null ? "" : jsonObject.get("dcpgg"));
                    stringBuilder.append("类型:");
                    stringBuilder.append(jsonObject.get("lx") == null ? "" : jsonObject.get("lx"));
                    stringBuilder.append("边框:");
                    stringBuilder.append(jsonObject.get("bk") == null ? "" : jsonObject.get("bk"));
                    stringBuilder.append("单/双面:");
                    stringBuilder.append(jsonObject.get("dsm") == null ? "" : jsonObject.get("dsm"));
                    stringBuilder.append("\n");
                }
            }
            item.put("construction_component_info", stringBuilder.toString());
        }
    }

    /**
     * 获取资料归档信息
     * @param stationIdList
     * @param fields
     * @return
     */
    private Map<String, Map<String, Object>> getArchivingInformation(List<Long> stationIdList, List<HygfBusinessField> fields) {
        return dealFields(businessFieldMapper.getArchivingInformation(stationIdList), fields);
    }

    /**
     * 获取扩展信息
     * @param stationIdList
     * @param fields
     * @return
     */
    private Map<String, Map<String, Object>> getExtendedInformation(List<Long> stationIdList, List<HygfBusinessField> fields) {
        List<Map<String, Object>> dataMap = businessFieldMapper.getExtendedInformation(stationIdList);
        if (CollectionUtil.isNotEmpty(dataMap)) {
            for (Map<String, Object> item : dataMap) {
                //处理联系人
                dealContacts(item);
            }
        }
        return dealFields(dataMap, fields);
    }

    /**
     * 处理联系人
     * @param item
     */
    private void dealContacts(Map<String, Object> item) {
        if (Objects.nonNull(item.get("contacts"))) {
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("contacts")));
            StringBuilder stringBuilder = new StringBuilder();
            int index = 0;
            for (Object o : jsonArray) {
                if (o instanceof JSONObject) {
                    index++;
                    JSONObject jsonObject = (JSONObject) o;
                    stringBuilder.append("序号:");
                    stringBuilder.append(index);
                    stringBuilder.append("姓名:");
                    stringBuilder.append(jsonObject.get("userName") == null ? "" : jsonObject.get("userName"));
                    stringBuilder.append("关系:");
                    stringBuilder.append(jsonObject.get("relation") == null ? "" : jsonObject.get("relation"));
                    stringBuilder.append("联系电话:");
                    stringBuilder.append(jsonObject.get("telephone") == null ? "" : jsonObject.get("telephone"));
                    stringBuilder.append("电子邮箱:");
                    stringBuilder.append(jsonObject.get("mailbox") == null ? "" : jsonObject.get("mailbox"));
                    stringBuilder.append("QQ:");
                    stringBuilder.append(jsonObject.get("qq") == null ? "" : jsonObject.get("qq"));
                    stringBuilder.append("微信:");
                    stringBuilder.append(jsonObject.get("wechat") == null ? "" : jsonObject.get("wechat"));
                    stringBuilder.append("\n");
                }
            }
            item.put("contacts", stringBuilder.toString());
        }
    }

    /**
     * 获取商务信息
     * @param stationIdList
     * @param fields
     * @return
     */
    private Map<String, Map<String, Object>> getBusinessInformation(List<Long> stationIdList, List<HygfBusinessField> fields) {
        List<Map<String, Object>> businessInformation = businessFieldMapper.getBusinessInformation(stationIdList);
        if (CollectionUtil.isNotEmpty(businessInformation)) {
            for (Map<String, Object> item : businessInformation) {
                if (Objects.nonNull(item.get("type"))) {
                    item.put("type", CommonEnum.getNameByCode(String.valueOf(item.get("type"))));
                }
                if (Objects.nonNull(item.get("legal_type"))) {
                    item.put("legal_type", CommonEnum.getNameByCode(String.valueOf(item.get("legal_type"))));
                }
            }
        }
        return dealFields(businessInformation, fields);
    }

    /**
     * 获取设计信息
     * @param stationIdList
     * @param fields
     * @return
     */
    private Map<String, Map<String, Object>> getDesignInformation(List<Long> stationIdList, List<HygfBusinessField> fields) {
        List<Map<String, Object>> dataMap = businessFieldMapper.getDesignInformation(stationIdList);
        if (CollectionUtil.isNotEmpty(dataMap)) {
            for (Map<String, Object> item : dataMap) {
                if (Objects.nonNull(item.get("anti_skiing"))) {
                    item.put("anti_skiing", CommonEnum.getNameByCode(String.valueOf(item.get("anti_skiing"))));
                }
                //处理组件
                dealAssembly(item);
                //处理逆变器
                dealInverter(item);
                //处理电缆
                dealCable(item);
                //处理并网箱
                dealElectricityMeter(item);
            }
        }
        return dealFields(dataMap, fields);
    }

    private void dealElectricityMeter(Map<String, Object> item) {
        if (Objects.nonNull(item.get("electricity_meter"))) {
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("electricity_meter")));
            StringBuilder stringBuilder = new StringBuilder();
            int index = 0;
            for (Object o : jsonArray) {
                if (o instanceof JSONObject) {
                    index++;
                    JSONObject jsonObject = (JSONObject) o;
                    stringBuilder.append("序号:");
                    stringBuilder.append(index);
                    stringBuilder.append("物料编码:");
                    stringBuilder.append(jsonObject.get("wlbm") == null ? "" : jsonObject.get("wlbm"));
                    stringBuilder.append("物料名称:");
                    stringBuilder.append(jsonObject.get("wlmc") == null ? "" : jsonObject.get("wlmc"));
                    stringBuilder.append("材质:");
                    stringBuilder.append(CommonEnum.getNameByCode(jsonObject.getString("cz")));
                    stringBuilder.append("功率:");
                    stringBuilder.append(jsonObject.get("gl") == null ? "" : jsonObject.get("gl"));
                    stringBuilder.append("类型:");
                    stringBuilder.append(jsonObject.getString("lx") == null ? "" : jsonObject.get("lx"));
                    stringBuilder.append("功能:");
                    stringBuilder.append(jsonObject.get("gn") == null ? "" : jsonObject.get("gn"));
                    stringBuilder.append("相位:");
                    stringBuilder.append(CommonEnum.getNameByCode(jsonObject.getString("xw")));
                    stringBuilder.append("上网模式:");
                    stringBuilder.append(CommonEnum.getNameByCode(jsonObject.getString("swms")));
                    stringBuilder.append("配置数量:");
                    stringBuilder.append(jsonObject.get("pzsl") == null ? "" : jsonObject.get("pzsl") + "个");
                    stringBuilder.append("金额:");
                    stringBuilder.append(jsonObject.get("price") == null ? "" : jsonObject.get("price") + "元");
                    stringBuilder.append("\n");
                }
            }
            item.put("electricity_meter", stringBuilder.toString());
        }
    }

    private void dealCable(Map<String, Object> item) {
        if (Objects.nonNull(item.get("cable"))) {
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("cable")));
            StringBuilder stringBuilder = new StringBuilder();
            int index = 0;
            for (Object o : jsonArray) {
                if (o instanceof JSONObject) {
                    index++;
                    JSONObject jsonObject = (JSONObject) o;
                    stringBuilder.append("序号:");
                    stringBuilder.append(index);
                    stringBuilder.append("物料编码:");
                    stringBuilder.append(jsonObject.get("wlbm") == null ? "" : jsonObject.get("wlbm"));
                    stringBuilder.append("物料名称:");
                    stringBuilder.append(jsonObject.get("wlmc") == null ? "" : jsonObject.get("wlmc"));
                    stringBuilder.append("型号:");
                    stringBuilder.append(jsonObject.get("xh") == null ? "" : jsonObject.get("xh"));
                    stringBuilder.append("规格:");
                    stringBuilder.append(jsonObject.get("gg") == null ? "" : jsonObject.get("gg"));
                    stringBuilder.append("配置数量:");
                    stringBuilder.append(jsonObject.get("pzsl") == null ? "" : jsonObject.get("pzsl") + "米");
                    stringBuilder.append("\n");
                }
            }
            item.put("cable", stringBuilder.toString());
        }
    }

    private void dealInverter(Map<String, Object> item) {
        if (Objects.nonNull(item.get("inverter"))) {
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("inverter")));
            StringBuilder stringBuilder = new StringBuilder();
            int index = 0;
            for (Object o : jsonArray) {
                if (o instanceof JSONObject) {
                    index++;
                    JSONObject jsonObject = (JSONObject) o;
                    stringBuilder.append("序号:");
                    stringBuilder.append(index);
                    stringBuilder.append("物料编码:");
                    stringBuilder.append(jsonObject.get("wlbm") == null ? "" : jsonObject.get("wlbm"));
                    stringBuilder.append("物料名称:");
                    stringBuilder.append(jsonObject.get("wlmc") == null ? "" : jsonObject.get("wlmc"));
                    stringBuilder.append("功率:");
                    stringBuilder.append(jsonObject.get("gl") == null ? "" : jsonObject.get("gl"));
                    stringBuilder.append("系列:");
                    stringBuilder.append(CommonEnum.getNameByCode(jsonObject.getString("xl")));
                    stringBuilder.append("相位:");
                    stringBuilder.append(CommonEnum.getNameByCode(jsonObject.getString("xw")));
                    stringBuilder.append("配置数量:");
                    stringBuilder.append(jsonObject.get("pzsl") == null ? "" : jsonObject.get("pzsl"));
                    stringBuilder.append("金额:");
                    stringBuilder.append(jsonObject.get("price") == null ? "" : jsonObject.get("price") + "元");
                    stringBuilder.append("\n");
                }
            }
            item.put("inverter", stringBuilder.toString());
        }
    }

    private void dealAssembly(Map<String, Object> item) {
        if (Objects.nonNull(item.get("assembly"))) {
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("assembly")));
            StringBuilder stringBuilder = new StringBuilder();
            int index = 0;
            for (Object o : jsonArray) {
                if (o instanceof JSONObject) {
                    index++;
                    JSONObject jsonObject = (JSONObject) o;
                    stringBuilder.append("序号:");
                    stringBuilder.append(index);
                    stringBuilder.append("物料编码:");
                    stringBuilder.append(jsonObject.get("wlbm") == null ? "" : jsonObject.get("wlbm"));
                    stringBuilder.append("物料名称:");
                    stringBuilder.append(jsonObject.get("wlmc") == null ? "" : jsonObject.get("wlmc"));
                    stringBuilder.append("电池片规格:");
                    stringBuilder.append(jsonObject.get("dcpgg") == null ? "" : jsonObject.get("dcpgg"));
                    stringBuilder.append("功率:");
                    stringBuilder.append(jsonObject.get("gl") == null ? "" : jsonObject.get("gl"));
                    stringBuilder.append("类型:");
                    stringBuilder.append(CommonEnum.getNameByCode(jsonObject.getString("lx")));
                    stringBuilder.append("边框:");
                    stringBuilder.append(jsonObject.get("bk") == null ? "" : jsonObject.get("bk"));
                    stringBuilder.append("总功率:");
                    stringBuilder.append(jsonObject.get("zgl") == null ? "" : jsonObject.get("zgl") + "W");
                    stringBuilder.append("单/双面:");
                    stringBuilder.append(CommonEnum.getNameByCode(jsonObject.getString("dsm")));
                    stringBuilder.append("配置数量:");
                    stringBuilder.append(jsonObject.get("pzsl") == null ? "" : jsonObject.get("pzsl") + "块");
                    stringBuilder.append("金额:");
                    stringBuilder.append(jsonObject.get("price") == null ? "" : jsonObject.get("price") + "元");
                    stringBuilder.append("\n");
                }
            }
            item.put("assembly", stringBuilder.toString());
        }
    }

    /**
     * 获取勘察信息
     * @param stationIdList
     * @param fields
     * @return
     */
    private Map<String, Map<String, Object>> getSurveyInformation(List<Long> stationIdList, List<HygfBusinessField> fields) {
        List<Map<String, Object>> surveyInformation = businessFieldMapper.getSurveyInformation(stationIdList);
        if (CollectionUtil.isNotEmpty(surveyInformation)) {
            for (Map<String, Object> item : surveyInformation) {
                if (Objects.nonNull(item.get("house_situation"))) {
                    item.put("house_situation", CommonEnum.getNameByCode(String.valueOf(item.get("house_situation"))));
                }
                if (Objects.nonNull(item.get("house_bias"))) {
                    item.put("house_bias", CommonEnum.getNameByCode(String.valueOf(item.get("house_bias"))));
                }
                if (Objects.nonNull(item.get("house_property"))) {
                    item.put("house_property", CommonEnum.getNameByCode(String.valueOf(item.get("house_property"))));
                }
                if (Objects.nonNull(item.get("house_crack"))) {
                    item.put("house_crack", String.valueOf(item.get("house_crack")).equals("s") ? "是" : "否");
                }
                if (Objects.nonNull(item.get("meter_position"))) {
                    item.put("meter_position", CommonEnum.getNameByCode(String.valueOf(item.get("meter_position"))));
                }
                if (Objects.nonNull(item.get("surveyor_time"))) {
                    item.put("surveyor_time", DateUtils.dateStringFormat(item.get("surveyor_time")));
                }
                if (Objects.nonNull(item.get("roofway"))) {
                    JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("roofway")));
                    List<String> list = new ArrayList<>();
                    for (Object o : jsonArray) {
                        list.add(String.valueOf(o));
                    }
                    item.put("roofway", CommonEnum.getNameByCodeList(list));
                }
                if (Objects.nonNull(item.get("obstacle"))) {
                    JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("obstacle")));
                    List<String> list = new ArrayList<>();
                    for (Object o : jsonArray) {
                        list.add(String.valueOf(o));
                    }
                    item.put("obstacle", CommonEnum.getNameByCodeList(list));
                }
                if (Objects.nonNull(item.get("screen"))) {
                    JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("screen")));
                    List<String> list = new ArrayList<>();
                    for (Object o : jsonArray) {
                        list.add(String.valueOf(o));
                    }
                    item.put("screen", CommonEnum.getNameByCodeList(list));
                }
                if (Objects.nonNull(item.get("house_type"))) {
                    JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("house_type")));
                    List<String> list = new ArrayList<>();
                    for (Object o : jsonArray) {
                        list.add(String.valueOf(o));
                    }
                    item.put("house_type", CommonEnum.getNameByCodeList(list));
                }
                if (Objects.nonNull(item.get("solution_measures"))) {
                    JSONArray jsonArray = JSONArray.parseArray(String.valueOf(item.get("solution_measures")));
                    List<String> list = new ArrayList<>();
                    for (Object o : jsonArray) {
                        list.add(String.valueOf(o));
                    }
                    item.put("solution_measures", CommonEnum.getNameByCodeList(list));
                }
            }
        }
        return dealFields(surveyInformation, fields);
    }

    /**
     * 获取基本信息
     * @param stationIdList
     * @param fields
     * @return
     */
    private Map<String, Map<String, Object>> getBasicInformation(List<Long> stationIdList, List<HygfBusinessField> fields) {
        List<Map<String, Object>> basicInformation = businessFieldMapper.getBasicInformation(stationIdList);
        if (CollectionUtil.isNotEmpty(basicInformation)) {
            //对个别类型进行翻译
            for (Map<String, Object> item : basicInformation) {
                if (Objects.nonNull(item.get("power_station_type"))) {
                    item.put("power_station_type", CommonEnum.getNameByCode(String.valueOf(item.get("power_station_type"))));
                }
                if (Objects.nonNull(item.get("owner_type"))) {
                    item.put("owner_type", CommonEnum.getNameByCode(String.valueOf(item.get("owner_type"))));
                }
                if (Objects.nonNull(item.get("creator_time"))) {
                    item.put("creator_time", DateUtils.dateStringFormat(item.get("creator_time")));
                }
            }
        }
        return dealFields(basicInformation, fields);
    }

    /**
     * 处理动态字段
     * @param selectMapList
     * @param fields
     * @return
     */
    private Map<String, Map<String, Object>> dealFields(List<Map<String, Object>> selectMapList, List<HygfBusinessField> fields) {
        Map<String, Map<String, Object>> result = new HashMap<>();
        if (CollectionUtil.isNotEmpty(selectMapList) && CollectionUtil.isNotEmpty(fields)) {
            for (Map<String, Object> stringObjectMap : selectMapList) {
                Map<String, Object> fieldMap = new HashMap<>();
                for (HygfBusinessField field : fields) {
                    fieldMap.put(field.getFieldName() + "_" + field.getBusinessName(), stringObjectMap.get(field.getFieldFlag()));
                }
                result.put(String.valueOf(stringObjectMap.get("stationId")), fieldMap);
            }

        }
        return result;
    }
}
