package com.ruoyi.project.common;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.export.JxlsTemplateEnum;
import com.ruoyi.common.utils.export.JxlsView;
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 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 org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 导入下载模板
     */
    @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("moc") ) {
            downloadname = "MOC管理导入模板.xlsx";
            url = "static/template/process/moc.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("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("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("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("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("targetlist") ) {
            downloadname = "目标录入导入模板.xlsx";
            url = "static/template/plant/targetlist.xlsx";
        } 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";
        }
        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());
        }
    }

    /**
     * 本地资源通用下载
     */
    @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();
            }
        }
    }
}
