package com.yeejoin.amos.boot.module.jcs.biz.controller;

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;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.ConvertUtils;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.feign.AmosFeignService;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.common.api.dto.CompanyPerson;
import com.yeejoin.amos.boot.module.common.api.dto.DutyCarDto;
import com.yeejoin.amos.boot.module.common.api.dto.DutyPersonDto;
import com.yeejoin.amos.boot.module.common.api.dto.DutyPersonShiftDto;
import com.yeejoin.amos.boot.module.common.api.dto.DutyShiftDto;
import com.yeejoin.amos.boot.module.common.api.dto.ExcelDto;
import com.yeejoin.amos.boot.module.common.api.dto.FireChemicalDto;
import com.yeejoin.amos.boot.module.common.api.dto.FireExpertsDto;
import com.yeejoin.amos.boot.module.common.api.dto.FireStationDto;
import com.yeejoin.amos.boot.module.common.api.dto.FireTeamDto;
import com.yeejoin.amos.boot.module.common.api.dto.FirefightersDto;
import com.yeejoin.amos.boot.module.common.api.dto.FirefightersExcelDto;
import com.yeejoin.amos.boot.module.common.api.dto.FirefightersInfoDto;
import com.yeejoin.amos.boot.module.common.api.dto.MaintenancePersonExcleDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrDto;
import com.yeejoin.amos.boot.module.common.api.dto.WaterResourceDto;
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.IMaintenanceCompanyService;
import com.yeejoin.amos.boot.module.common.biz.service.IDutyPersonService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DutyCarServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DutyCommonServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DutyPersonServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DutyPersonShiftServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DutyShiftServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DynamicFormColumnServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireChemicalServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireExpertsServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireStationServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.WaterResourceServiceImpl;
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 com.yeejoin.amos.boot.module.jcs.biz.service.impl.AircraftServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.DataSourcesImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.EquipmentServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.FireTeamServiceImpl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 导出导入
 *
 * @author system_generator
 * @date 2021-06-29
 */
@RestController
@Api(tags = "导出")
@RequestMapping(value = "/excel")
public class ExcelController extends BaseController {

    @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
    DutyCarServiceImpl dutyCarService;
    @Autowired
    AmosFeignService amosFeignService;
    @Autowired
    EquipmentServiceImpl equipmentService;
    @Autowired
    DutyShiftServiceImpl dutyShiftService;
    @Autowired
    DutyCommonServiceImpl dutyCommonServiceImpl;
    @Autowired
    DutyPersonServiceImpl dutyPersonService;
    @Autowired
    DutyPersonShiftServiceImpl dutyPersonShiftService;
    @Autowired
    OrgUsrServiceImpl orgUsrService;
    @Autowired
    IDutyPersonService iDutyPersonService;
    
    @Autowired
	IMaintenanceCompanyService maintenanceCompanyService;
    
    @Autowired
    DynamicFormColumnServiceImpl dynamicFormColumnService;
    
    @Autowired
	Sequence sequence;

    private static final String NOT_DUTY = "休班";
    private static final String PERSON = "PERSON";
    
    private static final String MAINTENANCE_PERSON = "maintenancePerson";


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "下载模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, ExcelDto excelDto) {
        try {
            String url = excelDto.getClassUrl();
            Class<?> clz = Class.forName(url);
            ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null, clz,
                    dataSourcesImpl, true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统异常！");
        }
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "导出公用类")
    @GetMapping("/export")
    public void getFireStationFile(HttpServletResponse response, ExcelDto excelDto) {
        try {
            switch (excelDto.getType()) {

                case ExcelEnums.WHP:
                    List<FireChemicalDto> data = fireChemicalServiceImpl.queryForFireChemicalList(false);
                    ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), data,
                            FireChemicalDto.class, dataSourcesImpl, false);
                    break;
                case ExcelEnums.XFZJ:
                    List<FireExpertsDto> fireExpertsDtoList = fireExpertsServiceImpl.queryForFireExpertsList(false);
                    ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                            fireExpertsDtoList, FireExpertsDto.class, dataSourcesImpl, false);
                    break;
                case ExcelEnums.SYXX:
                    List<WaterResourceDto> waterResourceDtoList = waterResourceServiceImpl.exportToExcel(true);
                    ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                            waterResourceDtoList, WaterResourceDto.class, dataSourcesImpl, false);
                    break;
                case ExcelEnums.HKQ:
                    List<AircraftDto> aircraftDtoList = aircraftServiceImpl.queryAircraftDtoForList(false);
                    ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                            aircraftDtoList, AircraftDto.class, dataSourcesImpl, false);
                    break;
                case ExcelEnums.XFDW:
                    List<FireTeamDto> fireTeamDtoList = fireTeamService.queryFireTeamForList(false);
                    ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), fireTeamDtoList,
                            FireTeamDto.class, dataSourcesImpl, false);
                    break;
                case ExcelEnums.WXXFZ:
                    List<FireStationDto> fireStationDtoList = fireStationService.queryForFireStationList(false);
                    ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                            fireStationDtoList, FireStationDto.class, null, false);
                    break;
                case ExcelEnums.XFRY:
                    List<FirefightersExcelDto> firefightersExcelDtoList = firefightersService.exportToExcel(false);
                    ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                            firefightersExcelDtoList, FirefightersExcelDto.class, null, false);
                    break;
                case ExcelEnums.WBRY:
                    List<MaintenancePersonExcleDto> maintenancePersonExcleDtoList = maintenanceCompanyService.exportToMaintenancePersonExcel();
                    ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
                    		maintenancePersonExcleDtoList, MaintenancePersonExcleDto.class, null, false);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统异常！");
        }
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "上传文件数据-")
    @PostMapping("/upload")
    public void template2(@RequestPart("file") MultipartFile multipartFile, ExcelDto excelDto) {
        try {
            switch (excelDto.getType()) {

                case ExcelEnums.WHP:
                    excelImportFireChemical(multipartFile);
                    break;
                case ExcelEnums.XFZJ:
                    excelImportFireExperts(multipartFile);
                    break;
                case ExcelEnums.SYXX:
                    excelImportWaterResource(multipartFile);
                    break;
                case ExcelEnums.HKQ:
                    excelImportAircraft(multipartFile);
                    break;
                case ExcelEnums.XFDW:
                    excelImportFireTeam(multipartFile);
                    break;
                case ExcelEnums.WXXFZ:
                    excelImportFireStation(multipartFile);
                    break;
                case ExcelEnums.XFRY:
                    excelImportFirefighters(multipartFile);
                    break;
                case ExcelEnums.CLZQ:
                    excelImportDutyPerson(multipartFile, ExcelEnums.CLZQ);
                    break;
                case ExcelEnums.RYZB:
                    excelImportDutyPerson(multipartFile, ExcelEnums.RYZB);
                case ExcelEnums.WBRY:
                    excelImportMaintenancePerson(multipartFile, ExcelEnums.WBRY);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统异常！");
        }
    }
    /**
     * @author chenhao 
     * @param multipartFile
     * @param wbry
     * @throws Exception 
     */
    private void excelImportMaintenancePerson(MultipartFile multipartFile, String wbry) 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.setCode(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 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.equals(dutyType)) {
                initDutyCarData(sheet, dataList, dayByMonth);
                dutyCarService.saveImportData(dataList);
            } else if (ExcelEnums.RYZB.equals(dutyType)) {
                initDutyPersonData(sheet, dataList, dayByMonth);
                dutyPersonService.saveImportData(dataList);
            }
        }
    }

    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 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 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);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "导出值班模板", notes = "导出值班模板")
    @GetMapping(value = "/duty_template")
    public void dutyCarTemplate(HttpServletResponse response, @RequestParam("beginDate") String beginDate,
                                @RequestParam("endDate") String endDate, ExcelDto excelDto,
                                @RequestParam("ids") String ids) {
        try {
            List<List<Object>> data = new ArrayList<>();
            if (ExcelEnums.CLZQ.equals(excelDto.getType())) {
                data = initDutyCarTemplate(ids);
            } else if (ExcelEnums.RYZB.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);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统异常！");
        }
    }

    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 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;
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "导出值班信息", notes = "导出值班模板")
    @GetMapping(value = "/duty_info")
    public void dutyCarDuty(HttpServletResponse response, @RequestParam("beginDate") String beginDate,
                            @RequestParam("endDate") String endDate, ExcelDto excelDto) {
        try {
            // 获取日期
            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.equals(excelDto.getType())) {
                data = initDutyCarInfo(beginDate, endDate, dayByMonth);
            } else if (ExcelEnums.RYZB.equals(excelDto.getType())) {
                data = initDutyPersonInfo(beginDate, endDate, dayByMonth);
            }

            exportDutyTemplate(response, excelDto.getClassUrl(), dayByMonth, excelDto, data, false);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统异常！");
        }
    }

    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;
    }

    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 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()]);
    }
}
