package com.ruoyi.project.ticket.controller;

import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.data.Texts;
import com.deepoove.poi.data.style.Style;
import com.ruoyi.common.utils.DateUtils;
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.common.controller.WordController;
import com.ruoyi.project.configuration.domain.TMatter;
import com.ruoyi.project.configuration.mapper.TMatterMapper;
import com.ruoyi.project.ticket.domain.PermitRelation;
import com.ruoyi.project.ticket.domain.TPermitFireWork;
import com.ruoyi.project.ticket.domain.THazardWorkPermit;
import com.ruoyi.project.ticket.domain.TTicketId;
import com.ruoyi.project.ticket.service.ITPermitFireWorkService;
import com.ruoyi.project.ticket.service.ITHazardWorkPermitService;
import com.ruoyi.project.ticket.service.ITPermitRelationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 危害工作许可证Controller
 *
 * @author ruoyi
 * @date 2021-10-25
 */
@RestController
@RequestMapping("/ticket/hazardworks")
public class THazardWorkPermitController extends BaseController {

    @Autowired
    private ITHazardWorkPermitService tHazardWorkPermitService;
    @Autowired
    private ITPermitFireWorkService tPermitFireWorkService;
    @Autowired
    private ITPermitRelationService itPermitRelationService;
    @Autowired
    private TTicketIdController tTicketIdController;
    @Autowired
    private WordController wordController;
    @Resource
    private TMatterMapper tMatterMapper;

    /**
     * 查询危害工作许可证列表
     */
    @GetMapping("/list")
    public TableDataInfo list(THazardWorkPermit tHazardWorkPermit) {
        startPage();
        List<THazardWorkPermit> list = tHazardWorkPermitService.selectTHazardWorkPermitList(tHazardWorkPermit);
        for (THazardWorkPermit t : list) {
            if (t.gethVNoOne() != null) {
                List<THazardWorkPermit> l = new ArrayList<>();
                THazardWorkPermit tt = new THazardWorkPermit();
                BeanUtils.copyProperties(t, tt);
                l.add(tt);
                l.add(tt);
                l.add(tt);
                l.add(tt);
                l.add(tt);
                int i = 1;
                List<THazardWorkPermit> l2 = new ArrayList<>();
                for (THazardWorkPermit th : l) {
                    THazardWorkPermit tt2 = new THazardWorkPermit();
                    BeanUtils.copyProperties(th, tt2);
                    tt2.sethVNoOne(Long.parseLong(String.valueOf(th.gethVNoOne()) + i++));
                    l2.add(tt2);
                }
                t.setChildren(l2);
            }
            if (t.gethVNoTwo() != null) {
                List<THazardWorkPermit> l = new ArrayList<>();
                THazardWorkPermit tt = new THazardWorkPermit();
                BeanUtils.copyProperties(t, tt);
                l.add(tt);
                t.setChildren(l);
            }
            if (t.gethVNoThree() != null) {
                List<THazardWorkPermit> l = new ArrayList<>();
                THazardWorkPermit tt = new THazardWorkPermit();
                BeanUtils.copyProperties(t, tt);
                l.add(tt);
                t.setChildren(l);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出危害工作许可证列表
     */
    @Log(title = "危害工作许可证", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(THazardWorkPermit tHazardWorkPermit) {
        List<THazardWorkPermit> list = tHazardWorkPermitService.selectTHazardWorkPermitList(tHazardWorkPermit);
        ExcelUtil<THazardWorkPermit> util = new ExcelUtil<THazardWorkPermit>(THazardWorkPermit.class);
        return util.exportExcel(list, "permit");
    }

    /**
     * 获取危害工作许可证详细信息
     */
    @GetMapping(value = "/{aId}")
    public AjaxResult getInfo(@PathVariable("aId") Long aId) {
        return AjaxResult.success(tHazardWorkPermitService.selectTHazardWorkPermitById(aId));
    }

    /**
     * 新增危害工作许可证
     */
    @Log(title = "危害工作许可证", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody THazardWorkPermit tHazardWorkPermit) throws IOException {
        TTicketId tTicketId = new TTicketId();
        tTicketId.setId(1l);
        Long ticketId = tTicketIdController.createId(tTicketId);
        logger.info("ticketId:" + ticketId);
        tHazardWorkPermit.setaId(ticketId);
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(tHazardWorkPermit);
        // 模板路径
        String templatePath = "static/word/ticket.docx";
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "ticketWord";;
        // 生成word的文件
        String fileName = "A" + ticketId + ".docx";
        String wordPath = this.wordController.createWord(templatePath, fileDir, fileName, params);
        tHazardWorkPermit.setWordUrl(wordPath);
        //使用流的方式转换PDF
        String fileName2 = "A" + tHazardWorkPermit.getaId() + ".pdf";
        String pdfPath = this.wordController.createPDF(fileDir, fileName, fileName2, params);
        tHazardWorkPermit.setPdfUrl(pdfPath);

        tHazardWorkPermitService.insertTHazardWorkPermit(tHazardWorkPermit);
        //保存危害工作许可证关联数据
        PermitRelation permitRelation = new PermitRelation();
        permitRelation.setPermitId(tHazardWorkPermit.getaId());
        permitRelation.setPermitType("A");
        permitRelation.setPermitStatus(1L);
        this.itPermitRelationService.add(permitRelation);
        return AjaxResult.success(tHazardWorkPermit.getaId());
    }

    /**
     * 新增危害工作许可证
     */
    @Log(title = "关联火票", businessType = BusinessType.INSERT)
    @PostMapping("/addFire")
    public AjaxResult addFire(@RequestBody THazardWorkPermit tHazardWorkPermit) throws IOException {
        TTicketId tTicketId = new TTicketId();
        tTicketId.setId(2l);
        Long ticketId = tTicketIdController.createId(tTicketId);
        logger.info("生成的ticketId:" + ticketId);
        tHazardWorkPermit.setcHId(ticketId);
        tHazardWorkPermitService.updateTHazardWorkPermit(tHazardWorkPermit);
        //生成火票信息
        TPermitFireWork tPermitFireWork = new TPermitFireWork();
        tPermitFireWork.sethId(ticketId);
        tPermitFireWork.setaEquipmentName(tHazardWorkPermit.getaEquipmentName());
        tPermitFireWork.setaEquipmentLeader(tHazardWorkPermit.getaEquipmentLeader());
        tPermitFireWork.setaEquipmentTel(tHazardWorkPermit.getaEquipmentTel());
        tPermitFireWork.setaEquipmentOffice(tHazardWorkPermit.getaEquipmentOffice());
        tPermitFireWork.setaConstructionName(tHazardWorkPermit.getaConstructionName());
        tPermitFireWork.setaConstructionLeader(tHazardWorkPermit.getaConstructionLeader());
        tPermitFireWork.setaConstructionTel(tHazardWorkPermit.getaConstructionTel());
        tPermitFireWork.setaConstructionOffice(tHazardWorkPermit.getaConstructionOffice());
        tPermitFireWork.setaContractorName(tHazardWorkPermit.getaContractorName());
        tPermitFireWork.setaContractorLeader(tHazardWorkPermit.getaContractorLeader());
        tPermitFireWork.setaContractorTel(tHazardWorkPermit.getaContractorTel());
        tPermitFireWork.setaContractorOffice(tHazardWorkPermit.getaContractorOffice());
        tPermitFireWork.setaIsNeedSafeLiaison(tHazardWorkPermit.getaIsNeedSafeLiaison());
        tPermitFireWork.setaSafeLiaisonName(tHazardWorkPermit.getaSafeLiaisonName());
        tPermitFireWork.setaSafeLiaisonSign(tHazardWorkPermit.getaSafeLiaisonSign());
        tPermitFireWork.setaSafeLiaisonTel(tHazardWorkPermit.getaSafeLiaisonTel());
        tPermitFireWork.setaSafeLiaisonOffice(tHazardWorkPermit.getaSafeLiaisonOffice());
        tPermitFireWork.setbDeviceName(tHazardWorkPermit.getbDeviceName());
        tPermitFireWork.setbAreaNo(tHazardWorkPermit.getbAreaNo());
        tPermitFireWork.setbWorkContent(tHazardWorkPermit.getbWorkContent());
        tPermitFireWork.setbValidityStartTime(tHazardWorkPermit.getbValidityStartTime());
        tPermitFireWork.setbValidityEndTime(tHazardWorkPermit.getbValidityEndTime());
        tPermitFireWorkService.insertTPermitFireWork(tPermitFireWork);
        //保存危害工作许可证关联数据
        PermitRelation permitRelation = new PermitRelation();
        permitRelation.setPermitId(tPermitFireWork.gethId());
        permitRelation.setPermitType("H");
        permitRelation.setPermitStatus(1L);
        this.itPermitRelationService.add(permitRelation);
        return AjaxResult.success(tHazardWorkPermit.getcHId());
    }

    /**
     * 修改危害工作许可证
     */
    @Log(title = "危害工作许可证", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody THazardWorkPermit tHazardWorkPermit) throws IOException {
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(tHazardWorkPermit);
        // 模板路径
        String templatePath = "static/word/ticket.docx";
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "ticketWord";
        // 生成word的文件
        String fileName = "A" + tHazardWorkPermit.getaId() + ".docx";
        String wordPath = this.wordController.createWord(templatePath, fileDir, fileName, params);
        tHazardWorkPermit.setWordUrl(wordPath);
        //使用流的方式转换PDF
        String fileName2 = "A" + tHazardWorkPermit.getaId() + ".pdf";
        String pdfPath = this.wordController.createPDF(fileDir, fileName, fileName2, params);
        tHazardWorkPermit.setPdfUrl(pdfPath);
        return toAjax(tHazardWorkPermitService.updateTHazardWorkPermit(tHazardWorkPermit));
    }

    /**
     * 删除危害工作许可证
     */
    @Log(title = "危害工作许可证", businessType = BusinessType.DELETE)
    @DeleteMapping("/{aIds}")
    public AjaxResult remove(@PathVariable Long[] aIds) {
        return toAjax(tHazardWorkPermitService.deleteTHazardWorkPermitByIds(aIds));
    }

    public Map<String, Object> getWordData(THazardWorkPermit tHazardWorkPermit) {
        Map<String, Object> params = new HashMap<>();
        // 渲染文本
        params.put("aId", Texts.of(tHazardWorkPermit.getaId().toString()).fontSize(7).bold().create());
        params.put("aEquipmentName", Texts.of(tHazardWorkPermit.getaEquipmentName()).fontSize(7).bold().create());
        params.put("aEquipmentLeader", Texts.of(tHazardWorkPermit.getaEquipmentLeader()).fontSize(7).bold().create());
        params.put("aEquipmentTel", Texts.of(tHazardWorkPermit.getaEquipmentTel()).fontSize(7).bold().create());
        params.put("aEquipmentOffice", Texts.of(tHazardWorkPermit.getaEquipmentOffice()).fontSize(7).bold().create());
        params.put("aConstructionName", Texts.of(tHazardWorkPermit.getaConstructionName()).fontSize(7).bold().create());
        params.put("aConstructionLeader", Texts.of(tHazardWorkPermit.getaConstructionLeader()).fontSize(7).bold().create());
        params.put("aConstructionTel", Texts.of(tHazardWorkPermit.getaConstructionTel()).fontSize(7).bold().create());
        params.put("aConstructionOffice", Texts.of(tHazardWorkPermit.getaConstructionOffice()).fontSize(7).bold().create());
        params.put("aContractorName", Texts.of(tHazardWorkPermit.getaContractorName()).fontSize(7).bold().create());
        params.put("aContractorLeader", Texts.of(tHazardWorkPermit.getaContractorLeader()).fontSize(7).bold().create());
        params.put("aContractorTel", Texts.of(tHazardWorkPermit.getaContractorTel()).fontSize(7).bold().create());
        params.put("aContractorOffice", Texts.of(tHazardWorkPermit.getaContractorOffice()).fontSize(7).bold().create());

        getCheck(params, tHazardWorkPermit.getaIsNeedSafeLiaison().toString(), "aIsNSL1", "aIsNSL2");
        params.put("aSafeLiaisonName", Texts.of(tHazardWorkPermit.getaSafeLiaisonName()).fontSize(7).bold().create());
        params.put("aSafeLiaisonSign", Texts.of(tHazardWorkPermit.getaSafeLiaisonSign()).fontSize(7).bold().create());
        params.put("aSafeLiaisonTel", Texts.of(tHazardWorkPermit.getaSafeLiaisonTel()).fontSize(7).bold().create());
        params.put("aSafeLiaisonOffice", Texts.of(tHazardWorkPermit.getaSafeLiaisonOffice()).fontSize(7).bold().create());
        // B 栏
        params.put("bDeviceName", Texts.of(tHazardWorkPermit.getbDeviceName()).fontSize(7).bold().create());
        params.put("bAreaNo", Texts.of(tHazardWorkPermit.getbAreaNo()).fontSize(7).bold().create());
        params.put("bWorkContent", Texts.of(tHazardWorkPermit.getbWorkContent()).fontSize(7).bold().create());
        if (tHazardWorkPermit.getbValidityStartTime() != null) {
            params.put("bValidityStartTime", Texts.of(DateUtils.parseDateToStr("yyyy年MM月dd日hh时mm分", tHazardWorkPermit.getbValidityStartTime())).fontSize(7).bold().create());
        }
        if (tHazardWorkPermit.getbValidityEndTime() != null) {
            params.put("bValidityEndTime", Texts.of(DateUtils.parseDateToStr("yyyy年MM月dd日hh时mm分", tHazardWorkPermit.getbValidityEndTime())).fontSize(7).bold().create());
        }
        // C 栏
        getCheck(params, tHazardWorkPermit.getcIsDanger(), "cIsDanger");
        List<TMatter> tMatters = tMatterMapper.selectTMatterList(new TMatter());
        for (TMatter t : tMatters
        ) {
            if (t.getId().toString().equals(tHazardWorkPermit.getcHarmMatterName())) {
                params.put("cHarmMatterName", Texts.of(t.getMatterName()).fontSize(7).bold().create());
            }
        }
        getCheck(params, tHazardWorkPermit.getcIsAttention(), "cIsAttention");
        getCheck(params, tHazardWorkPermit.getcIsToxic(), "cIsToxic");
        getCheck(params, tHazardWorkPermit.getcIsFlammable(), "cIsFlammable");
        getCheck(params, tHazardWorkPermit.getcIsOxidizing(), "cIsOxidizing");
        getCheck(params, tHazardWorkPermit.getcIsExplosive(), "cIsExplosive");
        getCheck(params, tHazardWorkPermit.getcIsCorrosive(), "cIsCorrosive");
        getCheck(params, tHazardWorkPermit.getcIsIrritantToxic(), "cIsIrritantToxic");
        getCheck(params, tHazardWorkPermit.getcIsHealthHazard(), "cIsHealthHazard");
        getCheck(params, tHazardWorkPermit.getcIsCompressedGas(), "cIsCompressedGas");
        getCheck(params, tHazardWorkPermit.getcIsEnvironmentalHazard(), "cIsEnvironmentalHazard");
        //设备内物质处于危险状态（{{cIsHighTemp}}高温/{{cIsLowTemp}}低温；{{cIsPosPressure}}正压/{{cIsNegPressure}}负压
        getCheck(params, tHazardWorkPermit.getcIsHighTemp(), "cIsHighTemp");
        getCheck(params, tHazardWorkPermit.getcIsLowTemp(), "cIsLowTemp");
        getCheck(params, tHazardWorkPermit.getcIsPosPressure(), "cIsPosPressure");
        getCheck(params, tHazardWorkPermit.getcIsNegPressure(), "cIsNegPressure");
        if ("1".equals(tHazardWorkPermit.getcIsHighTemp()) || "1".equals(tHazardWorkPermit.getcIsLowTemp()) || "1".equals(tHazardWorkPermit.getcIsPosPressure()) || "1".equals(tHazardWorkPermit.getcIsHighTemp())) {
            getCheck(params, "1", "isFacilityHazards");
        } else {
            getCheck(params, "2", "isFacilityHazards");
        }
        //来自设备/设施的危害（{{cIsMovingParts}}移动部件，{{cIsHotSurfaces}}热表面/ {{cIsColdSurfaces}}冷表面，{{cIsVoltages}}电压）
        getCheck(params, tHazardWorkPermit.getcIsMovingParts(), "cIsMovingParts");
        getCheck(params, tHazardWorkPermit.getcIsHotSurfaces(), "cIsHotSurfaces");
        getCheck(params, tHazardWorkPermit.getcIsColdSurfaces(), "cIsColdSurfaces");
        getCheck(params, tHazardWorkPermit.getcIsVoltages(), "cIsVoltages");
        if ("1".equals(tHazardWorkPermit.getcIsMovingParts()) || "1".equals(tHazardWorkPermit.getcIsHotSurfaces()) || "1".equals(tHazardWorkPermit.getcIsColdSurfaces()) || "1".equals(tHazardWorkPermit.getcIsVoltages())) {
            getCheck(params, "1", "isEquipmentHazards");
        } else {
            getCheck(params, "2", "isEquipmentHazards");
        }
        //{{cIsWorkProtective}} 安全保护设备的施工（{{cIsDy}}电仪安全保护设备，{{cIsAqf}}安全阀，{{cIsLq}}冷却系统）
        getCheck(params, tHazardWorkPermit.getcIsWorkProtective(), "cIsWorkProtective");
        getCheck(params, tHazardWorkPermit.getcIsDy(), "cIsDy");
        getCheck(params, tHazardWorkPermit.getcIsAqf(), "cIsAqf");
        getCheck(params, tHazardWorkPermit.getcIsLq(), "cIsLq");
        //{{cIsOtherDanger}} 其它危害：{{cOtherDangerContent}}
        getCheck(params, tHazardWorkPermit.getcIsOtherDanger(), "cIsOtherDanger");
        params.put("cOtherDangerContent", Texts.of(tHazardWorkPermit.getcOtherDangerContent()).fontSize(7).bold().create());
        //{{cIsHazardsProd}}	施工对生产单位的危害：{{cIsHazardsProdContent}}
        getCheck(params, tHazardWorkPermit.getcIsHazardsProd(), "cIsHazardsProd");
        params.put("cIsHazardsProdContent", Texts.of(tHazardWorkPermit.getcIsHazardsProdContent()).fontSize(7).bold().create());
        //D 栏
        // 1.1是否通过打开安全开关断电并上锁和运转测试
        getCheck(params, tHazardWorkPermit.getdIsOpenSafe(), "dIsOpenSafe", "dIsOpenSafe2");
        // 1.2
        getCheck(params, tHazardWorkPermit.getdIsDisFeeder(), "dIsDisFeeder", "dIsDisFeeder2");
        params.put("dBreakInclContent", Texts.of(tHazardWorkPermit.getdBreakInclContent()).fontSize(7).bold().create());
        params.put("dEleCircuitNo", Texts.of(tHazardWorkPermit.getdEleCircuitNo()).fontSize(7).bold().create());
        // 1.3
        getCheck(params, tHazardWorkPermit.getdIsRadioactiveSources(), "dIsRadioactiveSources", "dIsRadioactiveSources2");
        //E 栏
            //1.是否可能有残留物料
        getCheck(params, tHazardWorkPermit.geteIsPresent(), "eIsPresent", "eIsPresent2");
        getCheck(params, tHazardWorkPermit.geteIsRequiredPpe(), "eIsRequiredPpe", "eIsRequiredPpe2");
            //2.项目内容"
        params.put("ePpeContent", Texts.of(tHazardWorkPermit.getePpeContent()).fontSize(7).bold().create());
        getCheck(params, tHazardWorkPermit.geteIsSafeGoggles(), "eIsSafeGoggles", "eIsSafeGoggles2");
        getCheck(params, tHazardWorkPermit.geteIsFaceShield(), "eIsFaceShield", "eIsFaceShield2");
        getCheck(params, tHazardWorkPermit.geteIsProtectGloves(), "eIsProtectGloves", "eIsProtectGloves2");
        params.put("eProtectGlovesContent", Texts.of(tHazardWorkPermit.geteProtectGlovesContent()).fontSize(7).bold().create());

        getCheck(params, tHazardWorkPermit.geteIsRubberBoots(), "eIsRubberBoots", "eIsRubberBoots2");
        getCheck(params, tHazardWorkPermit.geteIsRubberApron(), "eIsRubberApron", "eIsRubberApron2");
        getCheck(params, tHazardWorkPermit.geteIsProtectSuit(), "eIsProtectSuit", "eIsProtectSuit2");
        params.put("eProtectSuitContent", Texts.of(tHazardWorkPermit.geteProtectSuitContent()).fontSize(7).bold().create());
            //2.7是否呼吸保护用品
        getCheck(params, tHazardWorkPermit.geteIsResProtect(), "eIsResProtect", "eIsResProtect2");
        params.put("eResProtectContent", Texts.of(tHazardWorkPermit.geteResProtectContent()).fontSize(7).bold().create());
        getCheck(params, tHazardWorkPermit.geteIsFallArrest(), "eIsFallArrest", "eIsFallArrest2");
        params.put("eFallArrestContent", Texts.of(tHazardWorkPermit.geteFallArrestContent()).fontSize(7).bold().create());
            //2.9
        getCheck(params, tHazardWorkPermit.geteIsOtherProtect(), "eIsOtherProtect", "eIsOtherProtect2");
        params.put("eOtherProtectContent", Texts.of(tHazardWorkPermit.geteOtherProtectContent()).fontSize(7).bold().create());
            //3.是否连续监控
        getCheck(params, tHazardWorkPermit.geteIsContinueMonitoring(), "eIsContinueMonitoring", "eIsContinueMonitoring2");

        return params;
    }

    // 勾选框判断渲染
    public void getCheck(Map<String, Object> params, String ticketWord, String check1) {
        if ("1".equals(ticketWord)) {
            params.put(check1, new TextRenderData("\u00FE", new Style("Wingdings", 7)));
        } else if ("2".equals(ticketWord)) {
            params.put(check1, new TextRenderData("\u006F", new Style("Wingdings", 7)));
        } else {
            params.put(check1, new TextRenderData("\u006F", new Style("Wingdings", 7)));
        }
    }

    // 勾选框判断渲染
    public void getCheck(Map<String, Object> params, String ticketWord, String check1, String check2) {
        if ("1".equals(ticketWord)) {
            params.put(check1, new TextRenderData("\u00FE", new Style("Wingdings", 7)));
            params.put(check2, new TextRenderData("\u006F", new Style("Wingdings", 7)));
        } else if ("2".equals(ticketWord)) {
            params.put(check1, new TextRenderData("\u006F", new Style("Wingdings", 7)));
            params.put(check2, new TextRenderData("\u00FE", new Style("Wingdings", 7)));
        } else {
            params.put(check1, new TextRenderData("\u006F", new Style("Wingdings", 7)));
            params.put(check2, new TextRenderData("\u006F", new Style("Wingdings", 7)));
        }
    }

}
