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.TRestrictedSpacePermit;
import com.ruoyi.project.ticket.domain.TTicketId;
import com.ruoyi.project.ticket.service.ITPermitRelationService;
import com.ruoyi.project.ticket.service.ITRestrictedSpacePermitService;
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.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-05
 */
@RestController
@RequestMapping("/ticket/restrictedspace")
public class TRestrictedSpacePermitController extends BaseController
{
    @Autowired
    private ITRestrictedSpacePermitService tRestrictedSpacePermitService;

    @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(TRestrictedSpacePermit tRestrictedSpacePermit)
    {
        startPage();
        List<TRestrictedSpacePermit> list = tRestrictedSpacePermitService.selectTRestrictedSpacePermitList(tRestrictedSpacePermit);
        return getDataTable(list);
    }

    /**
     * 导出限制性空间进入开票列表
     */
    @Log(title = "限制性空间进入开票", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TRestrictedSpacePermit tRestrictedSpacePermit)
    {
        List<TRestrictedSpacePermit> list = tRestrictedSpacePermitService.selectTRestrictedSpacePermitList(tRestrictedSpacePermit);
        ExcelUtil<TRestrictedSpacePermit> util = new ExcelUtil<TRestrictedSpacePermit>(TRestrictedSpacePermit.class);
        return util.exportExcel(list, "permit");
    }

    /**
     * 获取限制性空间进入开票详细信息
     */
    @GetMapping(value = "/{cId}")
    public AjaxResult getInfo(@PathVariable("cId") Long cId)
    {
        return AjaxResult.success(tRestrictedSpacePermitService.selectTRestrictedSpacePermitById(cId));
    }

    /**
     * 新增限制性空间进入开票
     */
    @Log(title = "限制性空间进入开票", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TRestrictedSpacePermit tRestrictedSpacePermit) throws IOException {
        //生成票号
        TTicketId tTicketId = new TTicketId();
        tTicketId.setId(1l);
        Long ticketId = tTicketIdController.createId(tTicketId);
        //保存限制空间许可证
        tRestrictedSpacePermit.setcId(ticketId);
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(tRestrictedSpacePermit);
        // 模板路径
        String templatePath = "static/word/restrictedSpaceTicket.docx";
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "ticketWord";;
        // 生成word的文件
        String fileName = "C" + ticketId + ".docx";
        String wordPath = this.wordController.createWord(templatePath, fileDir, fileName, params);
        tRestrictedSpacePermit.setWordUrl(wordPath);
        //使用流的方式转换PDF
        String fileName2 = "C" + tRestrictedSpacePermit.getcId() + ".pdf";
        String pdfPath = this.wordController.createPDF(fileDir, fileName, fileName2, params);
        tRestrictedSpacePermit.setPdfUrl(pdfPath);
        tRestrictedSpacePermitService.insertTRestrictedSpacePermit(tRestrictedSpacePermit);
        //返回票号
        return AjaxResult.success(tRestrictedSpacePermit.getcId());
    }

    /**
     * 修改限制性空间进入开票
     */
    @Log(title = "限制性空间进入开票", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TRestrictedSpacePermit tRestrictedSpacePermit) throws IOException {
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(tRestrictedSpacePermit);
        // 模板路径
        String templatePath = "static/word/restrictedSpaceTicket.docx";
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "ticketWord";
        // 生成word的文件
        String fileName = "C" + tRestrictedSpacePermit.getcId() + ".docx";
        String wordPath = this.wordController.createWord(templatePath, fileDir, fileName, params);
        tRestrictedSpacePermit.setWordUrl(wordPath);
        //使用流的方式转换PDF
        String fileName2 = "C" + tRestrictedSpacePermit.getcId() + ".pdf";
        String pdfPath = this.wordController.createPDF(fileDir, fileName, fileName2, params);
        tRestrictedSpacePermit.setPdfUrl(pdfPath);
        return toAjax(tRestrictedSpacePermitService.updateTRestrictedSpacePermit(tRestrictedSpacePermit));
    }

    /**
     * 删除限制性空间进入开票
     */
    @Log(title = "限制性空间进入开票", businessType = BusinessType.DELETE)
	@DeleteMapping("/{cIds}")
    public AjaxResult remove(@PathVariable Long[] cIds)
    {
        return toAjax(tRestrictedSpacePermitService.deleteTRestrictedSpacePermitByIds(cIds));
    }


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

}
