package com.ruoyi.project.sems.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.document.PDFTemplateUtil;
import com.ruoyi.common.utils.document.ZipUtil;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.sems.domain.TReportHiYlrq;
import com.ruoyi.project.sems.domain.TReportYlrq;
import com.ruoyi.project.sems.domain.TSpecdevYlrq;
import com.ruoyi.project.sems.service.ITReportHiYlrqService;
import com.ruoyi.project.sems.service.ITReportYlrqService;
import com.ruoyi.project.sems.service.ITSpecdevYlrqService;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.system.service.ISysUserService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 压力容器报告历史Controller
 *
 * @author ruoyi
 * @date 2021-09-02
 */
@RestController
@RequestMapping("/sems/historyYlrq")
public class TReportHiYlrqController extends BaseController {
    @Autowired
    private ITReportHiYlrqService tReportHiYlrqService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ITReportYlrqService tReportYlrqService;

    @Autowired
    private ITSpecdevYlrqService tSpecdevYlrqService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private HistoryService historyService;

    /**
     * 查询压力容器报告历史列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TReportHiYlrq tReportHiYlrq) {
        startPage();
        List<TReportHiYlrq> list = tReportHiYlrqService.selectTReportHiYlrqList(tReportHiYlrq);
        return getDataTable(list);
    }

    /**
     * 导出压力容器报告历史列表
     */
    @PreAuthorize("@ss.hasPermi('sems:historyYlrq:export')")
    @Log(title = "压力容器报告历史", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TReportHiYlrq tReportHiYlrq) {
        List<TReportHiYlrq> list = tReportHiYlrqService.selectTReportHiYlrqList(tReportHiYlrq);
        ExcelUtil<TReportHiYlrq> util = new ExcelUtil<TReportHiYlrq>(TReportHiYlrq.class);
        return util.exportExcel(list, "historyYlrq");
    }

    /**
     * 获取压力容器报告历史详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tReportHiYlrqService.selectTReportHiYlrqById(id));
    }

    /**
     * 新增压力容器报告历史
     */
    @PreAuthorize("@ss.hasPermi('sems:historyYlrq:add')")
    @Log(title = "压力容器报告历史", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TReportHiYlrq tReportHiYlrq) {
        return toAjax(tReportHiYlrqService.insertTReportHiYlrq(tReportHiYlrq));
    }

    /**
     * 修改压力容器报告历史
     */
    @PreAuthorize("@ss.hasPermi('sems:historyYlrq:edit')")
    @Log(title = "压力容器报告历史", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TReportHiYlrq tReportHiYlrq) {
        return toAjax(tReportHiYlrqService.updateTReportHiYlrq(tReportHiYlrq));
    }

    /**
     * 删除压力容器报告历史
     */
    @PreAuthorize("@ss.hasPermi('sems:historyYlrq:remove')")
    @Log(title = "压力容器报告历史", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tReportHiYlrqService.deleteTReportHiYlrqByIds(ids));
    }

    @GetMapping("/exportReportPDF")
    public String exportPDF(@RequestParam String id, HttpServletRequest request, HttpServletResponse response) {
//        OutputStream out = null;
        try {
//            out = response.getOutputStream();
            //获取信息，就是上面的结构
            HashMap<String, Object> map = new HashMap<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            TReportHiYlrq tReportHiYlrq = this.tReportHiYlrqService.selectTReportHiYlrqById(Long.parseLong(id));
            List<SysDictData> con = iSysDictTypeService.selectDictDataByType("REPORT_CON");
            if (StringUtils.isNotEmpty(tReportHiYlrq.getCon())) {
                for (SysDictData c : con) {
                    if (tReportHiYlrq.getCon().equals(c.getDictValue())) {
                        tReportHiYlrq.setCon(c.getDictLabel());
                    }
                }
            }
            if (StringUtils.isNotEmpty(tReportHiYlrq.getPlantCode())) {
                SysUser sysUser = this.iSysUserService.selectSafeManagerUserByPlantCode(tReportHiYlrq.getPlantCode());
                if (sysUser != null) {
                    map.put("safeUserName", sysUser.getNickName());
                    map.put("safePhonenumber", sysUser.getPhonenumber());
                } else {
                    map.put("safeUserName", "");
                    map.put("safePhonenumber", "");
                }
            }
            // 转换为 LocalDate 获取年份
            int year = tReportHiYlrq.getCheckDate().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate()
                    .getYear();
            tReportHiYlrq.setYearReportNo(tReportHiYlrq.getPlantCode() + "-"+ year +  "-" + tReportHiYlrq.getYearReportNo());
            map.put("reportHiYlrq", tReportHiYlrq);
            TReportYlrq reportYlrq = tReportYlrqService.selectTReportYlrqById(tReportHiYlrq.getReportId());
            TSpecdevYlrq devYlrq = tSpecdevYlrqService.selectTSpecdevYlrqById(reportYlrq.getDevId());
            map.put("devYlrq", devYlrq);
            if (tReportHiYlrq.getCheckDate() != null) {
                map.put("checkDate", sdf.format(tReportHiYlrq.getCheckDate()));
            }
            if (tReportHiYlrq.getNextWarnDate() != null) {
                String[] nextWarnDateGD = sdf.format(tReportHiYlrq.getNextWarnDate()).split("-");
                map.put("nextWarnDateYear", nextWarnDateGD[0]);
                map.put("nextWarnDateMonth", nextWarnDateGD[1]);
            }
            if (tReportHiYlrq.getNextCheckDate() != null) {
                String[] nextCheckDateGD = sdf.format(tReportHiYlrq.getNextCheckDate()).split("-");
                map.put("nextCheckDateYear", nextCheckDateGD[0]);
                map.put("nextCheckDateMonth", nextCheckDateGD[1]);
            }
            HistoricTaskInstanceQuery htiq = historyService.createHistoricTaskInstanceQuery();
            List<HistoricTaskInstance> htiLists = htiq.processInstanceId(tReportHiYlrq.getApproveId()).finished().orderByHistoricTaskInstanceEndTime().asc().list();
            logger.info("历史任务：" + JSON.toJSONString(htiLists));
            if (htiLists != null && htiLists.size() > 0  ) {
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                map.put("inspectorOne", iSysUserService.selectUserById(Long.parseLong(htiLists.get(0).getAssignee())).getNickName());
                map.put("inspectorOneEndTime", sdf2.format(htiLists.get(0).getEndTime()));
                map.put("inspectorTwo", iSysUserService.selectUserById(Long.parseLong(htiLists.get(1).getAssignee())).getNickName());
                map.put("inspectorTwoEndTime", sdf2.format(htiLists.get(1).getEndTime()));
                map.put("inspectorThree", iSysUserService.selectUserById(Long.parseLong(htiLists.get(2).getAssignee())).getNickName());
                map.put("inspectorThreeEndTime", sdf2.format(htiLists.get(2).getEndTime()));
                map.put("auditor",iSysUserService.selectUserById(Long.parseLong(htiLists.get(3).getAssignee())).getNickName());
                map.put("auditorEndTime", sdf2.format(htiLists.get(3).getEndTime()));
                map.put("approveUser", iSysUserService.selectUserById(Long.parseLong(htiLists.get(4).getAssignee())).getNickName());
                map.put("approveEndTime", sdf2.format(htiLists.get(4).getEndTime()));
            }
            String check = "-";
            if (tReportHiYlrq.getCheckDate()!= null) {
                check = sdf.format(tReportHiYlrq.getCheckDate());
            }
            String pdfName = tReportHiYlrq.getPlantCode()
                    + "-" + check
                    + "-" + tReportHiYlrq.getDevno()
                    + "-压力容器年度检查报告" +tReportHiYlrq.getReportId() + ".pdf"
                    .replace(" ", "")
                    .replace("\\s", "")
                    .replace("\n", "");
            pdfName = FileUtils.isValidFilenameAndReplace(pdfName); //验证合规
            // 生成PDF文件
            PDFTemplateUtil.createPdf("yearYlrqFMaker.ftl", pdfName,
                    RuoYiConfig.getProfile() + "/reportHiYlrq/",
                    "file:/" + RuoYiConfig.getProfile(), map, response);
//            PDFTemplateUtil.exportPdf("yearYlrqFMaker.ftl", pdfName, "file:/" + RuoYiConfig.getProfile(), map, response);
            reportYlrq.setReportUrl(pdfName);
            this.tReportHiYlrqService.updateTReportHiYlrq(reportYlrq);
            return Constants.RESOURCE_PREFIX + "/" + "/reportHiYlrq/"  + pdfName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return null;
    }

    @RequestMapping("/exportPDFForYear")
    public String exportPDFForYear(@RequestParam String year, HttpServletRequest request, HttpServletResponse response) {
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            //获取信息，就是上面的结构
            HashMap<String, Object> map = new HashMap<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //
            TReportHiYlrq hiYlrq = new TReportHiYlrq();
            Map param = new HashMap();
            param.put("year" , year);
            hiYlrq.setParams(param);
            List<TReportHiYlrq> tReportHiYlrqs = this.tReportHiYlrqService.selectTReportHiYlrqForYear(hiYlrq);
            List<SysDictData> con = iSysDictTypeService.selectDictDataByType("REPORT_CON");
            //使用当前时间作为文件夹，所有文件保存在当中
            long now = System.currentTimeMillis();
            //存放所有pdf文件路径
            List<String> list = new ArrayList<>();
            for (TReportHiYlrq tReportHiYlrq : tReportHiYlrqs) {
                if (tReportHiYlrq.getReportUrl()!= null) { //生成过得pdf不需要重复生成
                    list.add(tReportHiYlrq.getReportUrl());
                    continue;
                }
                if (StringUtils.isNotEmpty(tReportHiYlrq.getCon())) {
                    for (SysDictData c : con) {
                        if (tReportHiYlrq.getCon().equals(c.getDictValue())) {
                            tReportHiYlrq.setCon(c.getDictLabel());
                        }
                    }
                }
                if (StringUtils.isNotEmpty(tReportHiYlrq.getPlantCode())) {
                    SysUser sysUser = this.iSysUserService.selectSafeManagerUserByPlantCode(tReportHiYlrq.getPlantCode());
                    if (sysUser != null) {
                        map.put("safeUserName", sysUser.getNickName());
                        map.put("safePhonenumber", sysUser.getPhonenumber());
                    } else {
                        map.put("safeUserName", "");
                        map.put("safePhonenumber", "");
                    }
                }
                // 转换为 LocalDate 获取年份
                int year2 = tReportHiYlrq.getCheckDate().toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDate()
                        .getYear();
                tReportHiYlrq.setYearReportNo(tReportHiYlrq.getPlantCode() + "-"+ year2 +  "-"+tReportHiYlrq.getYearReportNo());
                map.put("reportHiYlrq", tReportHiYlrq);
                TReportYlrq reportYlrq = tReportYlrqService.selectTReportYlrqById(tReportHiYlrq.getReportId());
                //如果出现无法获取的基础数据，可能是以往的脏数据，选择跳过当前数据项
                if(reportYlrq == null){
                    continue;
                }
                TSpecdevYlrq devYlrq = tSpecdevYlrqService.selectTSpecdevYlrqById(reportYlrq.getDevId());
                map.put("devYlrq", devYlrq);
                if (tReportHiYlrq.getCheckDate() != null) {
                    map.put("checkDate", sdf.format(tReportHiYlrq.getCheckDate()));
                }
                if (tReportHiYlrq.getNextWarnDate() != null) {
                    String[] nextWarnDateGD = sdf.format(tReportHiYlrq.getNextWarnDate()).split("-");
                    map.put("nextWarnDateYear", nextWarnDateGD[0]);
                    map.put("nextWarnDateMonth", nextWarnDateGD[1]);
                }
                if (tReportHiYlrq.getNextCheckDate() != null) {
                    String[] nextCheckDateGD = sdf.format(tReportHiYlrq.getNextCheckDate()).split("-");
                    map.put("nextCheckDateYear", nextCheckDateGD[0]);
                    map.put("nextCheckDateMonth", nextCheckDateGD[1]);
                }
                HistoricTaskInstanceQuery htiq = historyService.createHistoricTaskInstanceQuery();
                List<HistoricTaskInstance> htiLists = htiq.processInstanceId(tReportHiYlrq.getApproveId()).finished().orderByHistoricTaskInstanceEndTime().asc().list();
                logger.info("报告数据：" + JSON.toJSONString(htiLists));
                if (htiLists != null) {
                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    map.put("inspectorOne", iSysUserService.selectUserById(Long.parseLong(htiLists.get(0).getAssignee())).getNickName());
                    map.put("inspectorOneEndTime", sdf2.format(htiLists.get(0).getEndTime()));
                    map.put("inspectorTwo", iSysUserService.selectUserById(Long.parseLong(htiLists.get(1).getAssignee())).getNickName());
                    map.put("inspectorTwoEndTime", sdf2.format(htiLists.get(1).getEndTime()));
                    map.put("inspectorThree", iSysUserService.selectUserById(Long.parseLong(htiLists.get(2).getAssignee())).getNickName());
                    map.put("inspectorThreeEndTime", sdf2.format(htiLists.get(2).getEndTime()));
                    map.put("auditor",iSysUserService.selectUserById(Long.parseLong(htiLists.get(3).getAssignee())).getNickName());
                    map.put("auditorEndTime", sdf2.format(htiLists.get(3).getEndTime()));
                    map.put("approveUser", iSysUserService.selectUserById(Long.parseLong(htiLists.get(4).getAssignee())).getNickName());
                    map.put("approveEndTime", sdf2.format(htiLists.get(4).getEndTime()));
                }
                //多个文件区分文件名
                String pdfName = tReportHiYlrq.getPlantCode()
                        + "-" + sdf.format(tReportHiYlrq.getCheckDate())
                        + "-" + tReportHiYlrq.getDevno()
                        + "-压力容器年度检查报告" +tReportHiYlrq.getId() + ".pdf"
                        .replace(" ", "")
                        .replace("\\s", "")
                        .replace("\n", "")
                        .replace("\r", "")
                .replace("\t", "");
                pdfName = FileUtils.isValidFilenameAndReplace(pdfName); //验证合规
                // 生成PDF文件
                PDFTemplateUtil.createPdf("yearYlrqFMaker.ftl", pdfName,
                        RuoYiConfig.getProfile() + "/reportHiYlrq/",
                        "file:/" + RuoYiConfig.getProfile(), map, response);
                tReportHiYlrq.setReportUrl(pdfName);
                this.tReportHiYlrqService.updateTReportHiYlrq(tReportHiYlrq);
                list.add(pdfName);
                //PDFTemplateUtil.exportPdf("yearYlrqFMaker.ftl", pdfName, "file:/" + RuoYiConfig.getProfile(), map, response);
            }
            ZipUtil.createZip(RuoYiConfig.getProfile() + "/reportHiYlrq/",  "", year + "年压力容器年度检查历史报告.zip", list, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }
}
