package com.testor.module.report.controller;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.word.WordExportUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.sys.dict.data.controller.SysDictDataController;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataListResponse;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataRequest;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.role.controller.SysRoleController;
import com.testor.biz.sys.role.model.domain.SysRole;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.common.constant.BelongUnitEnum;
import com.testor.common.core.utils.file.ImageUtils;
import com.testor.common.util.FileUtil;
import com.testor.common.util.excel.LocalDateTimeConverter;
import com.testor.ddd.safetyControl.application.service.spaceManage.SpaceManageService;
import com.testor.ddd.safetyControl.interfaces.model.vo.space.TSafeSpaceVO;
import com.testor.module.accident.model.req.AccidentReportExportReq;
import com.testor.module.accident.service.AccidentReportService;
import com.testor.module.duty.model.domain.TSysDutyLog;
import com.testor.module.duty.model.domain.TSysSelective;
import com.testor.module.duty.model.domain.TSysTaskWork;
import com.testor.module.duty.model.dto.TSysDutyLogParam;
import com.testor.module.duty.model.dto.TSysSelectiveExcelParam;
import com.testor.module.duty.model.dto.TSysSelectiveParam;
import com.testor.module.duty.service.TSysDutyLogService;
import com.testor.module.duty.service.TSysSelectiveService;
import com.testor.module.duty.service.TSysTaskWorkService;
import com.testor.module.duty.util.PoiExcelUtils;
import com.testor.module.news.model.dto.SysNewsParam;
import com.testor.module.partner.model.domain.TPartnerOrg;
import com.testor.module.partner.service.TPartnerOrgService;
import com.testor.module.report.dto.DutyDownload;
import com.testor.module.train.course.model.domain.TTrainCourse;
import com.testor.module.train.examinationManage.model.domain.TTrainExaminationManage;
import com.testor.module.train.examinationManage.model.dto.TTrainExaminationManageParam;
import com.testor.module.train.examinationManage.service.TTrainExaminationManageService;
import com.testor.module.train.project.dao.TTrainProjectDao;
import com.testor.module.train.project.model.dto.MyManagementExport;
import com.testor.module.train.project.model.dto.TTrainProjectParam;
import com.testor.module.train.project.model.dto.TTrainProjectParamImport;
import com.testor.module.train.project.service.TTrainProjectService;
import com.testor.module.video.controller.TVideoEquipmentInfoController;
import com.testor.module.video.model.domain.TVideoEquipmentInfo;
import com.testor.module.video.service.TVideoEquipmentInfoService;
import com.testor.module.video.util.Beans;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/report")
@Api(value = "report", tags = "报表统一下载接口")
public class PortController {
    private static final Logger logger = LoggerFactory.getLogger(PortController.class);

    @Autowired
    private SysOrgService sysOrgService;
    @Resource
    private HttpServletResponse response;

    @Autowired
    private TVideoEquipmentInfoService tVideoEquipmentInfoService;

    @Resource
    private HttpServletRequest request;
    @Value("${ureport.path}")
    private String path;
    @Autowired
    private TSysDutyLogService tSysDutyLogService;

    @Autowired
    private TSysTaskWorkService tSysTaskWorkService;

    @Autowired
    private TTrainProjectService tTrainProjectService;

    @Autowired
    private TTrainExaminationManageService tTrainExaminationManageService;

    @Autowired
    private AccidentReportService accidentReportService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired(required = false)
    private TTrainProjectDao tTrainProjectDao;

    @Autowired
    private TSysSelectiveService tSysSelectiveService;

    @PostMapping("/getExportExamProject")
    @ApiOperation(value = "考试计划导出", notes = "")
    public void getExportExamProject(@RequestBody TTrainExaminationManageParam param) {
        String companyids = param.getOrgId();
        String[] companyIds = null;
        companyIds = companyids.split(",");
        if (StringHelper.isEmpty(companyids)) {
            return;
        }
        List<Map<String, String>> mapList = new ArrayList<>();
        for (String companyId : companyIds) {
            TTrainExaminationManage manage = tTrainExaminationManageService.getById(companyId);
            Map<String, String> map = new HashMap<>();
            String userId = ContextUtils.getLoginUser().getUserId();
            String url = path + "/ureport/excel?_u=file:examProject.ureport.xml&id=" + companyId + "&userId=" + userId;
            SysOrg sysOrg = sysOrgService.getById(companyId);
            map.put("path", url);
            map.put("name", manage.getExamName() + ".xlsx");
            mapList.add(map);
        }
        FileUtil.zipUrlToFile(mapList, request, response);
    }

    @PostMapping("/getExportTrainProject")
    @ApiOperation(value = "培训计划导出", notes = "")
    public void getExportTrainProject(@RequestBody TTrainProjectParam param) {
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        String parentIds = sysOrg.getParentIds();
        String orgId = sysOrg.getOrgId();
        if (ObjectHelper.isNotEmpty(param.getVisitStartTime())) {
            //String startTime = param.getVisitStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String startTime =  com.testor.common.util.DateUtil.convertDateToStr( param.getVisitStartTime(),DatePattern.NORM_DATETIME_PATTERN);
            param.setStartTime(startTime);
        }
        if (ObjectHelper.isNotEmpty(param.getVisitEndTime())) {
           // String endTime = param.getVisitEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String endTime =  com.testor.common.util.DateUtil.convertDateToStr( param.getVisitEndTime(),DatePattern.NORM_DATETIME_PATTERN);

            param.setEndTime(endTime);
        }
        List<TTrainProjectParam> records = tTrainProjectDao.getAffiliation(param, parentIds, orgId);
        if (CollectionUtils.isEmpty(records) || records.size() == 0) {
            return;
        }
        List<String> collect = records.stream().map(TTrainProjectParam::getId).collect(Collectors.toList());

        BaseResponse<TTrainProjectParam> byIds = null;
        List<TTrainProjectParamImport> list = new ArrayList<>();
        //参数组装
        for (String s : collect) {
            try {
                byIds = tTrainProjectService.getByIds(s);
                TTrainProjectParam data = byIds.getData();
                TTrainProjectParamImport tTrainProjectParamImport = Beans.objectToBean(data, TTrainProjectParamImport.class);
                tTrainProjectParamImport.setExamTime(com.testor.common.util.DateUtil.convertDateToStr(data.getExamStartTime(),DatePattern.NORM_DATETIME_PATTERN)
                        + "到" + com.testor.common.util.DateUtil.convertDateToStr(data.getExamEndTime(),DatePattern.NORM_DATETIME_PATTERN)    );

                tTrainProjectParamImport.setVisitTime(
                        com.testor.common.util.DateUtil.convertDateToStr(data.getVisitStartTime(),DatePattern.NORM_DATETIME_PATTERN)
                        + "到" + com.testor.common.util.DateUtil.convertDateToStr(data.getVisitEndTime(),DatePattern.NORM_DATETIME_PATTERN));
                tTrainProjectParamImport.setIsAddExam(Objects.equals(tTrainProjectParamImport.getIsAddExam(), "1") ? "是" : "否");
                tTrainProjectParamImport.setVisitWay(CAN.getName(tTrainProjectParamImport.getVisitWay()));
                tTrainProjectParamImport.setCompany(data.getOrgName());
                if (data.getMyManagements().size() > 0) {
                    List<MyManagementExport> myManagementExports = Beans.listToBean(data.getMyManagements(), MyManagementExport.class);
                    for (MyManagementExport myManagementExport : myManagementExports) {
                        myManagementExport.setPersonAffiliation(BelongUnitEnum.getName(myManagementExport.getPersonAffiliation()));
                        myManagementExport.setCurrentStatus(GETTYPE.getName(myManagementExport.getCurrentStatus()));
                        myManagementExport.setSex(Boolean.getBoolean(myManagementExport.getSex()) ? "女" : "男");
                    }
                    tTrainProjectParamImport.setMyManagements(myManagementExports);
                }
                //获取课程名称
                if (data.getTrainCourses() != null && data.getTrainCourses().size() > 0) {
                    String s1 = "";
                    for (TTrainCourse trainCours : data.getTrainCourses()) {
                        s1 = s1 + trainCours.getCourseName();
                    }
                    tTrainProjectParamImport.setTrainCoursess(s1);
                }
                tTrainProjectParamImport.setVisitType(CAN_TYPE.getName(tTrainProjectParamImport.getVisitType()));
                tTrainProjectParamImport.setExamType(CAN.getName(tTrainProjectParamImport.getExamType()));
                tTrainProjectParamImport.setTrainType(TRAIN_TYPE.getName(tTrainProjectParamImport.getTrainType()));
                list.add(tTrainProjectParamImport);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        for (TTrainProjectParamImport tTrainProjectParamImport : list) {

        }
        try (OutputStream out = response.getOutputStream()) {
//            // 设置响应输出的头类型
//            response.setHeader("content-Type", "application/vnd.ms-excel");
//            // 设置下载的Excel名称，以当前时间为文件后缀，DateUtil为Hutool工具包里的工具类
//
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setCharacterEncoding("utf-8");
//             // String fileName = URLEncoder.encode("教育培训计划", "UTF-8").replaceAll("\\+", "%20");
//             //response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
//
//            String fileName = "教育培训计划.xlsx";
//            String fileNameURL = URLEncoder.encode(fileName, "UTF-8");
//            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileNameURL);

            String fileName = "教育培训计划";
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");



            Map<String, Object> map = new HashMap<>();
            ExportParams exportParams = new ExportParams();
            // 设置sheet得名称
            exportParams.setSheetName("培训计划");
            // title的参数为ExportParams类型，目前仅仅在ExportParams中设置了sheetName
            map.put("title", exportParams);
            // 模版导出对应得实体类型，即包含了List的对象
            map.put("entity", TTrainProjectParamImport.class);
            // sheet中要填充得数据
            map.put("data", list);

            List<Map<String, Object>> sheetsList = new ArrayList<>();
            sheetsList.add(map);
            //创建excel文件的方法
            Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
            //通过response输出流直接输入给客户端
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            out.flush();
        } catch (Exception e) {
            System.out.println("导出失败");
        }


    }

    @ApiOperation(value = "新闻统计下载", notes = "")
    @GetMapping("/getExcel")
    public void getExcels(SysNewsParam param, String startTime, String endTime, String levels) throws IOException {
        String loginUserId = ContextUtils.getLoginUserId();
        List<Map<String, String>> mapList = new ArrayList<>();
        String url = path + "/ureport/excel?_u=file:news.ureport.xml&title=" + param.getTitle() + "&startTime=" + startTime + "&endTime=" + endTime + "&levels=" + levels + "&isRead=" + param.getIsRead() + "&loginUserId=" + loginUserId;
        String url1 = path + "/ureport/excel?_u=file:11newsCount.ureport.xml&title=" + param.getTitle() + "&startTime=" + startTime + "&endTime=" + endTime + "&levels=" + levels + "&isRead=" + param.getIsRead() + "&loginUserId=" + loginUserId;
        Map<String, String> map = new HashMap<>();
        Map<String, String> map1 = new HashMap<>();
        map.put("path", url);
        map.put("name", "新闻信息汇总");
        mapList.add(map);
        map1.put("path", url1);
        map1.put("name", "新闻统计汇总");
        mapList.add(map1);
        String name = "新闻统计下载.xlsx";
        FileUtil.ExcelUrlToFile(mapList, request, response, name);
    }

    @ApiOperation(value = "事故统计下载", notes = "")
    @GetMapping("/getAccident")
    public void getAccident(AccidentReportExportReq accidentReportExportReq) throws Exception {
        String url = path + "/ureport/excel?_u=file:revisionAccident.ureport.xml";
        //事故等级
        if (ObjectHelper.isNotEmpty(accidentReportExportReq) && StringHelper.isNotEmpty(accidentReportExportReq.getAccidentLevel())) {
            url = url + "&accidentLevel=" + accidentReportExportReq.getAccidentLevel();
        }
        //
        if (ObjectHelper.isNotEmpty(accidentReportExportReq) && StringHelper.isNotEmpty(accidentReportExportReq.getIdList())) {
            url = url + "&ids=" + accidentReportExportReq.getIdList().stream().collect(Collectors.joining(","));
        }
//        if (ObjectHelper.isNotEmpty(accidentReportExportReq) && StringHelper.isNotEmpty(accidentReportExportReq.getLimit())) {
//            url = url+"&limit=" + accidentReportExportReq.getLimit();
//        }
//        if (ObjectHelper.isNotEmpty(accidentReportExportReq) && StringHelper.isNotEmpty(accidentReportExportReq.getPage())) {
//            url = url+"&page=" + accidentReportExportReq.getPage();
//        }
//        if (ObjectHelper.isNotEmpty(accidentReportExportReq) && StringHelper.isNotEmpty(accidentReportExportReq.getOrderBy())) {
//            url = url+"&orderBy=" + accidentReportExportReq.getOrderBy();
//        }
//        if (ObjectHelper.isNotEmpty(accidentReportExportReq) && StringHelper.isNotEmpty(accidentReportExportReq.getOrderType())) {
//            url = url+"&orderType=" + accidentReportExportReq.getOrderType();
//        }
        //区域公司id
        if (ObjectHelper.isNotEmpty(accidentReportExportReq) && StringHelper.isNotEmpty(accidentReportExportReq.getRegionalCompanyId())) {
            url = url + "&regionalCompanyId=" + accidentReportExportReq.getRegionalCompanyId();
        }
        //基层单位id
        if (ObjectHelper.isNotEmpty(accidentReportExportReq) && StringHelper.isNotEmpty(accidentReportExportReq.getBasicUnitId())) {
            url = url + "&basicUnitId=" + accidentReportExportReq.getBasicUnitId();
        }
        //流程状态
        if (ObjectHelper.isNotEmpty(accidentReportExportReq) && StringHelper.isNotEmpty(accidentReportExportReq.getProcessStatus())) {
            url = url + "&processStatus=" + accidentReportExportReq.getProcessStatus();
        }
        //事故开始时间
        if (accidentReportExportReq.getAccidentStartTime() != null) {
            url = url + "&accidentStartTime=" + DateUtils.format(accidentReportExportReq.getAccidentStartTime(), null);
        }
        //事故结束时间
        if (accidentReportExportReq.getAccidentEndTime() != null) {
            url = url + "&accidentEndTime=" + DateUtils.format(accidentReportExportReq.getAccidentEndTime(), null);
        }
        String fileName = "小事故信息月度统计报表.xlsx";
//        FileUtil.downloadHttpFile(url, request, response, fileName);

        accidentReportService.exports(response, request, accidentReportExportReq);
    }

    @ApiOperation(value = "本单位值班记录下载", notes = "")
    @PostMapping("/getDutyRecord")
    public void getDutyRecord(@RequestBody DutyDownload dutyDownload) {
        UserInfo loginUser = ContextUtils.getLoginUser();
        String companyids = dutyDownload.getCompanyids();
        String startDate = dutyDownload.getStartDate();
        String endDate = dutyDownload.getEndDate();
        SysOrg sysOrg1 = sysOrgService.getById(loginUser.getOrgId());
        String orgId = sysOrg1.getOrgId();
        String[] companyIds = null;
        if (companyids.equals("")) {
            companyIds = orgId.split(",");
        } else {
            companyIds = companyids.split(",");
        }
        LocalDate date = LocalDate.now();
        LocalDate firstDay = date.with(TemporalAdjusters.firstDayOfMonth()); // 获取当前月的第一天
        LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth()); // 获取当前月的最后一天
        //日期格式化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月");
        String format = firstDay.format(formatter);
        if (startDate.equals("")) {
            startDate = firstDay.toString();
        }
        if (endDate.equals("")) {
            endDate = lastDay.toString();
        }
        List<Map<String, String>> mapList = new ArrayList<>();
        for (String companyId : companyIds) {
            Map<String, String> map = new HashMap<>();
            String url = path + "/ureport/excel?_u=file:dutyBean.ureport.xml&companyids=" + companyId + "&startDate=" + startDate + "&endDate=" + endDate;
            SysOrg sysOrg = sysOrgService.getById(companyId);
            map.put("path", url);
            map.put("name", sysOrg.getOrgName() + format + "值班记录.xlsx");
            mapList.add(map);
        }
        FileUtil.zipUrlToFile(mapList, request, response);
    }

    @PostMapping("/getExportSpot")
    @ApiOperation(value = "导出值班抽查记录", notes = "")
    public void getExportSpot(@RequestBody TSysSelectiveParam param) {
        String startDate = param.getStartDate();
        String endDate = param.getEndDate();
        String companyids = param.getCompanyId();
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg1 = sysOrgService.getById(loginUser.getOrgId());
        String orgId = sysOrg1.getOrgId();
        String[] companyIds = null;
        if (StringUtils.isBlank(companyids)) {
            companyIds = orgId.split(",");
        } else {
            companyIds = companyids.split(",");
        }
        LocalDate date = LocalDate.now();
        LocalDate firstDay = date.with(TemporalAdjusters.firstDayOfMonth()); // 获取当前月的第一天
        LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth()); // 获取当前月的最后一天
        //日期格式化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月");
        String format = firstDay.format(formatter);
        if (StringUtils.isBlank(startDate)) {
            startDate = firstDay.toString();
        }
        if (StringUtils.isBlank(endDate)) {
            endDate = lastDay.toString();
        }
        /*List<Map<String, String>> mapList = new ArrayList<>();
        for (String companyId : companyIds) {
            Map<String, String> map = new HashMap<>();
            String url = path + "/ureport/excel?_u=file:TSysselectiveBean.ureport.xml&companyId=" +
                    companyId + "&startDate=" + startDate +
                    "&endDate=" + endDate + "&isIssue=" + param.getIsIssue();
            SysOrg sysOrg = sysOrgService.getById(companyId);
            map.put("path", url);
            map.put("name", sysOrg.getOrgName() + format + "值班抽查表.xlsx");
            mapList.add(map);
        }
        FileUtil.zipUrlToFile(mapList, request, response);*/

        ServletOutputStream out = null;
        ZipArchiveOutputStream zous = null;
        ByteArrayOutputStream arrayOutputStream = null;
        InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/zbcc.xlsx");
        ByteArrayOutputStream bos = FileUtil.cloneInputStream(templatePathName);
        try {
            String outputFileName = "文件" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
            response.reset();
            response.setHeader("Content-Type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(outputFileName, "UTF-8"));
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            out = response.getOutputStream();
            zous = new ZipArchiveOutputStream(out);
            zous.setUseZip64(Zip64Mode.AsNeeded);

            for (String companyId : companyIds) {
                TSysSelectiveParam query = new TSysSelectiveParam();
                BeanUtil.copyProperties(param,query);
                query.setCompanyId(companyId);
                query.setStartDate(startDate);
                query.setEndDate(endDate);
                QueryWrapper<TSysSelective> queryWrapper = this.createQuery(param);

                List<TSysSelective> list = tSysSelectiveService.list(queryWrapper);
                List<TSysSelectiveExcelParam> excelParamList = new ArrayList<>();
                for(TSysSelective selective : list){
                    TSysSelectiveExcelParam data = new TSysSelectiveExcelParam();
                    Date checkTime  = selective.getCheckTime();
                    String year = String.valueOf(DateUtil.year(checkTime));
                    String month = String.valueOf(DateUtil.month(checkTime) + 1);
                    String day = String.valueOf(DateUtil.dayOfMonth(checkTime));
                    String week = DateUtil.dayOfWeekEnum(checkTime).toChinese();
                    String time = DateUtil.format(com.testor.common.util.DateUtil.dateToLocalDateTime(selective.getCheckTime()),DatePattern.NORM_TIME_PATTERN);
                    data.setYear(year);
                    data.setMonth(month);
                    data.setDay(day);
                    data.setWeek(week);
                    data.setTime(time);

                    data.setCompanyName(selective.getCompanyName());
                    data.setUnitBelong(selective.getUnitBelong());
                    data.setSelectivePerson(selective.getSelectivePerson());
                    data.setPattern(selective.getPattern());
                    data.setDutyOperator(selective.getDutyOperator());
                    data.setWorkCase(selective.getWorkCase());
                    String checkPersonPhotoUrl = selective.getCheckPersonPhoto();
                    byte[] checkPersonPhoto = null;
                    if(StringUtils.isNotBlank(checkPersonPhotoUrl)){
                        checkPersonPhoto = ImageUtils.readFile(checkPersonPhotoUrl);
                    }
                    data.setCheckPersonPhoto(checkPersonPhoto);
                    data.setExistIssue(selective.getExistIssue());
                    String issuePhotoUrl = selective.getIssuePhoto();
                    byte[] issuePhoto = null;
                    if(StringUtils.isNotBlank(issuePhotoUrl)){
                        issuePhoto = ImageUtils.readFile(issuePhotoUrl);
                    }
                    data.setIssuePhoto(issuePhoto);
                    data.setRemarks(selective.getRemarks());
                    excelParamList.add(data);
                }
                SysOrg sysOrg = sysOrgService.getById(companyId);
                String excelName = StringHelper.format("{}{}值班抽查表.xlsx",sysOrg.getOrgName(), format);
                InputStream copyInputStream = new ByteArrayInputStream(bos.toByteArray());
                arrayOutputStream = new ByteArrayOutputStream();
                ExcelWriter excelWriter = EasyExcel.write(arrayOutputStream).withTemplate(copyInputStream).excelType(ExcelTypeEnum.XLSX).build();
                ArchiveEntry entry = new ZipArchiveEntry(excelName);
                zous.putArchiveEntry(entry);

                WriteSheet writeSheet = EasyExcel.writerSheet().build();
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
                excelWriter.fill(excelParamList, fillConfig, writeSheet);
                excelWriter.finish();

                arrayOutputStream.writeTo(zous);
                arrayOutputStream.flush();
                arrayOutputStream.close();
                zous.closeArchiveEntry();
                copyInputStream.close();
            }
            zous.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (null != arrayOutputStream) {
                try {
                    arrayOutputStream.flush();
                    arrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error(e.getMessage(),e);
                }
            }
            if (null != zous) {
                try {
                    zous.flush();
                    zous.finish();
                    zous.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error(e.getMessage(),e);
                }
            }
        }


    }

    //    @PostMapping("/getDowDutyLog")
//    @ApiOperation(value = "本单位批量下载值班日志", notes = "")
    public void getDownloadDutyLog(@RequestBody TSysDutyLogParam param) {
        String logId = param.getId();
        if (!("".equals(logId))) {
            String url = path + "/ureport/word?_u=file:taskworklog.ureport.xml&id=" + param.getId();
            String fileName = "值班日志.docx";
            FileUtil.downloadHttpFile(url, request, response, fileName);
        } else {
            UserInfo loginUser = ContextUtils.getLoginUser();
            SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
            QueryWrapper<TSysDutyLog> wrapper = new QueryWrapper<>();
            String startDate = param.getStartDate();
            String endDate = param.getEndDate();
            String companyId = param.getCompanyId();
            String processStatus = param.getProcessStatus();
            if (!("".equals(startDate)) && !("".equals(endDate))) {
                wrapper.between("duty_date", startDate + " 00:00:00", endDate + " 23:59:59");
            }
            if (!("".equals(companyId))) {
                wrapper.eq("company_id", companyId);
            } else {
                wrapper.eq("company_id", sysOrg.getOrgId());
            }
            if (!("".equals(processStatus))) {
                wrapper.eq("process_status", processStatus);
            }
            List<TSysDutyLog> list = tSysDutyLogService.list(wrapper);
            // 需要下载的日志的id
            List<String> listId = list.stream().map(TSysDutyLog::getId).collect(Collectors.toList());

            List<Map<String, String>> mapList = new ArrayList<>();
            Integer i = 1;
            for (String id : listId) {
                i++;
                Map<String, String> map = new HashMap<>();
                String url = path + "/ureport/word?_u=file:dutylogdow.ureport.xml&id=" + id;
                map.put("path", url);
                map.put("name", Integer.toString(i));
                mapList.add(map);
            }
            FileUtil.zipUrlToFile(mapList, request, response);
        }
    }

    @Autowired
    private TPartnerOrgService tPartnerOrgService;

    @Autowired
    private SysRoleController sysRoleController;


    @SneakyThrows
    @GetMapping("/DowDutyModel")
    @ApiOperation(value = "值班表信息批量导出模版(本单位)", notes = "")
    public void getDowDutyModel() throws IOException, BusinessException {
        UserInfo loginUser = ContextUtils.getLoginUser();
        String orgId = loginUser.getOrgId();
        List<Map<String, String>> mapList = new ArrayList<>();
        //获取当前登录的公司
        List<SysOrg> orgList = new ArrayList<>();
        SysOrg sysOrg = sysOrgService.getById(orgId);
        orgList.add(sysOrg);
        //获取当前公司人员
        List<SysUser> sysUsers = sysUserService.list(new QueryWrapper<SysUser>().eq("status", "0").eq("org_id", orgId));
        for (SysUser sysUser : sysUsers) {
            if (StringUtils.isNotBlank(sysUser.getDeptId())) {
                SysOrg dept = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq("org_id", sysUser.getDeptId()).eq("is_dept", "1").eq("status", "0"));
                if (dept != null) {
                    sysUser.setDeptId(dept.getOrgName());
                }
            }
        }
        String fileName = URLEncoder.encode("值班表信息批量导出模版(本单位)", "utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-download;charset=utf-8");
        response.setHeader("Content-disposition", URLEncoder.encode(fileName, "UTF-8"));
        //mime类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
        response.setHeader("Pragma", "No-cache");
        InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/zbdrmb.xlsx");
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templatePathName).build();
        WriteSheet writeSheet2 = EasyExcel.writerSheet(2).build();
        excelWriter.fill(orgList, fillConfig, writeSheet2);
        WriteSheet writeSheet4 = EasyExcel.writerSheet(4).build();
        excelWriter.fill(sysUsers, fillConfig, writeSheet4);
        excelWriter.finish();
    }




    /*@SneakyThrows
    @GetMapping("/DowDutyModel")
    @ApiOperation(value = "值班表信息批量导出模版(本单位)", notes = "")
    public void getDowDutyModel() throws IOException, BusinessException {
        UserInfo loginUser = ContextUtils.getLoginUser();
        String orgId = loginUser.getOrgId();
        List<Map<String, String>> mapList = new ArrayList<>();
        //参考文件企业信息
        String url2 = path + "/ureport/excel?_u=file:dowReferenceModel.ureport.xml&orgId=" + orgId;
        //参考文件-值班模式
        String url3 = path + "/ureport/excel?_u=file:dowDutyModel.ureport.xml";
//       //参考模式值班人员
        String url4 = path + "/ureport/excel?_u=file:dowDutyPersonModel.ureport.xml&orgId=" + orgId;
        //合并后的文件名称
        String fileName = "值班表信息批量导出模版(本单位).xlsx";
        InputStream orgMessage = FileUtil.getInputStreamFromUrl(url2);
        InputStream dutyMode = FileUtil.getInputStreamFromUrl(url3);
        InputStream watchkeeper = FileUtil.getInputStreamFromUrl(url4);
        InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/zbdrmb.xlsx");
        // 创建一个新的 Workbook 对象
        Workbook workbook = WorkbookFactory.create(templatePathName);

        // 创建新的 Sheet 页面并复制内容
        Sheet sheet1 = workbook.createSheet("参考文件-企业信息");
        copySheet(orgMessage, workbook, sheet1);

        Sheet sheet2 = workbook.createSheet("参考文件-值班模式");
        copySheet(dutyMode, workbook, sheet2);
        Sheet sheet3 = workbook.createSheet("参考文件-值班人员");
        copySheet(watchkeeper, workbook, sheet3);

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", URLEncoder.encode(fileName, "UTF-8"));
        //mime类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
        response.setHeader("Pragma", "No-cache");
        // 下载文件
        workbook.write(response.getOutputStream());
        workbook.close();
    }*/

    @SneakyThrows
    private void copySheet(InputStream inputStream, Workbook workbook, Sheet sheet) throws IOException {
        // 读取输入流中的内容到临时 Workbook 对象
        Workbook tempWorkbook = WorkbookFactory.create(inputStream);
        // 获取临时 Workbook 的第一个 Sheet
        Sheet tempSheet = tempWorkbook.getSheetAt(0);

        // 循环复制每一行到目标 Sheet
        for (Row tempRow : tempSheet) {
            Row newRow = sheet.createRow(tempRow.getRowNum());
            // 复制每个单元格的内容
            for (Cell tempCell : tempRow) {
                Cell newCell = newRow.createCell(tempCell.getColumnIndex(), tempCell.getCellType());
                newCell.setCellValue(tempCell.getStringCellValue());
            }
        }
    }

    //    @PostMapping("/getDowDutyLog")
//    @ApiOperation(value = "本单位批量下载值班日志", notes = "单个下载传 id   批量导出传 companyIds")
    public void getDownloadDutyLogs(@RequestBody TSysDutyLogParam param) throws Exception {
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        List<String> companyIds = param.getCompanyIds();
        QueryWrapper<TSysDutyLog> queryWrapper = new QueryWrapper<>();
        String dutyOrgId = param.getId();
        //模板位置
        String modelPath = PortController.class.getResource("/word").getPath() + File.separator + "dowdutylog.docx";
        if (!"".equals(dutyOrgId)) {
            queryWrapper.eq(TSysDutyLog.ID, dutyOrgId);
            TSysDutyLog one = tSysDutyLogService.getOne(queryWrapper);
            Map<String, Object> oneMap = objectToMap(one);
            //作业活动
            String jobId = one.getJobId();
            String[] split = jobId.split(",");
            QueryWrapper<TSysTaskWork> wrapper = new QueryWrapper<>();
            wrapper.in(TSysTaskWork.ID, split);
            List<TSysTaskWork> tSysTaskWorks = tSysTaskWorkService.list(wrapper);
            for (TSysTaskWork tSysTaskWork : tSysTaskWorks) {
                oneMap.put("activeCategory", tSysTaskWork.getActiveCategory());
                oneMap.put("isInvolve", tSysTaskWork.getIsInvolve());
                oneMap.put("involvePerson", tSysTaskWork.getInvolvePerson());
                oneMap.put("sceneGuardian", tSysTaskWork.getSceneGuardian());
                oneMap.put("isTaskApproval", tSysTaskWork.getIsTaskApproval());
                oneMap.put("isTaskAnalysis", tSysTaskWork.getIsTaskAnalysis());
                oneMap.put("isSkillTell", tSysTaskWork.getIsSkillTell());
                oneMap.put("isControlTask", tSysTaskWork.getIsControlTask());
                oneMap.put("controlReason", tSysTaskWork.getControlReason());
                oneMap.put("isElementChange", tSysTaskWork.getIsElementChange());
                oneMap.put("changeMeasure", tSysTaskWork.getChangeMeasure());
            }

            //作业活动
            String onefileName = one.getCompanyName() + one.getDutyDate() + one.getSubmitter() + "值班工作日志.docx";
            //导出领导签字
            ImageEntity img = new ImageEntity();
            img.setWidth(100);
            img.setHeight(100);
            img.setUrl(one.getHandoverSign());
            img.setType(ImageEntity.URL);
            oneMap.put("img", img);
            exportWord(modelPath, oneMap, onefileName);
        } else {
            if (companyIds != null) {
                queryWrapper.in(TSysDutyLog.COMPANY_ID, companyIds);
            } else {
                String orgId = loginUser.getOrgId();
                queryWrapper.eq(TSysDutyLog.COMPANY_ID, orgId);
            }
            List<TSysDutyLog> list = tSysDutyLogService.list(queryWrapper);

            try {
                String outputFileName = "文件" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
                response.reset();
                response.setHeader("Content-Type", "application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(outputFileName, "UTF-8"));
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                ZipArchiveOutputStream zos = new ZipArchiveOutputStream(response.getOutputStream());//压缩文件输出流
                zos.setUseZip64(Zip64Mode.AsNeeded);
                for (TSysDutyLog tSysDutyLog : list) {
                    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                    Map<String, Object> tSysDutyLogMap = objectToMap(tSysDutyLog);
                    //导出文件名称
                    String fileName = tSysDutyLog.getCompanyName() + tSysDutyLog.getDutyDate() + tSysDutyLog.getSubmitter() + "值班工作日志.docx";
                    // 导出模板
                    //作业活动
                    String jobId = tSysDutyLog.getJobId();
                    String[] split = jobId.split(",");
                    QueryWrapper<TSysTaskWork> wrapper = new QueryWrapper<>();
                    wrapper.in(TSysTaskWork.ID, split);
                    List<TSysTaskWork> tSysTaskWorks = tSysTaskWorkService.list(wrapper);
                    for (TSysTaskWork tSysTaskWork : tSysTaskWorks) {
                        tSysDutyLogMap.put("activeCategory", tSysTaskWork.getActiveCategory());
                        tSysDutyLogMap.put("isInvolve", tSysTaskWork.getIsInvolve());
                        tSysDutyLogMap.put("involvePerson", tSysTaskWork.getInvolvePerson());
                        tSysDutyLogMap.put("sceneGuardian", tSysTaskWork.getSceneGuardian());
                        tSysDutyLogMap.put("isTaskApproval", tSysTaskWork.getIsTaskApproval());
                        tSysDutyLogMap.put("isTaskAnalysis", tSysTaskWork.getIsTaskAnalysis());
                        tSysDutyLogMap.put("isSkillTell", tSysTaskWork.getIsSkillTell());
                        tSysDutyLogMap.put("isControlTask", tSysTaskWork.getIsControlTask());
                        tSysDutyLogMap.put("controlReason", tSysTaskWork.getControlReason());
                        tSysDutyLogMap.put("isElementChange", tSysTaskWork.getIsElementChange());
                        tSysDutyLogMap.put("changeMeasure", tSysTaskWork.getChangeMeasure());
                    }

                    //作业活动
                    XWPFDocument xwpfDocument = WordExportUtil.exportWord07(modelPath, tSysDutyLogMap);
                    xwpfDocument.write(arrayOutputStream);//把word对象内容写到ByteArray流临时存储
                    ArchiveEntry entry = new ZipArchiveEntry(fileName);
                    zos.putArchiveEntry(entry);
                    zos.write(arrayOutputStream.toByteArray());
                    zos.closeArchiveEntry();
                    arrayOutputStream.close();
                }
                zos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @SneakyThrows
    @GetMapping("/DowAptituteModel")
    @ApiOperation(value = "相关方人员资质信息批量导入模板下载", notes = "")
    public void getDowAptituteModel() {
        String orgId = ContextUtils.getLoginUser().getOrgId();
        //获取当前登录的子公司
        List<SysOrg> childrenById = sysOrgService.getChildrenById(orgId);
        //相关方机构
        List<TPartnerOrg> parentList = tPartnerOrgService.list(new QueryWrapper<TPartnerOrg>().eq("status", "0").eq("org_id", orgId));
        //当前登录公司的角色
        List<SysRole> sysRoles = sysRoleController.getOrgRole().getData();
        for (SysRole sysRole : sysRoles) {
            BigDecimal treeLevel = sysRole.getTreeLevel();
            if (treeLevel.compareTo(BigDecimal.ONE) == 0) {
                sysRole.setRoleId("总公司");
            }
            if (treeLevel.compareTo(BigDecimal.valueOf(2)) == 0) {
                sysRole.setRoleId("区域分公司");
            }
            if (treeLevel.compareTo(BigDecimal.valueOf(3)) == 0) {
                sysRole.setRoleId("粮库");
            }
        }
        try {
            String fileName = URLEncoder.encode("相关方人员资质信息批量导入模板", "utf-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download;charset=utf-8");
            response.setHeader("Content-disposition", URLEncoder.encode(fileName, "UTF-8"));
            //mime类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
            response.setHeader("Pragma", "No-cache");
            InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/xgfzz.xlsx");
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templatePathName).build();
            WriteSheet writeSheet2 = EasyExcel.writerSheet(2).build();
            excelWriter.fill(childrenById, fillConfig, writeSheet2);
            WriteSheet writeSheet3 = EasyExcel.writerSheet(3).build();
            excelWriter.fill(parentList, fillConfig, writeSheet3);
            WriteSheet writeSheet4 = EasyExcel.writerSheet(4).build();
            excelWriter.fill(sysRoles, fillConfig, writeSheet4);
            excelWriter.finish();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private SysDictDataController sysDictDataController;


    @SneakyThrows
    @GetMapping("/dowPersonnelQualification")
    @ApiOperation(value = "人员资质信息批量导入模板下载", notes = "")
    public void dowPersonnelQualification(HttpServletResponse response) {
        String orgId = ContextUtils.getLoginUser().getOrgId();
        //获取当前登录的公司
        List<SysOrg> orgList = new ArrayList<>();
        SysOrg sysOrg = sysOrgService.getById(orgId);
        orgList.add(sysOrg);
        //获取当前公司人员
        List<SysUser> sysUsers = sysUserService.list(new QueryWrapper<SysUser>().eq("status", "0").eq("org_id", orgId));
        for (SysUser sysUser : sysUsers) {
            if (StringUtils.isNotBlank(sysUser.getDeptId())) {
                SysOrg dept = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq("org_id", sysUser.getDeptId()).eq("is_dept", "1").eq("status", "0"));
                if (dept != null) {
                    sysUser.setDeptId(dept.getOrgName());
                }
            }
        }
        //获取资质类型
        SysDictDataRequest sysDictDataRequest = new SysDictDataRequest();
        sysDictDataRequest.setDictType("aptitude_type");
        List<SysDictDataListResponse> type = sysDictDataController.listDataByType(sysDictDataRequest).getData().getData();

        String fileName = URLEncoder.encode("人员资质信息批量导入模板", "utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-download;charset=utf-8");
        response.setHeader("Content-disposition", URLEncoder.encode(fileName, "UTF-8"));
        //mime类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
        response.setHeader("Pragma", "No-cache");
        InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/ryzzxxmb.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templatePathName).registerConverter(new LocalDateTimeConverter()).build();
        WriteSheet writeSheet2 = EasyExcel.writerSheet(2).build();
        excelWriter.fill(orgList, writeSheet2);
        WriteSheet writeSheet3 = EasyExcel.writerSheet(3).build();
        excelWriter.fill(sysUsers, writeSheet3);
        WriteSheet writeSheet4 = EasyExcel.writerSheet(4).build();
        excelWriter.fill(type, writeSheet4);
        excelWriter.finish();
    }

    /**
     * 对象转map
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }

    /**
     * @param modelPath 模板存放路径
     * @param map       渲染模板的map集合
     * @param fileName  导出的文件名称
     * @throws Exception
     */

    private void exportWord(String modelPath, Map<String, Object> map, String fileName) throws Exception {
        XWPFDocument xwpfDocument = WordExportUtil.exportWord07(modelPath, map);
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        ServletOutputStream outputStream = response.getOutputStream();
        xwpfDocument.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }


    @GetMapping("/videoEquipment")
    @ApiOperation(value = "视频监控模板导出", notes = "")
    public void videoEquipment() {
        UserInfo loginUser = ContextUtils.getLoginUser();
        String orgId = loginUser.getOrgId();
        List<Map<String, String>> mapList = new ArrayList<>();
        //视频监控设备信息
        String url = path + "/ureport/excel?_u=file:videoEquipment.ureport.xml";
        //参考说明
        String url1 = path + "/ureport/excel?_u=file:videoExplainModel.ureport.xml";
        //参照文件-企业信息
        String url2 = path + "/ureport/excel?_u=file:videoReferenceModel.ureport.xml&orgId=" + orgId;
        //参照文件-作业区域统计
        String url3 = path + "/ureport/excel?_u=file:videoJobAccount.ureport.xml&orgId=" + orgId;
        Map<String, String> map = new HashMap<>();
        Map<String, String> map1 = new HashMap<>();
        Map<String, String> map2 = new HashMap<>();
        Map<String, String> map3 = new HashMap<>();
        map.put("path", url);
        //sheet页名称
        map.put("name", "视频监控设备信息");
        mapList.add(map);
        map1.put("path", url1);
        map1.put("name", "参考说明");
        mapList.add(map1);
        map2.put("path", url2);
        map2.put("name", "参照文件-企业信息");
        mapList.add(map2);
        map3.put("path", url3);
        map3.put("name", "参照文件-作业区域统计");
        mapList.add(map3);
        //合并后的文件名称
        String name = "视频监控设备量导入模板.xlsx";
//        FileUtil.ExcelUrlToFile(mapList, request, response, name);
        tVideoEquipmentInfoService.getTemplate(request, response, orgId);

    }

    @Autowired
    private TVideoEquipmentInfoController tVideoEquipmentInfoController;
    @Autowired
    private SpaceManageService spaceManageService;


    @PostMapping("/importvideoEquipment")
    @ApiOperation(value = "视频监控批量导入", notes = "")
    public BaseResponse<String> imports(@RequestParam("file") MultipartFile file) throws Exception {
        BaseResponse<String> response = new BaseResponse<>();
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("当前登录人部门信息不存在，请联系管理员！");
        }
        Workbook workbook = null;
        InputStream inputStream = null;
        inputStream = file.getInputStream();
        // 读取Excel⽂件⼯作表
        workbook = PoiExcelUtils.readFile(inputStream, file.getOriginalFilename());
        //取得第⼀个⼯作表
        Sheet sheet = workbook.getSheetAt(0);
        //报表上传的每条数据
        List<Map<Integer, Object>> list = PoiExcelUtils.getBody(sheet, 7, 2);
        // 上传的每条数据
        List<TVideoEquipmentInfo> infos = new ArrayList<>();
        int num = 0;
        int temp = 0;
        for (Map<Integer, Object> map : list) {
            temp = num;
            String orgCode = map.get(1).toString().trim();
            if (!orgCode.equals(sysOrg.getOrgCode())) {
                temp += 3;
                throw new BusinessException("第" + temp + "行数据非本单位数据" + map.get(0).toString() + "-----" +
                        map.get(2).toString());
            }
            num++;
            TVideoEquipmentInfo tVideoEquipmentInfo = new TVideoEquipmentInfo();
            tVideoEquipmentInfo.setOrgName(map.get(0).toString()).setOrgId(sysOrg.getOrgId())
                    .setEquipmentName(map.get(2).toString()).setDeviceId(map.get(3).toString())
                    .setInstallationLocation(map.get(4).toString()).setMonitorLocation(map.get(6).toString());
            infos.add(tVideoEquipmentInfo);
        }

        // 得到最终入库的数据
        List<TVideoEquipmentInfo> extracted = extracted(infos);
        // 存储设备信息
        for (TVideoEquipmentInfo tVideoEquipmentInfo : extracted) {
            tVideoEquipmentInfoController.addEntity(tVideoEquipmentInfo);
        }
        return response;
    }

    private List<TVideoEquipmentInfo> extracted(List<TVideoEquipmentInfo> infos) throws BusinessException {
        // 存储最终入库的数据
        List<TVideoEquipmentInfo> equipmentInfos = new ArrayList<>();

        // 按照设备编号分组
        Map<String, List<TVideoEquipmentInfo>> collect = infos.stream().collect(Collectors.groupingBy(TVideoEquipmentInfo::getDeviceId));

        // 按照设备名称分组
        Map<String, List<TVideoEquipmentInfo>> pmentName = infos.stream().collect(Collectors.groupingBy(TVideoEquipmentInfo::getEquipmentName));

        checkVideo(pmentName);

        // 验证导入数据的合法性
        checkVideo(collect);


        for (String s : collect.keySet()) {
            String monitorLocation = "";
            List<TVideoEquipmentInfo> tVideoEquipmentInfos = collect.get(s);
            TVideoEquipmentInfo tVideoEquipmentIn = null;
            if (ObjectHelper.isNotEmpty(tVideoEquipmentInfos) && tVideoEquipmentInfos.size() > 0) {
                for (TVideoEquipmentInfo tVideoEquipmentInfo : tVideoEquipmentInfos) {
                    List<TSafeSpaceVO> tSafeSpaceVOS = spaceManageService.listByCode(tVideoEquipmentInfo.getMonitorLocation());
                    if (ObjectHelper.isNotEmpty(tSafeSpaceVOS) && tSafeSpaceVOS.size() > 0) {
                        TSafeSpaceVO tSafeSpaceVO = tSafeSpaceVOS.get(0);
                        monitorLocation += tSafeSpaceVO.getId() + ",";
                    }
                }
                tVideoEquipmentIn = tVideoEquipmentInfos.get(0);
            }
            tVideoEquipmentIn.setMonitorLocation(monitorLocation);
            tVideoEquipmentIn.setOrgId(null);
            tVideoEquipmentIn.setOrgName(null);
            equipmentInfos.add(tVideoEquipmentIn);
        }

        return equipmentInfos;
    }

    private void checkVideo(Map<String, List<TVideoEquipmentInfo>> collect) throws BusinessException {
        for (String s : collect.keySet()) {
            List<TVideoEquipmentInfo> tVideoEquipmentInfos = collect.get(s);
            // 按照设备名称下的监控区域分组
            Map<String, List<TVideoEquipmentInfo>> collect1 = tVideoEquipmentInfos.stream().collect(Collectors.groupingBy(TVideoEquipmentInfo::getMonitorLocation));
            for (String s1 : collect1.keySet()) {
                if (collect1.get(s1).size() > 1) {
                    throw new BusinessException("同一个设备请勿绑定相同的监控区域 " + s);
                }
            }
        }
    }

    private QueryWrapper<TSysSelective> createQuery(TSysSelectiveParam queryParam) {
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        QueryWrapper<TSysSelective> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(TSysSelective.IS_ISSUE,TSysSelective.CHECK_TIME);
        if (StringHelper.isNotEmpty(queryParam.getCompanyId())) {
            String[] split = queryParam.getCompanyId().split(",");
            queryWrapper.in(TSysSelective.ORG_ID, split);
        }else{
            queryWrapper.eq(TSysSelective.COMPANY_ID, sysOrg.getOrgId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStartDate()) && StringHelper.isNotEmpty(queryParam.getEndDate())) {
            queryWrapper.between(TSysSelective.DUTY_DATE, queryParam.getStartDate(), queryParam.getEndDate());
        }
        if (StringHelper.isNotEmpty(queryParam.getIsIssue())) {
            queryWrapper.eq(TSysSelective.IS_ISSUE, queryParam.getIsIssue());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(TSysSelective.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessId())) {
            queryWrapper.eq(TSysSelective.PROCESS_ID, queryParam.getProcessId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessStatus())) {
            queryWrapper.eq(TSysSelective.PROCESS_STATUS, queryParam.getProcessStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getSelectivePerson())) {
            queryWrapper.eq(TSysSelective.SELECTIVE_PERSON, queryParam.getSelectivePerson());
        }
        if (StringHelper.isNotEmpty(queryParam.getDeptName())) {
            queryWrapper.like(TSysSelective.DEPT_NAME, queryParam.getDeptName());
        }
        if (ObjectHelper.isNotEmpty(queryParam.getCheckTime())) {
            queryWrapper.eq(TSysSelective.CHECK_TIME, queryParam.getCheckTime());
        }
        if (StringHelper.isNotEmpty(queryParam.getWorkCase())) {
            queryWrapper.eq(TSysSelective.WORK_CASE, queryParam.getWorkCase());
        }
        if (StringHelper.isNotEmpty(queryParam.getExistIssue())) {
            queryWrapper.eq(TSysSelective.EXIST_ISSUE, queryParam.getExistIssue());
        }
        if (StringHelper.isNotEmpty(queryParam.getPattern())) {
            queryWrapper.eq(TSysSelective.PATTERN, queryParam.getPattern());
        }
        if (StringHelper.isNotEmpty(queryParam.getCheckPersonPhoto())) {
            queryWrapper.eq(TSysSelective.CHECK_PERSON_PHOTO, queryParam.getCheckPersonPhoto());
        }
        if (StringHelper.isNotEmpty(queryParam.getIssuePhoto())) {
            queryWrapper.eq(TSysSelective.ISSUE_PHOTO, queryParam.getIssuePhoto());
        }
        if (StringHelper.isNotEmpty(queryParam.getDutyOperator())) {
            queryWrapper.eq(TSysSelective.DUTY_OPERATOR, queryParam.getDutyOperator());
        }
        if (StringHelper.isNotEmpty(queryParam.getDutyOperatorId())) {
            queryWrapper.eq(TSysSelective.DUTY_OPERATOR_ID, queryParam.getDutyOperatorId());
        }
        if (StringHelper.isNotEmpty(queryParam.getUnitBelong())) {
            queryWrapper.eq(TSysSelective.UNIT_BELONG, queryParam.getUnitBelong());
        }
        if (StringHelper.isNotEmpty(queryParam.getCompanyName())) {
            queryWrapper.like(TSysSelective.COMPANY_NAME, queryParam.getCompanyName());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantName())) {
            queryWrapper.like(TSysSelective.TENANT_NAME, queryParam.getTenantName());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TSysSelective.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TSysSelective.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TSysSelective.UPDATE_DATE);
        }
        return queryWrapper;
    }

    public enum GETTYPE {
        P_M("0", "未开始"),
        A_M("1", "进行中"),
        R_M("3", "已完成"),
        N_M("5", "逾期未完成");
        private String value;
        private String name;

        GETTYPE(String value, String name) {
            this.value = value;
            this.name = name;
        }

        public String getValue() {
            return value;
        }

        public String getName() {
            return name;
        }

        public static String getName(String value) {
            for (GETTYPE bean : GETTYPE.values()) {
                if (bean.getValue().equals(value)) {
                    return bean.getName();
                }
            }
            return value;
        }
    }

    public enum CAN {
        P_M("0", "线上"),
        A_M("1", "线下"),
        R_M("2", "自主");
        private String value;
        private String name;

        CAN(String value, String name) {
            this.value = value;
            this.name = name;
        }

        public String getValue() {
            return value;
        }

        public String getName() {
            return name;
        }

        public static String getName(String value) {
            for (CAN bean : CAN.values()) {
                if (bean.getValue().equals(value)) {
                    return bean.getName();
                }
            }
            return value;
        }
    }

    public enum CAN_TYPE {
        P_M("3", "危险作业人员"),
        A_M("4", "一般从业人员"),
        B_M("5", "相关方人员"),
        C_M("6", "新员工及转岗人员"),
        D_M("entry_exam", "一把手"),
        R_M("skill_exam", "安全管理人员");
        private String value;
        private String name;

        CAN_TYPE(String value, String name) {
            this.value = value;
            this.name = name;
        }

        public String getValue() {
            return value;
        }

        public String getName() {
            return name;
        }

        public static String getName(String value) {
            for (CAN_TYPE bean : CAN_TYPE.values()) {
                if (bean.getValue().equals(value)) {
                    return bean.getName();
                }
            }
            return value;
        }
    }


    public enum TRAIN_TYPE {

        /**
         教育培训_培训类型(train_type)
         */
        A_M("1", "综合培训"),
        B_M("2", "专项培训"),
        C_M("3", "实操培训"),
        D_M("4", "新员工及转岗培训");
        private String value;
        private String name;

        TRAIN_TYPE(String value, String name) {
            this.value = value;
            this.name = name;
        }

        public String getValue() {
            return value;
        }

        public String getName() {
            return name;
        }

        public static String getName(String value) {
            for (TRAIN_TYPE bean : TRAIN_TYPE.values()) {
                if (bean.getValue().equals(value)) {
                    return bean.getName();
                }
            }
            return value;
        }
    }
}
