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.ticket.domain.PermitRelation;
import com.ruoyi.project.ticket.domain.THazardWorkPermit;
import com.ruoyi.project.ticket.domain.TTicketId;
import com.ruoyi.project.ticket.service.ITPermitRelationService;
import org.springframework.security.access.prepost.PreAuthorize;
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.TFireWorkPermit;
import com.ruoyi.project.ticket.service.ITFireWorkPermitService;
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 2022-02-23
 */
@RestController
@RequestMapping("/ticket/firework")
public class TFireWorkPermitController extends BaseController {
    @Autowired
    private ITFireWorkPermitService tFireWorkPermitService;
    @Autowired
    private WordController wordController;
    @Autowired
    private ITPermitRelationService itPermitRelationService;
    @Autowired
    private TTicketIdController tTicketIdController;
    @Resource
    private TMatterMapper tMatterMapper;

    /**
     * 查询【动火作业票】列表
     */
    @PreAuthorize("@ss.hasPermi('ticket:permit:list')")
    @GetMapping("/list")
    public TableDataInfo list(TFireWorkPermit tFireWorkPermit) {
        startPage();
        List<TFireWorkPermit> list = tFireWorkPermitService.selectTFireWorkPermitList(tFireWorkPermit);
        return getDataTable(list);
    }

    /**
     * 导出【动火作业票】列表
     */
    @PreAuthorize("@ss.hasPermi('ticket:permit:export')")
    @Log(title = "【动火作业票】", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TFireWorkPermit tFireWorkPermit) {
        List<TFireWorkPermit> list = tFireWorkPermitService.selectTFireWorkPermitList(tFireWorkPermit);
        ExcelUtil<TFireWorkPermit> util = new ExcelUtil<TFireWorkPermit>(TFireWorkPermit.class);
        return util.exportExcel(list, "permit");
    }

    /**
     * 获取【动火作业票】详细信息
     */
    @PreAuthorize("@ss.hasPermi('ticket:permit:query')")
    @GetMapping(value = "/{hId}")
    public AjaxResult getInfo(@PathVariable("hId") Long hId) {
        return AjaxResult.success(tFireWorkPermitService.selectTFireWorkPermitById(hId));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('ticket:permit:add')")
    @Log(title = "【动火作业票】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TFireWorkPermit tFireWorkPermit) {
        TTicketId tTicketId = new TTicketId();
        tTicketId.setId(1l);
        Long ticketId = tTicketIdController.createId(tTicketId);
        logger.info("ticketId:" + ticketId);
        tFireWorkPermit.sethId(ticketId);
        try {
            //生成word
            //渲染文本
            Map<String, Object> params = getWordData(tFireWorkPermit);
            // 模板路径
            String templatePath = "static/word/fireTicket.docx";
            // 生成word的路径
            String fileDir = RuoYiConfig.getProfile() + "/" + "ticketWord";
            // 生成word的文件
            String fileName = "H" + ticketId + ".docx";
            String wordPath = this.wordController.createWord(templatePath, fileDir, fileName, params);
            tFireWorkPermit.setWordUrl(wordPath);
            //使用流的方式转换PDF
            String fileName2 = "H" + ticketId + ".pdf";
            String pdfPath = this.wordController.createPDF(fileDir, fileName, fileName2, params);
            tFireWorkPermit.setPdfUrl(pdfPath);
        } catch (IOException e) {
            logger.error("生成文件失败");
        }
        tFireWorkPermitService.insertTFireWorkPermit(tFireWorkPermit);
        //保存危害工作许可证关联数据
        PermitRelation permitRelation = new PermitRelation();
        permitRelation.setPermitId(tFireWorkPermit.gethId());
        permitRelation.setPermitType("H");
        permitRelation.setPermitStatus(1L);
        this.itPermitRelationService.add(permitRelation);
        return AjaxResult.success(ticketId);
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('ticket:permit:edit')")
    @Log(title = "【动火作业票】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TFireWorkPermit tFireWorkPermit) {
        try {
            //生成word
            //渲染文本
            Map<String, Object> params = getWordData(tFireWorkPermit);
            // 模板路径
            String templatePath = "static/word/fireTicket.docx";
            // 生成word的路径
            String fileDir = RuoYiConfig.getProfile() + "/" + "ticketWord";
            // 生成word的文件
            String fileName = "H" + tFireWorkPermit.gethId() + ".docx";
            String wordPath = this.wordController.createWord(templatePath, fileDir, fileName, params);
            tFireWorkPermit.setWordUrl(wordPath);
            //使用流的方式转换PDF
            String fileName2 = "H" + tFireWorkPermit.gethId() + ".pdf";
            String pdfPath = this.wordController.createPDF(fileDir, fileName, fileName2, params);
            tFireWorkPermit.setPdfUrl(pdfPath);
        } catch (IOException e) {
            logger.error("生成文件失败");
        }
        return toAjax(tFireWorkPermitService.updateTFireWorkPermit(tFireWorkPermit));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('ticket:permit:remove')")
    @Log(title = "【动火作业票】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{hIds}")
    public AjaxResult remove(@PathVariable Long[] hIds) {
        return toAjax(tFireWorkPermitService.deleteTFireWorkPermitByIds(hIds));
    }


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

        getCheck(params, tFireWorkPermit.getaIsNeedSafeLiaison().toString(), "aIsNSL1", "aIsNSL2");
        params.put("aSafeLiaisonName", Texts.of(tFireWorkPermit.getaSafeLiaisonName()).fontSize(7).bold().create());
        params.put("aSafeLiaisonSign", Texts.of(tFireWorkPermit.getaSafeLiaisonSign()).fontSize(7).bold().create());
        params.put("aSafeLiaisonTel", Texts.of(tFireWorkPermit.getaSafeLiaisonTel()).fontSize(7).bold().create());
        params.put("aSafeLiaisonOffice", Texts.of(tFireWorkPermit.getaSafeLiaisonOffice()).fontSize(7).bold().create());
        // B 栏
        params.put("bDeviceName", Texts.of(tFireWorkPermit.getbDeviceName()).fontSize(7).bold().create());
        params.put("bAreaNo", Texts.of(tFireWorkPermit.getbAreaNo()).fontSize(7).bold().create());
        params.put("bWorkContent", Texts.of(tFireWorkPermit.getbWorkContent()).fontSize(7).bold().create());
        getCheck(params, tFireWorkPermit.getbFireWorkGrade() == null ? null : tFireWorkPermit.getbFireWorkGrade().toString(), "bfwg1", "bfwg2", "bfwg3");
        if (tFireWorkPermit.getbValidityStartTime() != null) {
            params.put("bValidityStartTime", Texts.of(DateUtils.parseDateToStr("yyyy年MM月dd日hh时mm分", tFireWorkPermit.getbValidityStartTime())).fontSize(7).bold().create());
        }
        if (tFireWorkPermit.getbValidityEndTime() != null) {
            params.put("bValidityEndTime", Texts.of(DateUtils.parseDateToStr("yyyy年MM月dd日hh时mm分", tFireWorkPermit.getbValidityEndTime())).fontSize(7).bold().create());
        }
        getCheck(params, tFireWorkPermit.getcIsWorkToFire() == null ? null : tFireWorkPermit.getcIsWorkToFire().toString(), "cIsWTF");
        getCheck(params, tFireWorkPermit.getcIsWorkToBlast() == null ? null : tFireWorkPermit.getcIsWorkToBlast().toString(), "cIsWTB");
        getCheck(params, tFireWorkPermit.getcIsWorkToEnvir() == null ? null : tFireWorkPermit.getcIsWorkToEnvir().toString(), "cIsWTE");
        getCheck(params, tFireWorkPermit.getcIsDeviceToBlast() == null ? null : tFireWorkPermit.getcIsDeviceToBlast().toString(), "cIsDTB");
        getCheck(params, tFireWorkPermit.getcIsOtherA() == null ? null : tFireWorkPermit.getcIsOtherA().toString(), "cIsOA");
        getCheck(params, tFireWorkPermit.getcIsOtherFire() == null ? null : tFireWorkPermit.getcIsOtherFire().toString(), "cIsOF");
        params.put("aId", Texts.of(tFireWorkPermit.getaId() == null ? "" : tFireWorkPermit.getaId().toString()).fontSize(7).bold().create());
        params.put("cOtherFireContent", Texts.of(tFireWorkPermit.getcOtherFireContent() == null ? "" : tFireWorkPermit.getcOtherFireContent()).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 ("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)));
        }
    }

    public void getCheck(Map<String, Object> params, String ticketWord, String check1, String check2, String check3) {
        if ("1".equals(ticketWord)) {
            params.put(check1, new TextRenderData("\u00FE", new Style("Wingdings", 7)));
            params.put(check2, new TextRenderData("\u006F", new Style("Wingdings", 7)));
            params.put(check3, 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)));
            params.put(check3, new TextRenderData("\u006F", new Style("Wingdings", 7)));
        } else if ("3".equals(ticketWord)) {
            params.put(check1, new TextRenderData("\u006F", new Style("Wingdings", 7)));
            params.put(check2, new TextRenderData("\u006F", new Style("Wingdings", 7)));
            params.put(check3, 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)));
            params.put(check3, new TextRenderData("\u006F", new Style("Wingdings", 7)));
        }
    }

}
