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

import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.common.api.dto.*;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormColumn;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.api.entity.FireChemical;
import com.yeejoin.amos.boot.module.common.api.entity.FireExperts;
import com.yeejoin.amos.boot.module.common.api.entity.FireStation;
import com.yeejoin.amos.boot.module.common.api.entity.FireTeam;
import com.yeejoin.amos.boot.module.common.api.entity.Firefighters;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersContacts;
import com.yeejoin.amos.boot.module.common.api.entity.MaintenanceCompany;
import com.yeejoin.amos.boot.module.common.api.excel.ExcelUtil;
import com.yeejoin.amos.boot.module.common.api.service.IDutyPersonService;
import com.yeejoin.amos.boot.module.common.api.service.IKeySiteService;
import com.yeejoin.amos.boot.module.common.api.service.IMaintenanceCompanyService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.*;
import com.yeejoin.amos.boot.module.jcs.api.dto.AircraftDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.Aircraft;
import com.yeejoin.amos.boot.module.jcs.api.enums.ExcelEnums;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.ibatis.annotations.Case;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.elasticsearch.search.aggregations.metrics.ParsedSingleValueNumericMetricsAggregation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author tb
 */
@Service
public class ExcelServiceImpl {

    private static final String NOT_DUTY = "休班";
    private static final String PERSON = "PERSON";
    private static final String MAINTENANCE_PERSON = "maintenancePerson";
    @Autowired
    DataSourcesImpl dataSourcesImpl;
    @Autowired
    FireChemicalServiceImpl fireChemicalServiceImpl;
    @Autowired
    FireExpertsServiceImpl fireExpertsServiceImpl;
    @Autowired
    WaterResourceServiceImpl waterResourceServiceImpl;
    @Autowired
    AircraftServiceImpl aircraftServiceImpl;
    @Autowired
    FireTeamServiceImpl fireTeamService;
    @Autowired
    FireStationServiceImpl fireStationService;
    @Autowired
    FirefightersServiceImpl firefightersService;
    @Autowired
    IMaintenanceCompanyService maintenanceCompanyService;
    @Autowired
    IKeySiteService keySiteService;
    @Autowired
    DutyCarServiceImpl dutyCarService;
    @Autowired
    DutyPersonServiceImpl dutyPersonService;
    @Autowired
    Sequence sequence;
    @Autowired
    DynamicFormColumnServiceImpl dynamicFormColumnService;
    @Autowired
    DutyPersonShiftServiceImpl dutyPersonShiftService;
    @Autowired
    OrgUsrServiceImpl orgUsrService;
    @Autowired
    DutyShiftServiceImpl dutyShiftService;
    @Autowired
    IDutyPersonService iDutyPersonService;
    @Autowired
    DynamicFormColumnServiceImpl dynamicFormColumnServiceImpl;
    @Autowired
    LinkageUnitServiceImpl linkageUnitServiceImpl;

    public void templateExport(HttpServletResponse response, ExcelDto excelDto) throws ClassNotFoundException {
        String url = excelDto.getClassUrl();
        Class<?> clz = Class.forName(url);
        ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null, clz,
                dataSourcesImpl, true);
    }

    public void commonExport(HttpServletResponse response, ExcelDto excelDto) {
        switch (excelDto.getType()) {

            case "WHP":
                List<FireChemicalDto> data = fireChemicalServiceImpl.queryForFireChemicalList(false);
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), data,
                        FireChemicalDto.class, dataSourcesImpl, false);
                break;
            case "XFZJ":
                List<FireExpertsDto> fireExpertsDtoList = fireExpertsServiceImpl.queryForFireExpertsList(false);
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                        fireExpertsDtoList, FireExpertsDto.class, dataSourcesImpl, false);
                break;
            case "SYXX":
                List<WaterResourceDto> waterResourceDtoList = waterResourceServiceImpl.exportToExcel(true);
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                        waterResourceDtoList, WaterResourceDto.class, dataSourcesImpl, false);
                break;
            case "HKQ":
                List<AircraftDto> aircraftDtoList = aircraftServiceImpl.queryAircraftDtoForList(false);
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                        aircraftDtoList, AircraftDto.class, dataSourcesImpl, false);
                break;
            case "XFDW":
                List<FireTeamDto> fireTeamDtoList = fireTeamService.queryFireTeamForList(false);
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), fireTeamDtoList,
                        FireTeamDto.class, dataSourcesImpl, false);
                break;
            case "WXXFZ":
                List<FireStationDto> fireStationDtoList = fireStationService.queryForFireStationList(false);
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                        fireStationDtoList, FireStationDto.class, null, false);
                break;
            case "XFRY":
                List<FirefightersExcelDto> firefightersExcelDtoList = firefightersService.exportToExcel(false);
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                        firefightersExcelDtoList, FirefightersExcelDto.class, null, false);
                break;
            case "WBRY":
                List<MaintenancePersonExcleDto> maintenancePersonExcelDtoList =
                        maintenanceCompanyService.exportToMaintenancePersonExcel();
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                        maintenancePersonExcelDtoList, MaintenancePersonExcleDto.class, null, false);
                break;
            case "KEYSITE":
                List<KeySiteExcleDto> keySiteDtoList = keySiteService.exportToExcel();
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                        keySiteDtoList, KeySiteExcleDto.class, null, false);
                break;
            case "JCDWRY":
                List<OrgUsrExcelDto> orgUsrList = orgUsrService.exportToExcel();

                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                        orgUsrList, OrgUsrExcelDto.class, null, false);
                break;
            case "LDDW":
                List<LinkageUnitDto> LinkageUnitDtoList = linkageUnitServiceImpl.exportToExcel();

                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                        LinkageUnitDtoList, LinkageUnitDto.class, null, false);
                break;
             default:
                break;
        }
    }

    public void commonUpload(MultipartFile multipartFile, ExcelDto excelDto) throws Exception {
        switch (excelDto.getType()) {

            case "WHP":
                excelImportFireChemical(multipartFile);
                break;
            case "XFZJ":
                excelImportFireExperts(multipartFile);
                break;
            case "SYXX":
                excelImportWaterResource(multipartFile);
                break;
            case "HKQ":
                excelImportAircraft(multipartFile);
                break;
            case "XFDW":
                excelImportFireTeam(multipartFile);
                break;
            case "WXXFZ":
                excelImportFireStation(multipartFile);
                break;
            case "XFRY":
                excelImportFirefighters(multipartFile);
                break;
            case "CLZQ":
                excelImportDutyPerson(multipartFile, "CLZQ");
                break;
            case "RYZB":
                excelImportDutyPerson(multipartFile, "RYZB");
                break;
            case "WBRY":
                excelImportMaintenancePerson(multipartFile);
                break;
            case "KEYSITE":
                excelImportKeySite(multipartFile);
                break;
            case "JCDWRY":
                excelImportOrgUsrExcelDto(multipartFile);
                break;
            case "LDDW":
                excelImportLinkageUnitZhDto(multipartFile);
                break;
        }
        return;
    }



    private void excelImportLinkageUnitZhDto(MultipartFile multipartFile) throws Exception {
        List<LinkageUnitDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile,
                LinkageUnitDto.class, 1);

        if(excelDtoList!=null&&excelDtoList.size()>0){
            excelDtoList.forEach(linkageUnitDto->{
                if(linkageUnitDto.getLinkageUnitType()!=null){
                    String[] certificates = linkageUnitDto.getLinkageUnitType().split("@");
                    linkageUnitDto.setLinkageUnitType(certificates[0]);
                    linkageUnitDto.setLinkageUnitTypeCode(certificates[1]);
                }
                if(linkageUnitDto.getEmergencyLinkageUnit()!=null){
                    String[] certificates = linkageUnitDto.getEmergencyLinkageUnit().split("@");
                    linkageUnitDto.setEmergencyLinkageUnit(certificates[0]);
                    linkageUnitDto.setEmergencyLinkageUnitCode(certificates[1]);
                }

                linkageUnitServiceImpl.saveLinkageModel(linkageUnitDto);
            });
        }




    }

    private void excelImportOrgUsrExcelDto(MultipartFile multipartFile) throws Exception {

            List<OrgUsrExcelDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile,
                    OrgUsrExcelDto.class, 1);

            if(excelDtoList!=null&&excelDtoList.size()>0){
                excelDtoList.forEach(orgUsrExcelDto->{
                    if(orgUsrExcelDto.getParentId()!=null){
                        String[] certificates = orgUsrExcelDto.getParentId().split("@");
                        orgUsrExcelDto.setParentId(certificates[1]);
                    }
            // 动态字段填充

                    List<DynamicFormInitDto> dynamicFormColumn = dynamicFormColumnServiceImpl.getFormlist("246");

                    List<DynamicFormInstanceDto> dynamicFormValue =new ArrayList<>();
                    List<DynamicFormInstance> dynamicFormInstancelist =new ArrayList<>();

                    dynamicFormColumn.forEach(DynamicFormInitDto->{
                        dynamicFormValue.add(DynamicFormInitDto.getFormItemDescr());
                    });

                    dynamicFormValue.forEach(dynamicFormInstanceDto->{
                        switch (dynamicFormInstanceDto.getFieldCode()) {

                            case "administrativePositionCode":
                                if(orgUsrExcelDto.getAdministrativePositionCode()!=null){
                                    String[] certificates = orgUsrExcelDto.getAdministrativePositionCode().split("@");
                                    dynamicFormInstanceDto.setFieldValue(certificates[1]);
                                    dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

                                }
                                break;
                            case "auditCycle":
                                if(orgUsrExcelDto.getAuditCycle()!=null){
                                    String[] certificates = orgUsrExcelDto.getAuditCycle().split("@");
                                    dynamicFormInstanceDto.setFieldValue(certificates[1]);
                                    dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

                                }
                                break;
                            case "certificatesNumber":
                                 dynamicFormInstanceDto.setFieldValue(orgUsrExcelDto.getCertificatesNumber());
                                break;
                            case "certificatesTypeCode":
                                if(orgUsrExcelDto.getCertificatesTypeCode()!=null){
                                    String[] certificates = orgUsrExcelDto.getCertificatesTypeCode().split("@");
                                    dynamicFormInstanceDto.setFieldValue(certificates[1]);
                                    dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

                                }
                                break;
                            case "certificateType":
                                if(orgUsrExcelDto.getCertificateType()!=null){
                                    String[] certificates = orgUsrExcelDto.getCertificateType().split("@");
                                    dynamicFormInstanceDto.setFieldValue(certificates[1]);
                                    dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

                                }
                            case "fireManagementPostCode":
                                if(orgUsrExcelDto.getFireManagementPostCode()!=null){
                                    String[] certificates = orgUsrExcelDto.getFireManagementPostCode().split("@");
                                    dynamicFormInstanceDto.setFieldValue(certificates[1]);
                                    dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

                                }
                                break;
                            case "gender":
                                 dynamicFormInstanceDto.setFieldValue(orgUsrExcelDto.getGender());
                                break;
                            case "internalPositionCode":
                                if(orgUsrExcelDto.getInternalPositionCode()!=null){
                                    String[] certificates = orgUsrExcelDto.getInternalPositionCode().split("@");
                                    dynamicFormInstanceDto.setFieldValue(certificates[1]);
                                    dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

                                }
                                break;
                            case "personNumber":
                                dynamicFormInstanceDto.setFieldValue(orgUsrExcelDto.getPersonNumber());
                                break;
                            case "positionType":
                                if(orgUsrExcelDto.getPositionType()!=null){
                                    String[] certificates = orgUsrExcelDto.getPositionType().split("@");
                                    dynamicFormInstanceDto.setFieldValue(certificates[1]);
                                    dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

                                }
                                break;
                            case "safetyTraining":
                                if(orgUsrExcelDto.getSafetyTraining()!=null){
                                    String[] certificates = orgUsrExcelDto.getSafetyTraining().split("@");
                                    dynamicFormInstanceDto.setFieldValue(certificates[1]);
                                    dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

                                }
                                break;
                            case "stateCode":
                                if(orgUsrExcelDto.getStateCode()!=null){
                                    String[] certificates = orgUsrExcelDto.getStateCode().split("@");
                                    dynamicFormInstanceDto.setFieldValue(certificates[1]);
                                    dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

                                }
                                break;
                            case "telephone":
                                dynamicFormInstanceDto.setFieldValue(orgUsrExcelDto.getTelephone());
                                break;

                        }

                        DynamicFormInstance dynamicFormInstance=new DynamicFormInstance();
                        BeanUtils.copyProperties(dynamicFormInstanceDto, dynamicFormInstance);
                        dynamicFormInstancelist.add(dynamicFormInstance);

                    });

                    orgUsrExcelDto.setDynamicFormValue(dynamicFormInstancelist);


                    try {
                        orgUsrService.saveOrgPersonExcel(orgUsrExcelDto);
                    } catch (Exception e) {
                        throw  new RuntimeException("导入失败!");
                    }
                });
            }



    }









    private void excelImportFirefighters(MultipartFile multipartFile) throws Exception {
        List<FirefightersExcelDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile,
                FirefightersExcelDto.class, 1);
        excelDtoList.forEach(
                item -> {
                    Firefighters firefighters = new Firefighters();
                    FirefightersContacts firefightersContacts = new FirefightersContacts();
                    firefighters = Bean.toPo(item, firefighters);
                    firefightersContacts = Bean.toPo(item, firefightersContacts);
                    if (item.getFireTeam() != null) {
                        Long fireTeamId = Long.valueOf(item.getFireTeam().split("@")[1]);
                        firefighters.setFireTeamId(fireTeamId);
                    }
                    if (firefighters.getCertificatesType() != null) {
                        String[] certificates = firefighters.getCertificatesType().split("@");
                        firefighters.setCertificatesType(certificates[0]);
                        firefighters.setCertificatesTypeCode(certificates[1]);
                    }
                    if (firefighters.getState() != null) {
                        String[] state = firefighters.getState().split("@");
                        firefighters.setState(state[0]);
                        firefighters.setStateCode(state[1]);
                    }
                    if (firefighters.getJobTitle() != null) {
                        String[] jobTitle = firefighters.getJobTitle().split("@");
                        firefighters.setJobTitle(jobTitle[0]);
                        firefighters.setJobTitleCode(jobTitle[1]);
                    }
                    if (firefightersContacts.getRelationship() != null) {
                        String relationship = firefightersContacts.getRelationship().split("@")[1];
                        firefightersContacts.setRelationship(relationship);
                    }
                    FirefightersInfoDto firefightersInfo = new FirefightersInfoDto(firefighters, firefightersContacts);
                    firefightersService.saveFirefighters(firefightersInfo);
                }
        );
    }

    private void excelImportFireStation(MultipartFile multipartFile) throws Exception {
        List<FireStationDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, FireStationDto.class, 1);
        List<FireStation> excelEntityList = new ArrayList<>();
        excelDtoList.forEach(
                item -> {
                    FireStation fireStation = new FireStation();
                    fireStation = Bean.toPo(item, fireStation);
                    if (fireStation.getWhereBuilding() != null) {
                        String[] whereBuilding = fireStation.getWhereBuilding().split("@");
                        fireStation.setWhereBuilding(whereBuilding[0]);
                        fireStation.setWhereBuildingId(whereBuilding[1]);
                    }
                    if (fireStation.getBizCompany() != null) {
                        String[] bizCompany = fireStation.getBizCompany().split("@");
                        fireStation.setBizCompany(bizCompany[0]);
                        fireStation.setBizCompanyId(Long.valueOf(bizCompany[1]));
                        fireStation.setBizCompanyCode(bizCompany[2]);
                    }
                    excelEntityList.add(fireStation);
                }
        );
        fireStationService.saveBatch(excelEntityList);
    }

    private void excelImportFireTeam(MultipartFile multipartFile) throws Exception {
        List<FireTeamDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, FireTeamDto.class, 1);
        List<FireTeam> excelEntityList = new ArrayList<>();
        excelDtoList.forEach(
                item -> {
                    FireTeam fireTeam = new FireTeam();
                    fireTeam = Bean.toPo(item, fireTeam);
                    if (fireTeam.getType() != null) {
                        String[] type = fireTeam.getType().split("@");
                        fireTeam.setType(type[0]);
                        fireTeam.setTypeCode(type[1]);
                    }
                    if (fireTeam.getContactUser() != null) {
                        String[] contactUser = fireTeam.getContactUser().split("@");
                        fireTeam.setContactUser(contactUser[0]);
                        fireTeam.setContactUserId(Long.valueOf(contactUser[1]));
                    }
                    if (item.getParentName() != null) {
                        String[] parentName = item.getParentName().split("@");
                        fireTeam.setParent(Long.valueOf(parentName[1]));
                    }
                    excelEntityList.add(fireTeam);
                }
        );
        fireTeamService.saveBatch(excelEntityList);
    }

    private void excelImportAircraft(MultipartFile multipartFile) throws Exception {
        List<AircraftDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, AircraftDto.class, 1);
        List<Aircraft> excelEntityList = new ArrayList<>();
        excelDtoList.forEach(
                item -> {
                    Aircraft aircraft = new Aircraft();
                    aircraft = Bean.toPo(item, aircraft);
                    if (aircraft.getEngineType() != null) {
                        String[] engineType = aircraft.getEngineType().split("@");
                        aircraft.setEngineType(engineType[0]);
                        aircraft.setEngineTypeCode(engineType[1]);
                    }
                    if (aircraft.getFuelType() != null) {
                        String[] fuelType = aircraft.getFuelType().split("@");
                        aircraft.setFuelType(fuelType[0]);
                        aircraft.setFuelTypeCode(fuelType[1]);
                    }
                    excelEntityList.add(aircraft);
                }
        );
        aircraftServiceImpl.saveBatch(excelEntityList);
    }

    private void excelImportFireChemical(MultipartFile multipartFile) throws Exception {
        List<FireChemicalDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, FireChemicalDto.class, 1);
        List<FireChemical> excelEntityList = new ArrayList<>();
        excelDtoList.forEach(
                item -> {
                    FireChemical fireChemical = new FireChemical();
                    fireChemical = Bean.toPo(item, fireChemical);
                    if (fireChemical.getType() != null) {
                        String[] type = fireChemical.getType().split("@");
                        fireChemical.setType(type[0]);
                        fireChemical.setTypeCode(type[1]);
                    }
                    excelEntityList.add(fireChemical);
                }
        );
        fireChemicalServiceImpl.saveBatch(excelEntityList);
    }

    private void excelImportWaterResource(MultipartFile multipartFile) throws Exception {
        List<WaterResourceDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile,
                WaterResourceDto.class, 1);
        excelDtoList.forEach(
                item -> {
                    if (item.getResourceTypeName() != null) {
                        String[] resourceTypeName = item.getResourceTypeName().split("@");
                        item.setResourceTypeName(resourceTypeName[0]);
                        item.setResourceType(resourceTypeName[1]);
                    }
                    if (item.getSystemType() != null) {
                        String[] systemType = item.getSystemType().split("@");
                        item.setSystemType(systemType[0]);
                        item.setSystemTypeCode(systemType[1]);
                    }
                    if (item.getPlaceForm() != null) {
                        String[] placeForm = item.getPlaceForm().split("@");
                        item.setPlaceForm(placeForm[0]);
                        item.setPlaceFormCode(placeForm[1]);
                    }
                    if (item.getBelongBuilding() != null) {
                        String[] belongBuilding = item.getBelongBuilding().split("@");
                        item.setBelongBuilding(belongBuilding[0]);
                        item.setBelongBuildingId(Long.valueOf(belongBuilding[1]));
                    }
                    if (item.getBelongFightingSystem() != null) {
                        String[] belongFightingSystem = item.getBelongFightingSystem().split("@");
                        item.setBelongFightingSystem(belongFightingSystem[0]);
                        item.setBelongFightingSystemId(Long.valueOf(belongFightingSystem[1]));
                    }
                    if (item.getManagementUnit() != null) {
                        String[] managementUnit = item.getManagementUnit().split("@");
                        item.setManagementUnit(managementUnit[0]);
                        item.setManagementUnitId(Long.valueOf(managementUnit[1]));
                    }
                    if (item.getMaintenanceUnit() != null) {
                        String[] maintenanceUnit = item.getMaintenanceUnit().split("@");
                        item.setMaintenanceUnit(maintenanceUnit[0]);
                        item.setMaintenanceUnitId(Long.valueOf(maintenanceUnit[1]));
                    }
                    if (item.getHoseConnection() != null) {
                        String[] hoseConnection = item.getHoseConnection().split("@");
                        item.setHoseConnection(hoseConnection[0]);
                        item.setHoseConnectionCode(hoseConnection[1]);
                    }
                    if (item.getIntakeForm() != null) {
                        String[] intakeForm = item.getIntakeForm().split("@");
                        item.setIntakeForm(intakeForm[0]);
                    }
                    if (item.getPipeTypeName() != null) {
                        String[] pipeTypeName = item.getPipeTypeName().split("@");
                        item.setPipeTypeName(pipeTypeName[0]);
                        item.setPipeTypeCode(pipeTypeName[1]);
                    }
                    if (item.getStatus() != null) {
                        String[] status = item.getStatus().split("@");
                        item.setStatus(status[0]);
                        item.setStatusCode(status[1]);
                    }
                    if (item.getType() != null) {
                        String[] type = item.getType().split("@");
                        item.setType(type[0]);
                        item.setTypeCode(type[1]);
                    }
                    waterResourceServiceImpl.importByExcel(item);
                }
        );
    }

    private void excelImportFireExperts(MultipartFile multipartFile) throws Exception {
        List<FireExpertsDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile,
                FireExpertsDto.class, 1);
        List<FireExperts> excelEntityList = new ArrayList<>();
        excelDtoList.forEach(
                fireExpertsDto -> {
                    FireExperts fireExperts = new FireExperts();
                    fireExperts = Bean.toPo(fireExpertsDto, fireExperts);
                    if (fireExperts.getCertificatesType() != null) {
                        String[] certificates = fireExperts.getCertificatesType().split("@");
                        fireExperts.setCertificatesType(certificates[0]);
                        fireExperts.setCertificatesTypeCode(certificates[1]);
                    }
                    if (fireExperts.getJobs() != null) {
                        String[] jobs = fireExperts.getJobs().split("@");
                        fireExperts.setJobs(jobs[0]);
                        fireExperts.setJobsCode(jobs[1]);
                    }
                    if (fireExperts.getExpert() != null) {
                        String[] expert = fireExperts.getExpert().split("@");
                        fireExperts.setExpert(expert[0]);
                        fireExperts.setExpertCode(expert[1]);
                    }
                    if (fireExperts.getHighestEducation() != null) {
                        String[] highestEducation = fireExperts.getHighestEducation().split("@");
                        fireExperts.setHighestEducation(highestEducation[0]);
                    }
                    excelEntityList.add(fireExperts);
                }
        );
        fireExpertsServiceImpl.saveBatch(excelEntityList);
    }

    private void excelImportDutyPerson(MultipartFile multipartFile, String dutyType) throws Exception {

        String fileName = multipartFile.getOriginalFilename();
        if (fileName == null) {
            throw new Exception("文件不存在！");
        }
        if (!fileName.toLowerCase().endsWith(ExcelTypeEnum.XLS.getValue()) && !fileName.toLowerCase().endsWith(ExcelTypeEnum.XLSX.getValue())) {
            throw new Exception("文件类型异常！");
        }
        InputStream input = multipartFile.getInputStream();
        XSSFWorkbook workbook = new XSSFWorkbook(input);
        XSSFSheet sheet = workbook.getSheetAt(0);
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (sheet != null) {
            //获取表头月份
            Row titleRow = sheet.getRow(0);
            Cell monthCell = titleRow.getCell(5);
            String dateStr = monthCell == null ? "" : monthCell.toString();

            List<Date> dayByMonth = DateUtils.getDayByMonth(dateStr);
            if (ExcelEnums.CLZQ.getType().equals(dutyType)) {
                initDutyCarData(sheet, dataList, dayByMonth);
                dutyCarService.saveImportData(dataList);
            } else if (ExcelEnums.RYZB.getType().equals(dutyType)) {
                initDutyPersonData(sheet, dataList, dayByMonth);
                dutyPersonService.saveImportData(dataList);
            }
        }
    }

    private void initDutyCarData(XSSFSheet sheet, List<Map<String, Object>> dataList, List<Date> dayByMonth) {
        //遍历行，i = 1，从第二行开始，第一行是表头跳过。
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            DutyCarDto dutyCarDto = new DutyCarDto();
            //row是一行数据，row.getCell(i),代表拿到这一行，第i列数据
            Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            Cell cell = row.getCell(1);
            if (cell != null) {
                String[] split = cell.toString().split("@");
                dutyCarDto.setTeamName(split[0]);
                dutyCarDto.setTeamId(split[1]);
            }
            cell = row.getCell(2);
            if (cell != null) {
                String[] userName = cell.toString().split("@");
                dutyCarDto.setUserName(userName[0]);
                dutyCarDto.setUserId(userName[1]);

                cell = row.getCell(3);
                if (cell != null) {
                    String[] postType = cell.toString().split("@");
                    dutyCarDto.setPostTypeName(postType[0]);
                    dutyCarDto.setPostType(postType[1]);
                }
                cell = row.getCell(4);
                if (cell != null) {
                    String[] carName = cell.toString().split("@");
                    dutyCarDto.setCarName(carName[0]);
                    dutyCarDto.setCarId(carName[1]);
                }
                List<DutyPersonShiftDto> dutyShift = dutyCarDto.getDutyShift();
                for (int j = 0; j < dayByMonth.size(); j++) {
                    cell = row.getCell(5 + j);
                    String dutyType = cell == null ? "" : cell.toString();
                    if (!StringUtils.isEmpty(dutyType)) {
                        DutyPersonShiftDto dutyPersonShiftDto = new DutyPersonShiftDto();
                        dutyPersonShiftDto.setDutyDate(dayByMonth.get(j));
                        dutyPersonShiftDto.setShiftId(Long.valueOf(dutyType.split("@")[1]));
                        dutyShift.add(dutyPersonShiftDto);
                    }
                }
                Map<String, Object> dutyCarDtoMap = Bean.BeantoMap(dutyCarDto);
                dataList.add(dutyCarDtoMap);
            }
        }
    }

    private void initDutyPersonData(XSSFSheet sheet, List<Map<String, Object>> dataList, List<Date> dayByMonth) {
        //遍历行，i = 1，从第二行开始，第一行是表头跳过。
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            DutyPersonDto dutyPersonDto = new DutyPersonDto();
            //row是一行数据，row.getCell(i),代表拿到这一行，第i列数据
            Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            Cell cell = row.getCell(1);
            if (cell != null) {
                dutyPersonDto.setUserId(cell.toString());
                cell = row.getCell(2);
                if (cell != null) {
                    dutyPersonDto.setUserName(cell.toString());
                }
                cell = row.getCell(3);
                if (cell != null) {
                    String[] split = cell.toString().split("@");
                    dutyPersonDto.setDeptName(split[0]);
                    dutyPersonDto.setDeptId(split[1]);
                }
                cell = row.getCell(4);
                if (cell != null) {
                    String[] split = cell.toString().split("@");
                    dutyPersonDto.setPostTypeName(split[0]);
                    dutyPersonDto.setPostType(split[1]);
                }
                List<DutyPersonShiftDto> dutyShift = new ArrayList<>();
                for (int j = 0; j < dayByMonth.size(); j++) {
                    cell = row.getCell(5 + j);
                    String dutyType = cell == null ? "" : cell.toString();
                    if (!StringUtils.isEmpty(dutyType)) {
                        DutyPersonShiftDto dutyPersonShiftDto = new DutyPersonShiftDto();
                        dutyPersonShiftDto.setDutyDate(dayByMonth.get(j));
                        dutyPersonShiftDto.setShiftId(Long.valueOf(dutyType.split("@")[1]));
                        dutyShift.add(dutyPersonShiftDto);
                    }
                }
                dutyPersonDto.setDutyShift(dutyShift);
                Map<String, Object> dutyPersonDtoMap = Bean.BeantoMap(dutyPersonDto);
                dataList.add(dutyPersonDtoMap);
            }
        }
    }

    private void excelImportMaintenancePerson(MultipartFile multipartFile) throws Exception {
        List<MaintenancePersonExcleDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile,
                MaintenancePersonExcleDto.class, 1);
        List<DynamicFormColumn> columns =
                dynamicFormColumnService.list(new LambdaQueryWrapper<DynamicFormColumn>().eq(DynamicFormColumn::getGroupCode, MAINTENANCE_PERSON));
        List<MaintenanceCompany> maintenanceCompanyList = new ArrayList<MaintenanceCompany>();
        List<DynamicFormInstance> dynamicFormInstanceList = new ArrayList<DynamicFormInstance>();
        for (MaintenancePersonExcleDto maintenancePersonExcleDto : excelDtoList) {
            Long instanceId = sequence.nextId();
            // 先填充主表的属性
            MaintenanceCompany maintenanceCompany = new MaintenanceCompany();
            maintenanceCompany = Bean.toPo(maintenancePersonExcleDto, maintenanceCompany);
            maintenanceCompany.setType(PERSON);
            if (maintenanceCompany.getParentId() != null) {
                long getParentId = Long.valueOf(maintenancePersonExcleDto.getParentName().split("@")[1]);
                maintenanceCompany.setParentId(getParentId);
            }
            if (maintenanceCompanyService.checkPersonCodeExists(maintenancePersonExcleDto.getCode())) {
                maintenanceCompany.setBizCode(maintenancePersonExcleDto.getCode());
            } else {
                maintenanceCompany.setCode(null);
            }
            maintenanceCompany.setOrgCode(null);
            maintenanceCompany.setBizCode(sequence.nextId() + "");
            maintenanceCompany.setInstanceId(instanceId);
            maintenanceCompanyList.add(maintenanceCompany);
            maintenanceCompanyService.maintenancePersonExcleDtoToDynamicFormInstanceList(columns,
                    maintenancePersonExcleDto, instanceId, dynamicFormInstanceList);
        }
        maintenanceCompanyService.saveMaintenanceCompanyBatch(maintenanceCompanyList, dynamicFormInstanceList);
    }

    private void excelImportKeySite(MultipartFile multipartFile) throws Exception {
        List<KeySiteExcleDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile,
                KeySiteExcleDto.class, 1);
        keySiteService.saveExcel(excelDtoList);
    }








    public void dutyTemplateExport(HttpServletResponse response, String beginDate, String endDate, ExcelDto excelDto,
                                   String ids) {
        List<List<Object>> data = new ArrayList<>();
        if (ExcelEnums.CLZQ.getType().equals(excelDto.getType())) {
            data = initDutyCarTemplate(ids);
        } else if (ExcelEnums.RYZB.getType().equals(excelDto.getType())) {
            data = initDutyPersonTemplate(ids);
        }
        // 获取日期
        List<Map<String, Object>> rangeDate = dutyPersonShiftService.getBaseMapper().genRangeDate(beginDate,
                endDate);
        List<String> dayByMonth = new ArrayList<>();
        rangeDate.forEach(item -> dayByMonth.add((String) item.get("date")));
        exportDutyTemplate(response, excelDto.getClassUrl(), dayByMonth, excelDto, data, true);
    }

    public void dutyInfoExport(HttpServletResponse response, String beginDate, String endDate, ExcelDto excelDto) throws ParseException {
        // 获取日期
        List<Map<String, Object>> rangeDate = dutyPersonShiftService.getBaseMapper().genRangeDate(beginDate,
                endDate);
        List<String> dayByMonth = new ArrayList<>();
        rangeDate.forEach(item -> dayByMonth.add((String) item.get("date")));
        List<List<Object>> data = new ArrayList<>();
        if (ExcelEnums.CLZQ.getType().equals(excelDto.getType())) {
            data = initDutyCarInfo(beginDate, endDate, dayByMonth);
        } else if (ExcelEnums.RYZB.getType().equals(excelDto.getType())) {
            data = initDutyPersonInfo(beginDate, endDate, dayByMonth);
        }

        exportDutyTemplate(response, excelDto.getClassUrl(), dayByMonth, excelDto, data, false);
    }

    private List<List<Object>> initDutyCarTemplate(String teamIds) {
        List<List<Object>> data = new ArrayList<>();
        // 根据id列表获取队伍下的人
        List<String> teamIdList = Lists.newArrayList();
        if (!ValidationUtil.isEmpty(teamIds)) {
            teamIdList = Lists.newArrayList(teamIds.split(","));
        }
        List<FirefightersDto> firefightersDtoList = fireTeamService.getFighterByTeamId(teamIdList);

        if (!firefightersDtoList.isEmpty()) {
            AtomicInteger row = new AtomicInteger(1);
            firefightersDtoList.forEach(o -> {
                ArrayList<Object> list = new ArrayList<>();
                list.add(row.getAndIncrement());
                list.add(o.getFireTeamName() + "@" + o.getFireTeamId());
                list.add(o.getName() + "@" + o.getSequenceNbr());
                list.add(o.getJobTitle() + "@" + o.getJobTitleCode());
                data.add(list);
            });
        }
        return data;
    }

    private List<List<Object>> initDutyPersonTemplate(String ids) {
        List<List<Object>> data = new ArrayList<>();
        // 根据id列表获取部门下的人
        List<Long> idList = Lists.newArrayList();
        if (!ValidationUtil.isEmpty(ids)) {
            String[] strings = ids.split(",");
            Long[] convert = (Long[]) ConvertUtils.convert(strings, Long.class);
            idList = Arrays.asList(convert);
        }
        try {
            List<CompanyPerson> companyPeople = orgUsrService.returnCompanyPerson(idList);
            if (!companyPeople.isEmpty()) {
                AtomicInteger row = new AtomicInteger(1);
                companyPeople.forEach(item -> {
                    List<OrgUsrDto> persons = item.getPersons();
                    if (persons != null && !persons.isEmpty()) {
                        persons.forEach(o -> {
                            ArrayList<Object> list = new ArrayList<>();
                            list.add(row.getAndIncrement());
                            list.add(o.getSequenceNbr().toString());
                            list.add(o.getBizOrgName());
                            list.add(item.getBizOrgName() + "@" + item.getSequenceNbr());
                            data.add(list);
                        });
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统异常！");
        }
        return data;
    }

    private void exportDutyTemplate(HttpServletResponse response, String classUrl, List<String> dayByMonth,
                                    ExcelDto excelDto, List<? extends Object> data, Boolean flag) {
        try {
            // 获取排班类型
            String[] dutyNameList = getDutyNameList();
            Class<?> clz = Class.forName(classUrl);
            ExcelUtil.createDutyTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), data,
                    clz, dayByMonth, dutyNameList, dataSourcesImpl, flag);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private String[] getDutyNameList() {
        List<String> dutyShiftList = new ArrayList<>();
        List<DutyShiftDto> dutyShiftDtoList = dutyShiftService.queryForDutyShiftList(null, false);
        dutyShiftDtoList.forEach(item -> dutyShiftList.add(item.getName() + "@" + item.getSequenceNbr()));
        return dutyShiftList.toArray(new String[dutyShiftList.size()]);
    }

    private List<List<Object>> initDutyCarInfo(String beginDate, String endDate, List<String> dayByMonth) throws ParseException {
        // 查询已值班数据
        List<DutyCarDto> contentList = dutyCarService.downloadList(beginDate, endDate);
        List<List<Object>> data = new ArrayList<>();
        // 组装导出数据
        if (!contentList.isEmpty()) {
            AtomicInteger row = new AtomicInteger(1);
            contentList.forEach(o -> {
                ArrayList<Object> list = new ArrayList<>();
                list.add(row.getAndIncrement());
                list.add(o.getTeamName());
                list.add(o.getUserName());
                list.add(o.getPostTypeName());
                list.add(o.getCarName());

                List<DutyPersonShiftDto> dutyShift = o.getDutyShift();
                initDutyShift(dayByMonth, dutyShift, list);

                data.add(list);
            });
        }
        return data;
    }

    private void initDutyShift(List<String> dayByMonth, List<DutyPersonShiftDto> dutyShift, ArrayList<Object> list) {
        HashMap<String, String> dutyShiftMap = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        dutyShift.forEach(item -> dutyShiftMap.put(format.format(item.getDutyDate()), item.getShiftName()));

        for (int i = 0; i < dayByMonth.size(); i++) {
            if (dutyShiftMap.containsKey(dayByMonth.get(i))) {
                list.add(dutyShiftMap.get(dayByMonth.get(i)));
            } else {
                list.add(NOT_DUTY);
            }
        }
    }

    private List<List<Object>> initDutyPersonInfo(String beginDate, String endDate, List<String> dayByMonth) throws ParseException {
        // 查询已值班数据
        List<DutyPersonDto> contentList = iDutyPersonService.downloadList(beginDate, endDate);
        List<List<Object>> data = new ArrayList<>();
        // 组装导出数据
        if (!contentList.isEmpty()) {
            AtomicInteger row = new AtomicInteger(1);
            contentList.forEach(o -> {
                ArrayList<Object> list = new ArrayList<>();
                list.add(row.getAndIncrement());
                list.add(o.getUserId());
                list.add(o.getUserName());
                list.add(o.getDeptName());
                list.add(o.getPostTypeName());

                List<DutyPersonShiftDto> dutyShift = o.getDutyShift();
                initDutyShift(dayByMonth, dutyShift, list);

                data.add(list);
            });
        }
        return data;
    }
}
