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.TReportHiYlgd;
import com.ruoyi.project.sems.domain.TReportYlgd;
import com.ruoyi.project.sems.domain.TSpecdevYlgd;
import com.ruoyi.project.sems.service.ITReportHiYlgdService;
import com.ruoyi.project.sems.service.ITReportYlgdService;
import com.ruoyi.project.sems.service.ITSpecdevYlgdService;
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/historyYlgd")
public class TReportHiYlgdController extends BaseController {
    @Autowired
    private ITReportHiYlgdService tReportHiYlgdService;

    @Autowired
    private ITReportYlgdService tReportYlgdService;

    @Autowired
    private ITSpecdevYlgdService tSpecdevYlgdService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private HistoryService historyService;

    /**
     * 查询压力管道报告历史列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TReportHiYlgd tReportHiYlgd) {
        startPage();
        List<TReportHiYlgd> list = tReportHiYlgdService.selectTReportHiYlgdList(tReportHiYlgd);
        return getDataTable(list);
    }

    /**
     * 导出压力管道报告历史列表
     */
    @PreAuthorize("@ss.hasPermi('sems:historyYlgd:export')")
    @Log(title = "压力管道报告历史", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TReportHiYlgd tReportHiYlgd) {
        List<TReportHiYlgd> list = tReportHiYlgdService.selectTReportHiYlgdList(tReportHiYlgd);
        ExcelUtil<TReportHiYlgd> util = new ExcelUtil<TReportHiYlgd>(TReportHiYlgd.class);
        return util.exportExcel(list, "historyYlgd");
    }

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

    /**
     * 新增压力管道报告历史
     */
    @PreAuthorize("@ss.hasPermi('sems:historyYlgd:add')")
    @Log(title = "压力管道报告历史", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TReportHiYlgd tReportHiYlgd) {
        return toAjax(tReportHiYlgdService.insertTReportHiYlgd(tReportHiYlgd));
    }

    /**
     * 修改压力管道报告历史
     */
    @PreAuthorize("@ss.hasPermi('sems:historyYlgd:edit')")
    @Log(title = "压力管道报告历史", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TReportHiYlgd tReportHiYlgd) {
        return toAjax(tReportHiYlgdService.updateTReportHiYlgd(tReportHiYlgd));
    }

    /**
     * 删除压力管道报告历史
     */
    @PreAuthorize("@ss.hasPermi('sems:historyYlgd:remove')")
    @Log(title = "压力管道报告历史", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tReportHiYlgdService.deleteTReportHiYlgdByIds(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");
            TReportHiYlgd reportHiYlgd = tReportHiYlgdService.selectTReportHiYlgdById(Long.parseLong(id));
            if (StringUtils.isNotEmpty(reportHiYlgd.getCon())) {
                List<SysDictData> con = iSysDictTypeService.selectDictDataByType("REPORT_CON");
                for (SysDictData c : con) {
                    if (reportHiYlgd.getCon().equals(c.getDictValue())) {
                        reportHiYlgd.setCon(c.getDictLabel());
                    }
                }
            }
            if (StringUtils.isNotEmpty(reportHiYlgd.getPlantCode())) {
                SysUser sysUser = this.iSysUserService.selectSafeManagerUserByPlantCode(reportHiYlgd.getPlantCode());
                if (sysUser != null) {
                    map.put("safeUserName", sysUser.getNickName());
                    map.put("safePhonenumber", sysUser.getPhonenumber());
                } else {
                    map.put("safeUserName", "");
                    map.put("safePhonenumber", "");
                }
            }
            // 转换为 LocalDate 获取年份
            int year = reportHiYlgd.getCheckDate().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate()
                    .getYear();
            reportHiYlgd.setYearReportNo(reportHiYlgd.getPlantCode() + "-"+ year +  "-" + reportHiYlgd.getYearReportNo());
            map.put("reportHiYlgd", reportHiYlgd);
            TReportYlgd reportYlgd = tReportYlgdService.selectTReportYlgdById(reportHiYlgd.getReportId());
            TSpecdevYlgd devYlgd = tSpecdevYlgdService.selectTSpecdevYlgdById(reportYlgd.getDevId());
            map.put("devYlgd", devYlgd);
            if (reportHiYlgd.getCheckDate() != null) {
                map.put("checkDate", sdf.format(reportHiYlgd.getCheckDate()));
            }
            if (reportYlgd.getNextWarnDate() != null) {
                String[] nextWarnDateGD = sdf.format(reportYlgd.getNextWarnDate()).split("-");
                map.put("nextWarnDateYear", nextWarnDateGD[0]);
                map.put("nextWarnDateMonth", nextWarnDateGD[1]);
            }
            if (reportHiYlgd.getNextCheckDate() != null) {
                String[] nextCheckDateGD = sdf.format(reportHiYlgd.getNextCheckDate()).split("-");
                map.put("nextCheckDateYear", nextCheckDateGD[0]);
                map.put("nextCheckDateMonth", nextCheckDateGD[1]);
            }
            HistoricTaskInstanceQuery htiq = historyService.createHistoricTaskInstanceQuery();
            List<HistoricTaskInstance> htiLists = htiq.processInstanceId(reportHiYlgd.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 (reportHiYlgd.getCheckDate()!= null) {
                check = sdf.format(reportHiYlgd.getCheckDate());
            }
            String pdfName = reportHiYlgd.getPlantCode()
                    + "-" + check
                    + "-" + reportHiYlgd.getDevno()
                    + "-压力管道年度检查报告" +reportHiYlgd.getId() + ".pdf"
                    .replace(" ", "")
                    .replace("\\s", "")
                    .replace("\n", "");
            pdfName = FileUtils.isValidFilenameAndReplace(pdfName); //验证合规
            // 生成PDF文件
            PDFTemplateUtil.createPdf("yearYlgdFMaker.ftl", pdfName,
                    RuoYiConfig.getProfile() + "/reportHiYlgd/" ,
                    "file:" + RuoYiConfig.getProfile(), map, response);
            reportHiYlgd.setReportUrl(pdfName);
            tReportHiYlgdService.updateTReportHiYlgd(reportHiYlgd);
            return Constants.RESOURCE_PREFIX + "/" + "/reportHiYlgd/"  + 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");
            //
            TReportHiYlgd hiYlgd = new TReportHiYlgd();
            Map param = new HashMap();
            param.put("year" , year);
            hiYlgd.setParams(param);
            List<TReportHiYlgd> tReportHiYlgds = this.tReportHiYlgdService.selectTReportHiYlgdForYear(hiYlgd);
            List<SysDictData> con = iSysDictTypeService.selectDictDataByType("REPORT_CON");
            //使用当前时间作为文件夹，所有文件保存在当中
            long now = System.currentTimeMillis();
            //存放所有pdf文件路径
            List<String> list = new ArrayList<>();
            for (TReportHiYlgd tReportHiYlgd : tReportHiYlgds) {
                if (tReportHiYlgd.getReportUrl()!= null) {
                    list.add(tReportHiYlgd.getReportUrl());
                    continue;
                }
                if (StringUtils.isNotEmpty(tReportHiYlgd.getCon())) {
                    for (SysDictData c : con) {
                        if (tReportHiYlgd.getCon().equals(c.getDictValue())) {
                            tReportHiYlgd.setCon(c.getDictLabel());
                        }
                    }
                }
                if (StringUtils.isNotEmpty(tReportHiYlgd.getPlantCode())) {
                    SysUser sysUser = this.iSysUserService.selectSafeManagerUserByPlantCode(tReportHiYlgd.getPlantCode());
                    if (sysUser != null) {
                        map.put("safeUserName", sysUser.getNickName());
                        map.put("safePhonenumber", sysUser.getPhonenumber());
                    } else {
                        map.put("safeUserName", "");
                        map.put("safePhonenumber", "");
                    }
                }
                // 转换为 LocalDate 获取年份
                int year2 = tReportHiYlgd.getCheckDate().toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDate()
                        .getYear();
                tReportHiYlgd.setYearReportNo(tReportHiYlgd.getPlantCode() + "-"+ year2 +  "-" + tReportHiYlgd.getYearReportNo());
                map.put("reportHiYlgd", tReportHiYlgd);
                TReportYlgd reportYlgd = tReportYlgdService.selectTReportYlgdById(tReportHiYlgd.getReportId());
                //如果出现无法获取的基础数据，可能是以往的脏数据，选择跳过当前数据项
                if(reportYlgd == null){
                    continue;
                }
                TSpecdevYlgd devYlgd = tSpecdevYlgdService.selectTSpecdevYlgdById(reportYlgd.getDevId());
                map.put("devYlgd", devYlgd);
                if (tReportHiYlgd.getCheckDate() != null) {
                    map.put("checkDate", sdf.format(tReportHiYlgd.getCheckDate()));
                }
                if (tReportHiYlgd.getNextWarnDate() != null) {
                    String[] nextWarnDateGD = sdf.format(tReportHiYlgd.getNextWarnDate()).split("-");
                    map.put("nextWarnDateYear", nextWarnDateGD[0]);
                    map.put("nextWarnDateMonth", nextWarnDateGD[1]);
                }
                if (tReportHiYlgd.getNextCheckDate() != null) {
                    String[] nextCheckDateGD = sdf.format(tReportHiYlgd.getNextCheckDate()).split("-");
                    map.put("nextCheckDateYear", nextCheckDateGD[0]);
                    map.put("nextCheckDateMonth", nextCheckDateGD[1]);
                }
                HistoricTaskInstanceQuery htiq = historyService.createHistoricTaskInstanceQuery();
                List<HistoricTaskInstance> htiLists = htiq.processInstanceId(tReportHiYlgd.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 pdfName = tReportHiYlgd.getPlantCode()
                        + "-" + sdf.format(tReportHiYlgd.getCheckDate())
                        + "-" + tReportHiYlgd.getDevno()
                        + "-压力管道年度检查报告" +tReportHiYlgd.getId() + ".pdf"
                        .replace(" ", "")
                        .replace("\\s", "")
                        .replace("\n", "");
                pdfName = FileUtils.isValidFilenameAndReplace(pdfName); //验证合规
                // 生成PDF文件
                PDFTemplateUtil.createPdf("yearYlgdFMaker.ftl", pdfName,
                        RuoYiConfig.getProfile() + "/reportHiYlgd/",
                        "file:" + RuoYiConfig.getProfile(), map, response);
                tReportHiYlgd.setReportUrl(pdfName);
                tReportHiYlgdService.updateTReportHiYlgd(tReportHiYlgd);
                list.add(pdfName);
            }
            ZipUtil.createZip(RuoYiConfig.getProfile() + "/reportHiYlgd/", "", year + "年压力管道年度检查历史报告.zip", list, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }
}
