package com.ruoyi.project.common;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.sems.domain.TSpecdevGl;
import com.ruoyi.project.sems.service.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
public class CommonController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    private static final String FILE_DELIMETER = ",";

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ITSpecdevYlrqService tSpecdevYlrqService;
    @Autowired
    private ITSpecdevYlgdService tSpecdevYlgdService;
    @Autowired
    private ITSpecdevGlService tSpecdevGlService;
    @Autowired
    private ITSpecdevDzsbService tSpecdevDzsbService;
    @Autowired
    private ITSpecdevDtService tSpecdevDtService;
    @Autowired
    private ITSpecdevCcService tSpecdevCcService;

    /**
     * 导入下载模板
     */
    @RequestMapping("common/template")
    @ResponseBody
    public void template(String type,HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        String downloadname = "";
        String url = "";
        if ( type.equals("alarmmodify") ) {
            downloadname = "报警值管理导入模板.xlsx";
            url = "static/template/process/alarmmodify.xlsx";
        } else if( type.equals("publicdoc") ) {
            downloadname = "公共文档管理导入模板.xlsx";
            url = "static/template/document/publicdoc.xlsx";
        } else if( type.equals("publicdocmenu") ) {
            downloadname = "公共文档目录管理导入模板.xlsx";
            url = "static/template/document/publicdocmenu.xlsx";
        } else if( type.equals("permanentMoc") ) {
            downloadname = "永久MOC导入模板.xlsx";
            url = "static/template/process/moc/permanentMoc.xlsx";
        } else if( type.equals("temporaryMoc") ) {
            downloadname = "临时MOC导入模板.xlsx";
            url = "static/template/process/moc/temporaryMoc.xlsx";
        } else if( type.equals("aquifier") ) {
            downloadname = "临时MOC-带压消漏清单导入模板.xlsx";
            url = "static/template/process/moc/aquifier.xlsx";
        } else if( type.equals("facility") ) {
            downloadname = "临时MOC-临时设施及其它导入模板.xlsx";
            url = "static/template/process/moc/facility.xlsx";
        } else if( type.equals("interlock") ) {
            downloadname = "临时MOC-仪表联锁旁路导入模板.xlsx";
            url = "static/template/process/moc/interlock.xlsx";
        } else if( type.equals("accident") ) {
            downloadname = "隐患排查导入模板.xlsx";
            url = "static/template/production/accident.xlsx";
        } else if( type.equals("blind") ) {
            downloadname = "盲板清单导入模板.xlsx";
            url = "static/template/production/blind.xlsx";
        } else if( type.equals("我的机器") ) {
            downloadname = "5S管理我的机器导入模板.xlsx";
            url = "static/template/production/wsglmachine.xlsx";
        } else if( type.equals("我的区域") ) {
            downloadname = "5S管理我的区域导入模板.xlsx";
            url = "static/template/production/wsglarea.xlsx";
        } else if( type.equals("day") ) {
            downloadname = "报警统计（昨天）导入模板.xlsx";
            url = "static/template/production/alarmstatistics.xlsx";
        } else if( type.equals("month") ) {
            downloadname = "报警统计（上月）导入模板.xlsx";
            url = "static/template/production/alarmstatistics.xlsx";
        } else if( type.equals("lbnhjstj") ) {
            downloadname = "能耗管理统计导入模板.xlsx";
            url = "static/template/production/lbnhjstj.xlsx";
        } else if( type.equals("sai") ) {
            downloadname = "SAI检查管理导入模板.xlsx";
            url = "static/template/production/sai.xlsx";
        } else if( type.equals("saiApply") ) {
            downloadname = "SAI开项管理导入模板.xlsx";
            url = "static/template/production/saiApply.xlsx";
        } else if( type.equals("rcaudit") ) {
            downloadname = "RC审计助手导入模板.xlsx";
            url = "static/template/ehs/rcaudit.xlsx";
        } else if( type.equals("rcauditmenu") ) {
            downloadname = "RC审计助手目录导入模板.xlsx";
            url = "static/template/ehs/rcauditmenu.xlsx";
        } else if( type.equals("plantproglistprocedure") ) {
            downloadname = "装置程序清单程序总汇导入模板.xlsx";
            url = "static/template/document/plantproglistprocedure.xlsx";
        } else if( type.equals("plantproglistform") ) {
            downloadname = "装置程序清单表格总汇导入模板.xlsx";
            url = "static/template/document/plantproglistform.xlsx";
        } else if( type.equals("plantproglistguide") ) {
            downloadname = "装置程序清单指南总汇导入模板.xlsx";
            url = "static/template/document/plantproglistguide.xlsx";
        } else if( type.equals("plantproglistbook") ) {
            downloadname = "装置程序清单指导书总汇导入模板.xlsx";
            url = "static/template/document/plantproglistbook.xlsx";
        } else if( type.equals("plantproglistannex") ) {
            downloadname = "装置程序清单附件总汇导入模板.xlsx";
            url = "static/template/document/plantproglistannex.xlsx";
        } else if( type.equals("plantproglistmaterials") ) {
            downloadname = "装置程序清单培训材料导入模板.xlsx";
            url = "static/template/document/plantproglistmaterials.xlsx";
        } else if( type.equals("officesupply") ) {
            downloadname = "办公用品管理导入模板.xlsx";
            url = "static/template/affair/officesupply.xlsx";
        } else if( type.equals("ppe") ) {
            downloadname = "PPE发放登记导入模板.xlsx";
            url = "static/template/affair/ppe.xlsx";
        } else if( type.equals("intercom") ) {
            downloadname = "对讲机管理导入模板.xlsx";
            url = "static/template/affair/intercom.xlsx";
        } else if( type.equals("kkxglcs") ) {
            downloadname = "可靠性管理措施导入模板.xlsx";
            url = "static/template/reliability/kkxglcs.xlsx";
        } else if( type.equals("original") ) {
            downloadname = "故障管理初选导入模板.xlsx";
            url = "static/template/reliability/original.xlsx";
        } else if( type.equals("abnormalreport") ) {
            downloadname = "异常报告管理导入模板.xlsx";
            url = "static/template/reliability/abnormalreport.xlsx";
        } else if( type.equals("assetlist") ) {
            downloadname = "资产清单导入模板.xlsx";
            url = "static/template/reliability/assetlist.xlsx";
        } else if( type.equals("safetyvavle") ) {
            downloadname = "安全阀清单导入模板.xlsx";
            url = "static/template/reliability/safetyvavle.xlsx";
        } else if( type.equals("preventivemaintenance") ) {
            downloadname = "预防性维修导入模板.xlsx";
            url = "static/template/reliability/preventivemaintenance.xlsx";
        } else if( type.equals("pipe") ) {
            downloadname = "管线清单导入模板.xlsx";
            url = "static/template/cui/pipe.xlsx";
        } else if( type.equals("pvessel") ) {
            downloadname = "容器清单导入模板.xlsx";
            url = "static/template/cui/pvessel.xlsx";
        } else if( type.equals("problems") ) {
            downloadname = "CUI问题整改跟踪清单导入模板.xlsx";
            url = "static/template/cui/problems.xlsx";
        } else if( type.equals("eyewasher") ) {
            downloadname = "洗眼器导入模板.xlsx";
            url = "static/template/ehs/eyewasher.xlsx";
        } else if( type.equals("firehose") ) {
            downloadname = "消防水带箱导入模板.xlsx";
            url = "static/template/ehs/firehose.xlsx";
        } else if( type.equals("firehydrant") ) {
            downloadname = "消防栓导入模板.xlsx";
            url = "static/template/ehs/firehydrant.xlsx";
        } else if( type.equals("highpresfire") ) {
            downloadname = "高压消防炮导入模板.xlsx";
            url = "static/template/ehs/highpresfire.xlsx";
        } else if( type.equals("fireextinguisher") ) {
            downloadname = "灭火器导入模板.xlsx";
            url = "static/template/ehs/fireextinguisher.xlsx";
        } else if( type.equals("autosprinkler") ) {
            downloadname = "自动喷淋系统导入模板.xlsx";
            url = "static/template/ehs/autosprinkler.xlsx";
        } else if( type.equals("firestandpipe") ) {
            downloadname = "消防竖管导入模板.xlsx";
            url = "static/template/ehs/firestandpipe.xlsx";
        } else if( type.equals("safetyapproval") ) {
            downloadname = "安全批文清单导入模板.xlsx";
            url = "static/template/ehs/safetyapproval.xlsx";
        } else if( type.equals("fireapproval") ) {
            downloadname = "消防批文清单导入模板.xlsx";
            url = "static/template/ehs/fireapproval.xlsx";
        } else if( type.equals("environapproval") ) {
            downloadname = "环保批文清单导入模板.xlsx";
            url = "static/template/ehs/environapproval.xlsx";
        } else if( type.equals("healthapproval") ) {
            downloadname = "卫生批文清单导入模板.xlsx";
            url = "static/template/ehs/healthapproval.xlsx";
        } else if( type.equals("safetyapprcont") ) {
            downloadname = "安全批文主要内容导入模板.xlsx";
            url = "static/template/ehs/safetyapprcont.xlsx";
        } else if( type.equals("environapprcont") ) {
            downloadname = "环保批文主要内容导入模板.xlsx";
            url = "static/template/ehs/environapprcont.xlsx";
        } else if( type.equals("jobticket") ) {
            downloadname = "工作票导入模板.xlsx";
            url = "static/template/ehs/jobticket.xlsx";
        } else if( type.equals("msds") ) {
            downloadname = "MSDS管理导入模板.xlsx";
            url = "static/template/ehs/msds.xlsx";
        } else if( type.equals("incidentRecords") ) {
            downloadname = "事故报告清单导入模板.xlsx";
            url = "static/template/ehs/incidentRecords.xlsx";
        } else if( type.equals("water") ) {
            downloadname = "废水风险评估导入模板.xlsx";
            url = "static/template/ehs/water.xlsx";
        } else if( type.equals("danger") ) {
            downloadname = "危险废物清单导入模板.xlsx";
            url = "static/template/ehs/danger.xlsx";
        } else if( type.equals("dangermonth") ) {
            downloadname = "危险废物出入库月报导入模板.xlsx";
            url = "static/template/ehs/dangermonth.xlsx";
        } else if( type.equals("barrelmonth") ) {
            downloadname = "废桶进出库统计日报导入模板.xlsx";
            url = "static/template/ehs/barrelmonth.xlsx";
        } else if( type.equals("dangerday") ) {
            downloadname = "危废出入库统计日报导入模板.xlsx";
            url = "static/template/ehs/dangerday.xlsx";
        } else if( type.equals("workcertificate") ) {
            downloadname = "作业证书一览表导入模板.xlsx";
            url = "static/template/training/workcertificate.xlsx";
        } else if( type.equals("byxworkcertificate") ) {
            downloadname = "苯乙烯作业证书一览表导入模板.xlsx";
            url = "static/template/training/byxworkcertificate.xlsx";
        } else if( type.equals("worklicense") ) {
            downloadname = "上岗证一览表导入模板.xlsx";
            url = "static/template/training/worklicense.xlsx";
        } else if( type.equals("trainingrecords") ) {
            downloadname = "培训成绩导入模板.xlsx";
            url = "static/template/training/trainingrecords.xlsx";
        } else if( type.equals("training") ) {
            downloadname = "培训计划执行及跟踪导入模板.xlsx";
            url = "static/template/training/training.xlsx";
        } else if( type.equals("skillevaluation") ) {
            downloadname = "岗位人员技能评估导入模板.xlsx";
            url = "static/template/training/skillevaluation.xlsx";
        } else if( type.equals("newemployee") ) {
            downloadname = "新员工培训导入模板.xlsx";
            url = "static/template/training/newemployee.xlsx";
        }else if( type.equals("companyLevelRecord") ) {
            downloadname = "公司培训成绩导入模板.xlsx";
            url = "static/template/training/companyLevelRecord.xlsx";
        } else if( type.equals("targetlist") ) {
            downloadname = "目标录入导入模板.xlsm";
            url = "static/template/plant/targetlist.xlsm";
        } else if( type.equals("targetreview") ) {
            downloadname = "目标回顾导入模板.xlsx";
            url = "static/template/plant/targetreview.xlsx";
        } else if( type.equals("manageactivity") ) {
            downloadname = "管理活动抽查导入模板.xlsx";
            url = "static/template/plant/manageactivity.xlsx";
        } else if( type.equals("awardrecord") ) {
            downloadname = "人员嘉奖记录导入模板.xlsx";
            url = "static/template/plant/awardrecord.xlsx";
        } else if( type.equals("staffmgr") ) {
            downloadname = "人员信息导入模板.xlsx";
            url = "static/template/plant/staffmgr.xlsx";
        } else if( type.equals("specYlrq") ) {
            downloadname = "压力容器导入模板.xlsx";
            url = "static/template/sems/specYlrq.xlsx";
        } else if( type.equals("specYlgd") ) {
            downloadname = "压力管道导入模板.xlsx";
            url = "static/template/sems/specYlgd.xlsx";
        }else if( type.equals("specGl") ) {
            downloadname = "锅炉导入模板.xlsx";
            url = "static/template/sems/specGl.xlsx";
        }else if( type.equals("specDzsb") ) {
            downloadname = "起重机械导入模板.xlsx";
            url = "static/template/sems/specDzsb.xlsx";
        }else if( type.equals("specCc") ) {
            downloadname = "叉车导入模板.xlsx";
            url = "static/template/sems/specCc.xlsx";
        }else if( type.equals("specDt") ) {
            downloadname = "电梯导入模板.xlsx";
            url = "static/template/sems/specDt.xlsx";
        }else if( type.equals("reportYlrq") ) {
            downloadname = "压力容器年检报告批量导入更新模板.xlsx";
            url = "static/template/sems/reportYlrq.xlsx";
        }else if( type.equals("reportYlgd") ) {
            downloadname = "压力管道年检报告批量导入更新模板.xlsx";
            url = "static/template/sems/reportYlgd.xlsx";
        }else if( type.equals("thickness") ) {
            downloadname = "定点测厚批量导入更新模板.xlsx";
            url = "static/template/sems/thickness.xlsx";
        }else if( type.equals("thicknessData") ) {
            downloadname = "定点测厚数据导入模板.xlsx";
            url = "static/template/sems/thicknessData.xlsx";
        }else if( type.equals("applyLock") ) {
            downloadname = "锁开锁关导入模板.xlsx";
            url = "static/template/apply/applyLock.xlsx";
        }else if( type.equals("workcertificateCbps") ) {
            downloadname = "作业证书模板.xlsx";
            url = "static/template/training/workcertificateCbps.xlsx";
        }else if( type.equals("quality") ) {
            downloadname = "质量月报批量导入模板.xlsx";
            url = "static/template/production/quality.xlsx";
        }else if( type.equals("trainingMatrix") ) {
            downloadname = "培训矩阵导入模板.xlsx";
            url = "static/template/training/trainingMatrix.xlsx";
        }else if( type.equals("ljPlanTmpl") ) {
            downloadname = "裂解培训导入模板.xlsx";
            url = "static/template/training/bccnewDsdt.xlsx";
        }else if( type.equals("ysPlanTmpl") ) {
            downloadname = "压缩培训导入模板.xlsx";
            url = "static/template/training/bccnewDsdt.xlsx";
        }else if( type.equals("flPlanTmpl") ) {
            downloadname = "分离培训导入模板.xlsx";
            url = "static/template/training/bccnewDsdt.xlsx";
        }else if( type.equals("ftPlanTmpl") ) {
            downloadname = "芳烃培训导入模板.xlsx";
            url = "static/template/training/bccnewDsdt.xlsx";
        }else if( type.equals("jzPlanTmpl") ) {
            downloadname = "装置级培训导入模板.xlsx";
            url = "static/template/training/bccnewJz.xlsx";
        }else if( type.equals("trainerTmpl") ) {
            downloadname = "导师库导入模板.xlsx";
            url = "static/template/training/bccnewDsk.xlsx";
        }else if( type.equals("shiftRoster") ) {
            downloadname = "排班计划导入模板.xlsx";
            url = "static/template/training/roster.xlsx";
        }else if( type.equals("pssrTmpl") ) {
            downloadname = "开车条件确认表导入模板.xlsx";
            url = "static/template/pssr/pssrTmpl.xlsx";
        }else if( type.equals("pssrRegionTmpl") ) {
            downloadname = "PSSR区域导入模板.xlsx";
            url = "static/template/pssr/pssrRegionTmpl.xlsx";
        }else if( type.equals("overhaulExchanger") ) {
            downloadname = "PSSR检修项目-换热器导入模板.xlsx";
            url = "static/template/pssr/overhaulExchanger.xlsx";
        }else if( type.equals("overhaulTower") ) {
            downloadname = "PSSR检修项目-塔罐导入模板.xlsx";
            url = "static/template/pssr/overhaulTower.xlsx";
        }else if( type.equals("overhaulValve") ) {
            downloadname = "PSSR检修项目-阀门导入模板.xlsx";
            url = "static/template/pssr/overhaulValve.xlsx";
        }else if( type.equals("overhaulFilter") ) {
            downloadname = "PSSR检修项目-过滤器导入模板.xlsx";
            url = "static/template/pssr/overhaulFilter.xlsx";
        }else if( type.equals("pssrblind") ) {
            downloadname = "PSSR盲板导入模板.xlsx";
            url = "static/template/pssr/blind.xlsx";
        }else if( type.equals("overhaulExchanger2") ) {
            downloadname = "PSSR检修项目-电仪导入模板.xlsx";
            url = "static/template/pssr/overhaulExchanger.xlsx";
        }else if( type.equals("overhaulExchanger3") ) {
            downloadname = "PSSR检修项目-反应器导入模板.xlsx";
            url = "static/template/pssr/overhaulExchanger.xlsx";
        }else if( type.equals("overhaulExchanger4") ) {
            downloadname = "PSSR检修项目-裂解炉导入模板.xlsx";
            url = "static/template/pssr/overhaulExchanger.xlsx";
        }else if( type.equals("overhaulExchanger5") ) {
            downloadname = "PSSR检修项目-其它导入模板.xlsx";
            url = "static/template/pssr/overhaulExchanger.xlsx";
        }else if( type.equals("overhaulExchanger6") ) {
            downloadname = "PSSR检修项目-动设备导入模板.xlsx";
            url = "static/template/pssr/overhaulExchanger.xlsx";
        }else if( type.equals("overhaulExchanger7") ) {
            downloadname = "PSSR检修项目-安全附件导入模板.xlsx";
            url = "static/template/pssr/overhaulExchanger.xlsx";
        }else if( type.equals("overhaulExchanger8") ) {
            downloadname = "PSSR检修项目-管道导入模板.xlsx";
            url = "static/template/pssr/overhaulExchanger.xlsx";
        }else if( type.equals("hygiene") ) {
            downloadname = "PSSR现场卫生导入模板.xlsx";
            url = "static/template/pssr/hygiene.xlsx";
        }else if( type.equals("measure") ) {
            downloadname = "PSSR人身防护现场转动设备防护措施检查表导入模板.xlsx";
            url = "static/template/pssr/measure.xlsx";
        }else if( type.equals("protection") ) {
            downloadname = "PSSR人身防护现场管道和设备保温防护检查表导入模板.xlsx";
            url = "static/template/pssr/protection.xlsx";
        }else if( type.equals("cleaning") ) {
            downloadname = "PSSR设备清洁度导入模板.xlsx";
            url = "static/template/pssr/cleaning.xlsx";
        }else if( type.equals("airtight") ) {
            downloadname = "PSSR气密导入模板.xlsx";
            url = "static/template/pssr/airtight.xlsx";
        }else if( type.equals("laboratory") ) {
            downloadname = "PSSR实验室导入模板.xlsx";
            url = "static/template/pssr/laboratory.xlsx";
        }else if( type.equals("circuit") ) {
            downloadname = "PSSR短接导入模板.xlsx";
            url = "static/template/pssr/circuit.xlsx";
        }else if( type.equals("nitrogen") ) {
            downloadname = "PSSR氮气置换导入模板.xlsx";
            url = "static/template/pssr/nitrogen.xlsx";
        }else if( type.equals("safetyBrust") ) {
            downloadname = "PSSR安全设施-爆破片导入模板.xlsx";
            url = "static/template/pssr/safetyBrust.xlsx";
        }else if( type.equals("safetyBreath") ) {
            downloadname = "PSSR安全设施-呼吸阀导入模板.xlsx";
            url = "static/template/pssr/safetyBreath.xlsx";
        }else if( type.equals("safetyBleed") ) {
            downloadname = "PSSR安全设施-泄放阀导入模板.xlsx";
            url = "static/template/pssr/safetyBleed.xlsx";
        }else if( type.equals("safetyFlamearrester") ) {
            downloadname = "PSSR安全设施-阻火器导入模板.xlsx";
            url = "static/template/pssr/safetyFlamearrester.xlsx";
        }else if( type.equals("pumpFill") ) {//
            downloadname = "PSSR机泵-润滑油加注确认清单导入模板.xlsx";
            url = "static/template/pssr/pumpFill.xlsx";
        }else if( type.equals("pumpOverhaul") ) {
            downloadname = "PSSR机泵-检修完成确认清单导入模板.xlsx";
            url = "static/template/pssr/pumpOverhaul.xlsx";
        }else if( type.equals("pumpCleaning") ) {
            downloadname = "PSSR机泵-过滤器清理回装确认表导入模板.xlsx";
            url = "static/template/pssr/pumpCleaning.xlsx";
        }else if( type.equals("motor") ) {
            downloadname = "PSSR电机设备导入模板.xlsx";
            url = "static/template/pssr/motor.xlsx";
        }else if( type.equals("calibration") ) {
            downloadname = "PSSR仪表校验导入模板.xlsx";
            url = "static/template/pssr/calibration.xlsx";
        }else if( type.equals("frame") ) {
            downloadname = "PSSR支（吊）架导入模板.xlsx";
            url = "static/template/pssr/frame.xlsx";
        }else if( type.equals("franklinism") ) {
            downloadname = "PSSR静电接地，跨接导入模板.xlsx";
            url = "static/template/pssr/franklinism.xlsx";
        }else if( type.equals("gasdetector") ) {
            downloadname = "PSSR气体检测器导入模板.xlsx";
            url = "static/template/pssr/gasdetector.xlsx";
        }else if( type.equals("analyzer") ) {
            downloadname = "PSSR在线分析仪导入模板.xlsx";
            url = "static/template/pssr/analyzer.xlsx";
        }else if( type.equals("pssrFrameTmpl") ) {
            downloadname = "PSSR支（吊）架模板数据维护.xlsx";
            url = "static/template/pssr/frameModel.xlsx";
        }

        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(url);

        downloadFile(downloadname, is, request, response);
    }


    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            logger.info("url:" + url);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/common/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files, @RequestParam(value = "fileDir", required = false) String fileDir) throws Exception {
        try {
            // 上传文件路径
            String filePath;
            if (StringUtils.isNotEmpty(fileDir)) {
                filePath = RuoYiConfig.getUploadPath(getResource(fileDir));
            } else {
                filePath = RuoYiConfig.getUploadPath();
            }
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl();
                if (url.contains("81")){
                    url += "/cpms";
                }
                url = url + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    private static String getResource(String type) {
        switch (type) {
            case "1":
                return "/annihiliator";
            case "12":
                return "/eyewash";
            default:
                return "";
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String name, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(name, Constants.RESOURCE_PREFIX);
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }

    public static void downloadFile(String filename, InputStream is, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.reset();
        if (filename.endsWith(".doc") || filename.endsWith(".docx")) {
            response.setContentType("application/msword;charset=utf-8");
        } else if (filename.endsWith(".xls") || filename.endsWith(".xlsx")) {
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
        } else {
            response.setHeader("content-type", "application/octet-stream");
        }
        //下载文件的名称
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "iso-8859-1"));
        request.setCharacterEncoding("UTF-8");

        ServletOutputStream out = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            out = response.getOutputStream();
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

//    @RequestMapping("/common/download/exportDevList")
//    public ModelAndView exportbmy(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws ParseException {
//        logger.info(JSON.toJSONString(params));
//        String id = (String) params.get("ids");
//        int devType = Integer.parseInt((String) params.get("devType"));
//        String[] ids = id.split(",");
//        logger.info("ids" + ids);
//        int downloadType = Integer.parseInt((String) params.get("downloadType"));
//        logger.info("downloadType" + downloadType);
//        List<Object> list = new ArrayList<>();
//        switch (devType) {
//            case 1:
//                for (String i : ids
//                ) {
//                    TSpecdevYlrq ylrqEntity = tSpecdevYlrqService.getById(i);
//                    list.add(ylrqEntity);
//                }
//                break;
//            case 2:
//                for (String i : ids
//                ) {
//                    TSpecdevYlgd ylgdEntity = tSpecdevYlgdService.getById(i);
//                    list.add(ylgdEntity);
//                }
//                break;
//            case 3:
//                for (String i : ids
//                ) {
//                    TSpecdevDzsb dzsbEntity = tSpecdevDzsbService.getById(i);
//                    list.add(dzsbEntity);
//                }
//                break;
//            case 4:
//                for (String i : ids
//                ) {
//                    TSpecdevGl glEntity = tSpecdevGlService.getById(i);
//                    list.add(glEntity);
//                }
//                break;
//            case 5:
//                for (String i : ids
//                ) {
//                    TSpecdevDt dtEntity = tSpecdevDtService.getById(i);
//                    list.add(dtEntity);
//                }
//                break;
//            case 6:
//                for (String i : ids
//                ) {
//                    TSpecdevCc ccEntity = tSpecdevCcService.getById(i);
//                    list.add(ccEntity);
//                }
//                break;
//            case 7:
////                for (String i : ids
////                ) {
////                    TOtherTankEntity tankEntity = tOtherTankService.getById(i);
////                    list.add(tankEntity);
////                }
//        }
//        if(devType == 1 && downloadType == 2){ return new ModelAndView(new JxlsView(JxlsTemplateEnum.DEV_YLRQ_UPDATE, list)); }
//        else if(devType == 2 && downloadType == 2){ return new ModelAndView(new JxlsView(JxlsTemplateEnum.DEV_YLGD_UPDATE, list)); }
//        else if(devType == 3 && downloadType == 2){ return new ModelAndView(new JxlsView(JxlsTemplateEnum.DEV_DZSB_UPDATE, list)); }
//        else if(devType == 4 && downloadType == 2){ return new ModelAndView(new JxlsView(JxlsTemplateEnum.DEV_GL_UPDATE, list)); }
//        else if(devType == 5 && downloadType == 2){ return new ModelAndView(new JxlsView(JxlsTemplateEnum.DEV_DT_UPDATE, list)); }
//        else if(devType == 6 && downloadType == 2){ return new ModelAndView(new JxlsView(JxlsTemplateEnum.DEV_CC_UPDATE, list)); }
//        return null;
//    }
    @GetMapping("/common/download/exportDevList")
    public AjaxResult exportbmy(TSpecdevGl tSpecdevGl) throws IOException {
        logger.info("kaishi");
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        CellStyle wrapStyle = wb.createCellStyle();
        wrapStyle.setWrapText(true);    //设置自动换行
        //创建sheet页
        Sheet sheet = wb.createSheet("sheetName");
    //设置列的宽度，第一个参数为列的序号，从0开始，第二参数为列宽，单位1/256个字节
        sheet.setColumnWidth(0, 12*256);
        sheet.setColumnWidth(2, 16*256);
        sheet.setColumnWidth(5, 12*256);
        sheet.setColumnWidth(6, 26*256);
        sheet.setColumnWidth(7, 26*256);
        //设置开始行和开始列
        int rowIndex = 0;
        int columnIndex = 0;
        Row row = sheet.createRow(rowIndex);

        OutputStream out = null;
        String filename = encodingFilename("sheetName");
        out = new FileOutputStream(getAbsoluteFile(filename));
        wb.write(out);
        wb.close();
        out.close();
       return AjaxResult.success(filename);
    }

    /**
     * 编码文件名
     */
    public String encodingFilename(String filename)
    {
        filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
        return filename;
    }

    /**
     * 获取下载路径
     *
     * @param filename 文件名称
     */
    public String getAbsoluteFile(String filename)
    {
        String downloadPath = RuoYiConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }
}
