package com.ruoyi.project.ticket.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.framework.config.RuoYiConfig;
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.configuration.service.ITMatterProtectService;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.ticket.domain.PermitRelation;
import com.ruoyi.project.ticket.domain.TTicketId;
import com.ruoyi.project.ticket.service.ITPermitRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.ticket.domain.TPermitBlindPlate;
import com.ruoyi.project.ticket.service.ITPermitBlindPlateService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 盲板抽堵工作票Controller
 *
 * @author ruoyi
 * @date 2023-05-11
 */
@RestController
@RequestMapping("/ticket/blindplate")
public class TPermitBlindPlateController extends BaseController
{
    @Autowired
    private ITPermitBlindPlateService tPermitBlindPlateService;

    @Autowired
    private TTicketIdController tTicketIdController;

    @Autowired
    private ITPermitRelationService itPermitRelationService;

    @Resource
    private TMatterMapper tMatterMapper;

    @Autowired
    private WordController wordController;

    @Autowired
    private ITMatterProtectService matterProtectService;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 查询盲板抽堵工作票列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TPermitBlindPlate tPermitBlindPlate)
    {
        startPage();
        List<TPermitBlindPlate> list = tPermitBlindPlateService.selectTPermitBlindPlateList(tPermitBlindPlate);
        return getDataTable(list);
    }

    /**
     * 导出盲板抽堵工作票列表
     */
    @Log(title = "盲板抽堵工作票", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPermitBlindPlate tPermitBlindPlate)
    {
        List<TPermitBlindPlate> list = tPermitBlindPlateService.selectTPermitBlindPlateList(tPermitBlindPlate);
        ExcelUtil<TPermitBlindPlate> util = new ExcelUtil<TPermitBlindPlate>(TPermitBlindPlate.class);
        return util.exportExcel(list, "blindplate");
    }

    /**
     * 获取盲板抽堵工作票详细信息
     */
    @GetMapping(value = "/{bpId}")
    public AjaxResult getInfo(@PathVariable("bpId") Long bpId)
    {
        return AjaxResult.success(tPermitBlindPlateService.selectTPermitBlindPlateById(bpId));
    }

    /**
     * 新增盲板抽堵工作票
     */
    @Log(title = "盲板抽堵工作票", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPermitBlindPlate tPermitBlindPlate) throws IOException {
        //生成票号
        TTicketId tTicketId = new TTicketId();
        tTicketId.setId(1l);
        Long ticketId = tTicketIdController.createId(tTicketId);
        //保存限制空间许可证
        tPermitBlindPlate.setBpId(ticketId);
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(tPermitBlindPlate);
        // 模板路径
        String templatePath = "static/word/blindPlateTicket.docx";
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "ticketWord";;
        // 生成word的文件
        String fileName = "BP" + ticketId + ".docx";
        String wordPath = this.wordController.createWord(templatePath, fileDir, fileName, params);
        tPermitBlindPlate.setWordUrl(wordPath);
        //使用流的方式转换PDF
        String fileName2 = "BP" + tPermitBlindPlate.getBpId() + ".pdf";
        String pdfPath = this.wordController.createPDF(fileDir, fileName, fileName2, params);
        tPermitBlindPlate.setPdfUrl(pdfPath);
        tPermitBlindPlateService.insertTPermitBlindPlate(tPermitBlindPlate);
        //返回票号
        return AjaxResult.success(tPermitBlindPlate.getBpId());
    }

    /**
     * 修改盲板抽堵工作票
     */
    @Log(title = "盲板抽堵工作票", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPermitBlindPlate tPermitBlindPlate) throws IOException {
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(tPermitBlindPlate);
        // 模板路径
        String templatePath = "static/word/blindPlateTicket.docx";
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "ticketWord";
        // 生成word的文件
        String fileName = "BP" + tPermitBlindPlate.getBpId() + ".docx";
        String wordPath = this.wordController.createWord(templatePath, fileDir, fileName, params);
        tPermitBlindPlate.setWordUrl(wordPath);
        //使用流的方式转换PDF
        String fileName2 = "BP" + tPermitBlindPlate.getBpId() + ".pdf";
        String pdfPath = this.wordController.createPDF(fileDir, fileName, fileName2, params);
        tPermitBlindPlate.setPdfUrl(pdfPath);
        return toAjax(tPermitBlindPlateService.updateTPermitBlindPlate(tPermitBlindPlate));
    }

    /**
     * 删除盲板抽堵工作票
     */
    @Log(title = "盲板抽堵工作票", businessType = BusinessType.DELETE)
	@DeleteMapping("/{bpIds}")
    public AjaxResult remove(@PathVariable Long[] bpIds)
    {
        return toAjax(tPermitBlindPlateService.deleteTPermitBlindPlateByIds(bpIds));
    }

    public Map<String, Object> getWordData(TPermitBlindPlate tPermitBlindPlate) {
        Map<String, Object> params = new HashMap<>();
        // 渲染文本
        params.put("bpId", Texts.of(tPermitBlindPlate.getBpId().toString()).fontSize(7).bold().create());
        // A栏
        params.put("aEquipmentName", Texts.of(tPermitBlindPlate.getaEquipmentName()).fontSize(7).bold().create());
        params.put("aEquipmentLeader", Texts.of(tPermitBlindPlate.getaEquipmentLeader()).fontSize(7).bold().create());
        params.put("aEquipmentTel", Texts.of(tPermitBlindPlate.getaEquipmentTel()).fontSize(7).bold().create());
        params.put("aEquipmentOffice", Texts.of(tPermitBlindPlate.getaEquipmentOffice()).fontSize(7).bold().create());
        params.put("aConstructionName", Texts.of(deptService.selectDeptById(Long.parseLong(tPermitBlindPlate.getaConstructionName())).getDeptName()).fontSize(7).bold().create());
        params.put("aConstructionLeader", Texts.of(tPermitBlindPlate.getaConstructionLeader()).fontSize(7).bold().create());
        params.put("aConstructionTel", Texts.of(tPermitBlindPlate.getaConstructionTel()).fontSize(7).bold().create());
        params.put("aConstructionOffice", Texts.of(tPermitBlindPlate.getaConstructionOffice()).fontSize(7).bold().create());
        params.put("aContractorName", Texts.of(tPermitBlindPlate.getaContractorName()).fontSize(7).bold().create());
        params.put("aContractorLeader", Texts.of(tPermitBlindPlate.getaContractorLeader()).fontSize(7).bold().create());
        params.put("aContractorTel", Texts.of(tPermitBlindPlate.getaContractorTel()).fontSize(7).bold().create());
        params.put("aContractorOffice", Texts.of(tPermitBlindPlate.getaContractorOffice()).fontSize(7).bold().create());
        getCheck(params, tPermitBlindPlate.getaIsNeedSafeLiaison().toString(), "aIsNSL1", "aIsNSL2");
        params.put("aSafeLiaisonName", Texts.of(tPermitBlindPlate.getaSafeLiaisonName()).fontSize(7).bold().create());
        params.put("aSafeLiaisonSign", Texts.of(tPermitBlindPlate.getaSafeLiaisonSign()).fontSize(7).bold().create());
        params.put("aSafeLiaisonTel", Texts.of(tPermitBlindPlate.getaSafeLiaisonTel()).fontSize(7).bold().create());
        params.put("aSafeLiaisonOffice", Texts.of(tPermitBlindPlate.getaSafeLiaisonOffice()).fontSize(7).bold().create());
        // B栏
        params.put("bDeviceName", Texts.of(tPermitBlindPlate.getbDeviceName()).fontSize(7).bold().create());
        params.put("bAreaNo", Texts.of(tPermitBlindPlate.getbAreaNo()).fontSize(7).bold().create());
        params.put("bWorkContent", Texts.of(tPermitBlindPlate.getbWorkContent()).fontSize(7).bold().create());
        if (tPermitBlindPlate.getbValidityStartTime() != null) {
            params.put("bValidityStartTime", Texts.of(DateUtils.parseDateToStr("yyyy年MM月dd日HH时mm分", tPermitBlindPlate.getbValidityStartTime())).fontSize(7).bold().create());
        }
        if (tPermitBlindPlate.getbValidityEndTime() != null) {
            params.put("bValidityEndTime", Texts.of(DateUtils.parseDateToStr("yyyy年MM月dd日HH时mm分", tPermitBlindPlate.getbValidityEndTime())).fontSize(7).bold().create());
        }
        // C 栏
        getCheck(params, tPermitBlindPlate.getcIsYesDanger(), "cIsYesDanger");
        List<TMatter> tMatters = tMatterMapper.selectTMatterList(new TMatter());
        for (TMatter t : tMatters
        ) {
            if (t.getId().toString().equals(tPermitBlindPlate.getcHarmMatterName())) {
                params.put("cHarmMatterName", Texts.of(t.getMatterName()).fontSize(7).bold().create());
            }
        }
        getCheck(params, tPermitBlindPlate.getcIsGhs(), "cIsGhs");
        getCheck(params, tPermitBlindPlate.getcIsToxic(), "cIsToxic");
        getCheck(params, tPermitBlindPlate.getcIsFlammable(), "cIsFlammable");
        getCheck(params, tPermitBlindPlate.getcIsOxidizing(), "cIsOxidizing");
        getCheck(params, tPermitBlindPlate.getcIsExplosive(), "cIsExplosive");
        getCheck(params, tPermitBlindPlate.getcIsCorrosive(), "cIsCorrosive");
        getCheck(params, tPermitBlindPlate.getcIsIrritantToxic(), "cIsIrritantToxic");
        getCheck(params, tPermitBlindPlate.getcIsHealthHazard(), "cIsHealthHazard");
        getCheck(params, tPermitBlindPlate.getcIsCompressedGas(), "cIsCompressedGas");
        getCheck(params, tPermitBlindPlate.getcIsEnvironmentalHazard(), "cIsEnvironmentalHazard");
        //设备内物质处于危险状态（{{cIsHighTemp}}高温/{{cIsLowTemp}}低温；{{cIsPosPressure}}正压/{{cIsNegPressure}}负压
        getCheck(params, tPermitBlindPlate.getcIsHighTemp(), "cIsHighTemp");
        getCheck(params, tPermitBlindPlate.getcIsLowTemp(), "cIsLowTemp");
        getCheck(params, tPermitBlindPlate.getcIsPosPressure(), "cIsPosPressure");
        getCheck(params, tPermitBlindPlate.getcIsNegPressure(), "cIsNegPressure");
        if ("1".equals(tPermitBlindPlate.getcIsHighTemp()) || "1".equals(tPermitBlindPlate.getcIsLowTemp()) || "1".equals(tPermitBlindPlate.getcIsPosPressure()) || "1".equals(tPermitBlindPlate.getcIsHighTemp())) {
            getCheck(params, "1", "isFacilityHazards");
        } else {
            getCheck(params, "2", "isFacilityHazards");
        }
        //来自设备/设施的危害（{{cIsMovingParts}}移动部件，{{cIsHotSurfaces}}热表面/ {{cIsColdSurfaces}}冷表面，{{cIsVoltages}}电压）
        getCheck(params, tPermitBlindPlate.getcIsMovingParts(), "cIsMovingParts");
        getCheck(params, tPermitBlindPlate.getcIsHotSurfaces(), "cIsHotSurfaces");
        getCheck(params, tPermitBlindPlate.getcIsColdSurfaces(), "cIsColdSurfaces");
        getCheck(params, tPermitBlindPlate.getcIsVoltages(), "cIsVoltages");
        if ("1".equals(tPermitBlindPlate.getcIsMovingParts()) || "1".equals(tPermitBlindPlate.getcIsHotSurfaces()) || "1".equals(tPermitBlindPlate.getcIsColdSurfaces()) || "1".equals(tPermitBlindPlate.getcIsVoltages())) {
            getCheck(params, "1", "isEquipmentHazards");
        } else {
            getCheck(params, "2", "isEquipmentHazards");
        }
        getCheck(params, tPermitBlindPlate.getcIsDrain(), "cIsDrain");
        getCheck(params, tPermitBlindPlate.getcIsFall(), "cIsFall");
        getCheck(params, tPermitBlindPlate.getcIsLighting(), "cIsLighting");
        getCheck(params, tPermitBlindPlate.getcIsRay(), "cIsRay");
        getCheck(params, tPermitBlindPlate.getcIsWorkProtective(), "cIsWorkProtective");
        //{{cIsOtherDanger}} 其它危害：{{cOtherDangerContent}}
        getCheck(params, tPermitBlindPlate.getcIsOtherDanger(), "cIsOtherDanger");
        params.put("cOtherDangerContent", Texts.of(tPermitBlindPlate.getcOtherDangerContent()).fontSize(7).bold().create());
        //{{cIsHazardsProd}}	施工对生产单位的危害：{{cIsHazardsProdContent}}
        getCheck(params, tPermitBlindPlate.getcIsHazardsProd(), "cIsHazardsProd");
        params.put("cIsHazardsProdContent", Texts.of(tPermitBlindPlate.getcIsHazardsProdContent()).fontSize(7).bold().create());
        //E 栏
        //1.是否可能有残留物料
        getCheck(params, tPermitBlindPlate.geteIsPresent(), "eIsPresent", "eIsPresent2");
        getCheck(params, tPermitBlindPlate.geteIsRequiredPpe(), "eIsRequiredPpe", "eIsRequiredPpe2");
        //2.项目内容"
        params.put("ePpeContent", Texts.of(tPermitBlindPlate.getePpeContent()).fontSize(7).bold().create());
        getCheck(params, tPermitBlindPlate.geteIsSafeGoggles(), "eIsSafeGoggles", "eIsSafeGoggles2");
        getCheck(params, tPermitBlindPlate.geteIsFaceShield(), "eIsFaceShield", "eIsFaceShield2");
        getCheck(params, tPermitBlindPlate.geteIsProtectGloves(), "eIsProtectGloves", "eIsProtectGloves2");
        if (tPermitBlindPlate.geteProtectGlovesContent() != null && !"0".equals(tPermitBlindPlate.geteProtectGlovesContent())) {
            params.put("eProtectGlovesContent", Texts.of(matterProtectService.selectTMatterProtectById(Long.parseLong(tPermitBlindPlate.geteProtectGlovesContent())).getConservatoryMeasureName()).fontSize(7).bold().create());
        }
        getCheck(params, tPermitBlindPlate.geteIsRubberBoots(), "eIsRubberBoots", "eIsRubberBoots2");
        getCheck(params, tPermitBlindPlate.geteIsRubberApron(), "eIsRubberApron", "eIsRubberApron2");
        getCheck(params, tPermitBlindPlate.geteIsProtectSuit(), "eIsProtectSuit", "eIsProtectSuit2");
        if (tPermitBlindPlate.geteProtectSuitContent() != null && !"0".equals(tPermitBlindPlate.geteProtectSuitContent())) {
            params.put("eProtectSuitContent", Texts.of(matterProtectService.selectTMatterProtectById(Long.parseLong(tPermitBlindPlate.geteProtectSuitContent())).getConservatoryMeasureName()).fontSize(7).bold().create());
        }
        //2.7是否呼吸保护用品
        getCheck(params, tPermitBlindPlate.geteIsResProtect(), "eIsResProtect", "eIsResProtect2");
        if (tPermitBlindPlate.geteResProtectContent() != null && !"0".equals(tPermitBlindPlate.geteResProtectContent())) {
            params.put("eResProtectContent", Texts.of(matterProtectService.selectTMatterProtectById(Long.parseLong(tPermitBlindPlate.geteResProtectContent())).getConservatoryMeasureName()).fontSize(7).bold().create());
        }
        //2.8
        getCheck(params, tPermitBlindPlate.geteIsOtherProtect(), "eIsOtherProtect", "eIsOtherProtect2");
        params.put("eOtherProtectContent", Texts.of(tPermitBlindPlate.geteOtherProtectContent()).fontSize(7).bold().create());
        //3
        params.put("eSafetySign1", Texts.of(tPermitBlindPlate.geteSafetySign1()).fontSize(7).bold().create());
        params.put("eSafetySign2", Texts.of(tPermitBlindPlate.geteSafetySign2()).fontSize(7).bold().create());
        //4.通风措施
        params.put("eNaturalVenContent", Texts.of(tPermitBlindPlate.geteNaturalVenContent()).fontSize(7).bold().create());
        params.put("eMecVenContent", Texts.of(tPermitBlindPlate.geteMecVenContent()).fontSize(7).bold().create());
        params.put("eAnalyzeAirContent", Texts.of(tPermitBlindPlate.geteAnalyzeAirContent()).fontSize(7).bold().create());
        params.put("eAnalyzeAirInterval", Texts.of(tPermitBlindPlate.geteAnalyzeAirInterval()).fontSize(7).bold().create());
        params.put("eOtherVenContent", Texts.of(tPermitBlindPlate.geteOtherVenContent()).fontSize(7).bold().create());
        getCheck(params, tPermitBlindPlate.geteIsNaturalVen(), "eIsNaturalVen", "eIsNaturalVen2");
        getCheck(params, tPermitBlindPlate.geteIsMecVen(), "eIsMecVen", "eIsMecVen2");
        getCheck(params, tPermitBlindPlate.geteIsExxtractDust(), "eIsExxtractDust", "eIsExxtractDust2");
        getCheck(params, tPermitBlindPlate.geteIsAnalyzeAir(), "eIsAnalyzeAir", "eIsAnalyzeAir2");
        getCheck(params, tPermitBlindPlate.geteIsOtherVen(), "eIsOtherVen", "eIsOtherVen2");
        //5
        getCheck(params, tPermitBlindPlate.geteOther1(), "eOther1", "eOther12");
        getCheck(params, tPermitBlindPlate.geteOther2(), "eOther2", "eOther22");
        getCheck(params, tPermitBlindPlate.geteOther3(), "eOther3", "eOther32");
        getCheck(params, tPermitBlindPlate.geteOther4(), "eOther4", "eOther42");
        getCheck(params, tPermitBlindPlate.geteIsOtherSafety(), "eIsOtherSafety", "eIsOtherSafety2");
        params.put("eOtherSafetyContent", Texts.of(tPermitBlindPlate.geteOtherSafetyContent()).fontSize(7).bold().create());
        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 ("0".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)));
        }
    }
}
