package com.ruoyi.project.apply.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.Pictures;
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.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
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.interceptor.annotation.RepeatSubmit;
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.apply.domain.TApplyLock;
import com.ruoyi.project.apply.domain.TApplySafetychange;
import com.ruoyi.project.apply.service.ITApplyLockService;
import com.ruoyi.project.apply.service.ITApplySafetychangeService;
import com.ruoyi.project.approve.damain.DevTask;
import com.ruoyi.project.listener.apply.change.*;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import io.jsonwebtoken.lang.Assert;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 组织保护措施状态变更申请Controller
 *
 * @author ruoyi
 * @date 2023-02-09
 */
@RestController
@RequestMapping("/apply/safetychange")
public class TApplySafetychangeController extends BaseController {
    @Autowired
    private ITApplySafetychangeService tApplySafetychangeService;

    @Autowired
    private ITApplyLockService tApplyLockService;


    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TaskService taskService;

    /**
     * 查询组织保护措施状态变更申请列表
     */
    @PreAuthorize("@ss.hasPermi('apply:safetychange:list')")
    @GetMapping("/list")
    public TableDataInfo list(TApplySafetychange tApplySafetychange) {
        startPage();
        List<TApplySafetychange> list = tApplySafetychangeService.selectTApplySafetychangeList(tApplySafetychange);
        return getDataTable(list);
    }

    @GetMapping("/listChangeDescribe")
    public AjaxResult listChangeDescribe(TApplySafetychange tApplySafetychange) {
        List<TApplySafetychange> list = tApplySafetychangeService.selectChangeDescribe(tApplySafetychange);
        return AjaxResult.success(list);
    }

    @GetMapping("/listChangeReason")
    public AjaxResult listChangeReason(TApplySafetychange tApplySafetychange) {
        List<TApplySafetychange> list = tApplySafetychangeService.selectChangeReason(tApplySafetychange);
        return AjaxResult.success(list);
    }

    @GetMapping("/listSAFA")
    public AjaxResult listSAFA(TApplySafetychange tApplySafetychange) {
        List<TApplySafetychange> list = tApplySafetychangeService.selectSAFA(tApplySafetychange);
        return AjaxResult.success(list);
    }


    /**
     * 导出组织保护措施状态变更申请列表
     */
    @PreAuthorize("@ss.hasPermi('apply:safetychange:export')")
    @Log(title = "组织保护措施状态变更申请", businessType = BusinessType.EXPORT)
    @PutMapping("/export")
    public AjaxResult export(@RequestBody TApplySafetychange tApplySafetychange) {
        List<TApplySafetychange> list = tApplySafetychangeService.selectTApplySafetychangeList(tApplySafetychange);
        ExcelUtil<TApplySafetychange> util = new ExcelUtil<TApplySafetychange>(TApplySafetychange.class);
        return util.exportExcel(list, "safetychange");
    }

    /**
     * 获取组织保护措施状态变更申请详细信息
     */
//    @PreAuthorize("@ss.hasPermi('apply:safetychange:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tApplySafetychangeService.selectTApplySafetychangeById(id));
    }

    /**
     * 新增组织保护措施状态变更申请
     */
    @PreAuthorize("@ss.hasPermi('apply:safetychange:add')")
    @Log(title = "组织保护措施状态变更申请", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@RequestBody TApplySafetychange tApplySafetychange) {
        String userId = getUserId().toString();
        for (String s : tApplySafetychange.getLockNo().split(",")) {
            TApplyLock tApplyLock = tApplyLockService.selectTApplyLockByLockCode(s.substring(0, s.indexOf("(")));
            if (tApplyLock!=null) {
                if (tApplyLock.getStatus() == 1 || tApplyLock.getStatus() == 2) {
                    return AjaxResult.error("该锁不可用。");
                }
                //修改锁状态
                tApplyLock.setStatus(1L);
                tApplyLockService.updateTApplyLock(tApplyLock);
            }
        }
        tApplySafetychange.setApplicant(userId);
        tApplySafetychange.setApplicantName(getNickName());
        tApplySafetychange.setApplicationTime(new Date());
        tApplySafetychange.setCreatedate(new Date());
        tApplySafetychange.setCreaterCode(getUserId().toString());
        String safaerIds = tApplySafetychange.getSafaer();
        tApplySafetychange.setSafaer(null);
        // tApplySafetychange.setConfirmer(tApplySafetychange.getSafaer());
//        tApplySafetychange.setConfirmerName(tApplySafetychange.getSafaerName());
        if (StringUtils.isNotEmpty(tApplySafetychange.getRemarks()) && (!tApplySafetychange.getRemarks().endsWith("；") || !tApplySafetychange.getRemarks().endsWith(";")))
            tApplySafetychange.setRemarks("申请人-" + getNickName() + "：" + tApplySafetychange.getRemarks() + "；");
        tApplySafetychangeService.insertTApplySafetychange(tApplySafetychange);

        // 开始申请流程
        tApplySafetychange.setApNo(DateUtils.dateTimeNow() + userId);
        long businessKey = tApplySafetychange.getId();
        //开始工作流、监听
        Authentication.setAuthenticatedUserId(userId);//设置当前申请人
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyuser", userId);
//        StringBuilder confirmer = new StringBuilder();
//        for (String staffId : safaerIds.split(",")) {
//            SysUser user = userService.selectUserByStaffId(staffId);
//            confirmer.append(user.getUserId()).append(",");
//        }
//        if (StringUtils.isNotEmpty(confirmer.toString())) {
//            confirmer = new StringBuilder(confirmer.substring(0, confirmer.length() - 1));
//        }
        variables.put("confirmer", safaerIds);
        variables.put("resetConfirmer2", safaerIds);
        variables.put("executor", tApplySafetychange.getExecutor());
        variables.put("safaer", safaerIds);
        //查询经理
        TStaffmgr tStaffmgr = new TStaffmgr();
        tStaffmgr.setActualposts("24,26");
        StringBuilder approvers = new StringBuilder();
        for (SysUser user : userService.selectUserPost(tStaffmgr)) {
            approvers.append(user.getUserId().toString()).append(",");
        }
        if (StringUtils.isNotEmpty(approvers.toString())) {
            approvers = new StringBuilder(approvers.substring(0, approvers.length() - 1));
        }
        variables.put("approver", approvers.toString());
        tStaffmgr = new TStaffmgr();
        tStaffmgr.setActualposts("12");
        StringBuilder changeExecutors = new StringBuilder();
        for (SysUser user : userService.selectUserPost(tStaffmgr)) {
            changeExecutors.append(user.getUserId().toString()).append(",");
        }
        if (StringUtils.isNotEmpty(changeExecutors.toString())) {
            changeExecutors = new StringBuilder(changeExecutors.substring(0, changeExecutors.length() - 1));
        }
        variables.put("changeExecutor", changeExecutors.toString());
        variables.put("changeNextTaskListener", new ChangeNextTaskListener());
        variables.put("changeMgrListener", new ChangeMgrListener());
        variables.put("changeEndFailListener", new ChangeEndFailListener());
        variables.put("changeEndSuccessListener", new ChangeEndSuccessListener());
        variables.put("changeFlowListener", new ChangeFlowListener());
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("safetychange", String.valueOf(businessKey), variables);
        logger.info("流程定义id：" + pi.getProcessDefinitionId());
        logger.info("流程实例id：" + pi.getProcessInstanceId());
        tApplySafetychange.setProcessId(pi.getProcessInstanceId());
        tApplySafetychangeService.updateTApplySafetychange(tApplySafetychange);

        // 申请人申请直接通过
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        Task task = taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).active().singleResult();
        String taskId = task.getId();
        processEngine.getTaskService().claim(taskId, getUserId().toString());
        taskService.addComment(taskId, pi.getProcessInstanceId(), "");
        Map<String, Object> param = new HashMap<>();
        param.put("condition", "1");
        taskService.complete(taskId, param);
        return toAjax(1);
    }

    @Log(title = "组织保护措施状态变更申请审核处理", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping("/handle")
    public AjaxResult handle(@RequestBody DevTask devTask) {
        TApplySafetychange form = devTask.getSafetychange();
        //使用任务服务完成任务(提交任务)
        String taskId = devTask.getTaskId();
        // 使用任务id,获取任务对象，获取流程实例id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //利用任务对象，获取流程实例id
        String processInstancesId = task.getProcessInstanceId();
        TApplySafetychange tApplySafetychange = tApplySafetychangeService.selectTApplySafetychangeById(form.getId());
        String taskName = task.getName();//实例名
        // 添加备注
        String remarks = StringUtils.isEmpty(tApplySafetychange.getRemarks()) ? "" : tApplySafetychange.getRemarks();
        if (taskName.contains("安全评估人")) {
            taskName = "安全评估人";
        }
        //流程审批意见
        String symbol = "";
        String text = "";
        if (StringUtils.isNotEmpty(form.getRemarks())) {
            text = form.getRemarks();
            symbol = "，";
            form.setRemarks(remarks + taskName + "-" + getNickName() + "：" + form.getRemarks() + "；");
        } else
            form.setRemarks("");
        // 判断流程
        if ("1".equals(devTask.getCondition())) {
            devTask.setComment("通过" + symbol + text);
        } else if ("0".equals(devTask.getCondition())) {
            devTask.setComment("拒绝" + symbol + text);
            form.setStatus(1L);
            form.setApproveStatus("3");
            //修改锁状态
            for (String lockNo : tApplySafetychange.getLockNo().split(",")) {
                TApplyLock tApplyLock = tApplyLockService.selectTApplyLockByLockCode(lockNo.substring(0, lockNo.indexOf("(")));
                if (tApplyLock != null) {
                    tApplyLock.setStatus(0L);//将锁状态改为已拆锁
                    tApplyLockService.updateTApplyLock(tApplyLock);
                }
            }
        } else if ("2".equals(devTask.getCondition())) {
            devTask.setComment("驳回" + symbol + text);
        }
        // 根据实例名判断当前流程节点
        Map<String, Object> param = new HashMap<>();
        switch (task.getName()) {
            case "安全评估人1":
                form.setSafaer(getUserId().toString());
                form.setSafaerName(getNickName());
                form.setSafaTime(new Date());
                break;
            case "批准人":
                form.setApprover(getUserId().toString());
                form.setApproverName(getNickName());
                form.setApproveTime(new Date());
                if ("1".equals(devTask.getCondition()))
                    form.setApproveStatus("2");
                break;
            case "措施执行人":
                form.setExecutionTime(new Date());
                break;
            case "措施确认人":
                form.setConfirmerName(getNickName());
                form.setConfirmer(getUserId().toString());
                form.setConfirmTime(new Date());
                break;
            case "变更执行人":
                form.setChangeExecutor(getUserId().toString());
                form.setChangeExecutorName(getNickName());
                form.setChangeExecutorTime(new Date());
                break;
            case "安全评估人2":
                TStaffmgr tStaffmgr = new TStaffmgr();
                tStaffmgr.setActualposts("12");
                StringBuilder resetConfirmer1 = new StringBuilder();
                for (SysUser user : userService.selectUserPost(tStaffmgr)) {
                    resetConfirmer1.append(user.getUserId().toString()).append(",");
                }
                if (StringUtils.isNotEmpty(resetConfirmer1.toString())) {
                    resetConfirmer1 = new StringBuilder(resetConfirmer1.substring(0, resetConfirmer1.length() - 1));
                }
                param.put("resetConfirmer1", resetConfirmer1.toString());
                break;
            case "确认人1":
                form.setResetConfirmer1(getUserId().toString());
                form.setResetConfirmTime1(new Date());
                form.setResetConfirmerName1(getNickName());
                break;
            case "确认人2":
                form.setResetConfirmer2(getUserId().toString());
                form.setResetConfirmTime2(new Date());
                form.setResetConfirmerName2(getNickName());
                form.setStatus(1L);
                //修改锁状态
                for (String lockNo : tApplySafetychange.getLockNo().split(",")) {
                    TApplyLock tApplyLock = tApplyLockService.selectTApplyLockByLockCode(lockNo.substring(0, lockNo.indexOf("(")));
                    if (tApplyLock != null) {
                        tApplyLock.setStatus(0L);//将锁状态改为已拆锁
                        tApplyLockService.updateTApplyLock(tApplyLock);
                    }
                }
                break;
        }
        param.put("condition", devTask.getCondition());
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        //认领任务
        processEngine.getTaskService().claim(taskId, getUserId().toString());
        taskService.addComment(taskId, processInstancesId, devTask.getComment());
        taskService.complete(taskId, param);
        // 更新任务
        tApplySafetychangeService.updateTApplySafetychange(form);
        return AjaxResult.success();
    }

    /**
     * 修改组织保护措施状态变更申请
     */
    @PreAuthorize("@ss.hasPermi('apply:safetychange:edit')")
    @Log(title = "组织保护措施状态变更申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TApplySafetychange tApplySafetychange) {
        tApplySafetychange.setUpdatedate(new Date());
        tApplySafetychange.setUpdaterCode(getUserId());
        return toAjax(tApplySafetychangeService.updateTApplySafetychange(tApplySafetychange));
    }

    /**
     * 删除组织保护措施状态变更申请
     */
    @PreAuthorize("@ss.hasPermi('apply:safetychange:remove')")
    @Log(title = "组织保护措施状态变更申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tApplySafetychangeService.deleteTApplySafetychangeByIds(ids));
    }

    /**
     * @param id
     * @return
     * @throws IOException
     */
    @GetMapping("/wordView/{id}")
    public AjaxResult wordView(@PathVariable Long id) throws IOException {
        //根据ID查询并生成
        String url = PreView(id);
        return AjaxResult.success(url);
    }

    /**
     * @param id 生成文件名
     * @return
     * @throws IOException
     */
    public String PreView(Long id) throws IOException {
        //根据ID查询并生成
        TApplySafetychange tApplySafetychange = tApplySafetychangeService.selectTApplySafetychangeById(id);
        String url = this.createApplySafetychangeWord(tApplySafetychange);
        return url;
    }

    /**
     * 生成word
     */
    public String createApplySafetychangeWord(TApplySafetychange tApplySafetychange) throws IOException {
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(tApplySafetychange);
        // 模板路径
        String templatePath = "static/word/apply/applySafetychange.docx";
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "apply/applySafetychange";
        // 生成word的文件名称
        String fileName = tApplySafetychange.getId() + ".docx";
        String wordPath = this.createWord(templatePath, fileDir, fileName, params);
        return wordPath;
    }

    /**
     * 获取word数据
     */
    public Map<String, Object> getWordData(TApplySafetychange tApplySafetychange) {
        Map<String, Object> params = new HashMap<>();
        params.put("lockNo", Texts.of(tApplySafetychange.getLockNo()).fontSize(10).bold().create());
        params.put("changeDescribe", Texts.of(tApplySafetychange.getChangeDescribe()).fontSize(10).bold().create());
        params.put("changeReason", Texts.of(tApplySafetychange.getChangeReason()).fontSize(10).bold().create());
        if (StringUtils.isNotEmpty(tApplySafetychange.getApplicant())) {//申请人
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplySafetychange.getApplicant()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("applicantP", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("applicant", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }
        if (tApplySafetychange.getApplicationTime() != null) {//申请时间
            params.put("applicationTime", Texts.of(DateUtils.dateTimeMin(tApplySafetychange.getApplicationTime())).fontSize(9).bold().create());
        }
        params.put("safa", Texts.of(tApplySafetychange.getSafa()).fontSize(10).bold().create());
        if (StringUtils.isNotEmpty(tApplySafetychange.getSafaer())) {//安全评估人
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplySafetychange.getSafaer()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("safaerP", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("safaer", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }

        if (tApplySafetychange.getSafaTime() != null) {//安全评估时间
            params.put("safaTime", Texts.of(DateUtils.dateTimeMin(tApplySafetychange.getSafaTime())).fontSize(9).bold().create());
        }
        if (StringUtils.isNotEmpty(tApplySafetychange.getApprover())) {//批准人
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplySafetychange.getApprover()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("approverP", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("approver", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }
        if (tApplySafetychange.getApproveTime() != null) {//批准时间
            params.put("approveTime", Texts.of(DateUtils.dateTimeMin(tApplySafetychange.getApproveTime())).fontSize(9).bold().create());
        }
        if (StringUtils.isNotEmpty(tApplySafetychange.getExecutor())) {//临时安全措施执行人
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplySafetychange.getExecutor()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("exeP", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("exe", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }
        if (tApplySafetychange.getExecutionTime() != null) {//临时安全措施执行（时间）
            params.put("exeT", Texts.of(DateUtils.dateTimeMin(tApplySafetychange.getExecutionTime())).fontSize(9).bold().create());
        }
        if (StringUtils.isNotEmpty(tApplySafetychange.getConfirmer())) {//临时安全措施确认人
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplySafetychange.getConfirmer()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("conP", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("con", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }
        if (tApplySafetychange.getConfirmTime() != null) {//临时安全措施确认（时间）
            params.put("conT", Texts.of(DateUtils.dateTimeMin(tApplySafetychange.getConfirmTime())).fontSize(9).bold().create());
        }
        params.put("changeExecution", Texts.of(tApplySafetychange.getChangeExecution()).fontSize(10).bold().create());

        if (StringUtils.isNotEmpty(tApplySafetychange.getChangeExecutor())) {//执行人
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplySafetychange.getChangeExecutor()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("cEP", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("cE", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }
        if (tApplySafetychange.getChangeExecutorTime() != null) {//执行时间）
            params.put("cET", Texts.of(DateUtils.dateTimeMin(tApplySafetychange.getChangeExecutorTime())).fontSize(9).bold().create());
        }
        getCheck(params, tApplySafetychange.getResetConfirm(), "resetConfirm1", "resetConfirm2");

        if (StringUtils.isNotEmpty(tApplySafetychange.getResetConfirmer1())) {//状态恢复，确认人1
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplySafetychange.getResetConfirmer1()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("resetConfirmer1P", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("resetConfirmer1", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }
        if (tApplySafetychange.getResetConfirmTime1() != null) {//状态恢复，确认人1时间）
            params.put("resetConfirmTime1", Texts.of(DateUtils.dateTimeMin(tApplySafetychange.getResetConfirmTime1())).fontSize(9).bold().create());
        }
        if (StringUtils.isNotEmpty(tApplySafetychange.getResetConfirmer2())) {//状态恢复，确认人2
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplySafetychange.getResetConfirmer2()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("resetConfirmer2P", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("resetConfirmer2", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }
        if (tApplySafetychange.getResetConfirmTime2() != null) {//状态恢复，确认人2时间）
            params.put("resetConfirmTime2", Texts.of(DateUtils.dateTimeMin(tApplySafetychange.getResetConfirmTime2())).fontSize(9).bold().create());
        }

        getCheck(params, tApplySafetychange.getRevokeConfirm(), "revoke1", "revoke2");
        getCheck(params, tApplySafetychange.getRevokeConfirm(), "revoke3");
        params.put("remarks", Texts.of(tApplySafetychange.getRemarks()).fontSize(10).bold().create());

        // 渲染文本
        return params;
    }

    /**
     * @param templatePath word模板文件路径
     * @param fileDir      生成的文件存放地址
     * @param fileName     生成的文件名
     * @param paramMap     参数集合
     * @return 返回word生成的路径
     */
    public String createWord(String templatePath, String fileDir, String fileName, Map<String, Object> paramMap) throws IOException {
        Assert.notNull(templatePath, "word模板文件路径不能为空");
        Assert.notNull(fileDir, "生成的文件存放地址不能为空");
        Assert.notNull(fileName, "生成的文件名不能为空");
        File dir = new File(fileDir);
        if (!dir.exists()) {
            logger.info("目录不存在，创建文件夹{}!", fileDir);
            dir.mkdirs();
        }
        fileName = fileName.replaceAll("/", "_"); //替换文件中敏感字段
        logger.info("目录文件{}!", fileName);
        String filePath = fileDir + "/" + fileName;
        logger.info("目录{}!", filePath);
        // 读取模板渲染参数
        InputStream is = getClass().getClassLoader().getResourceAsStream(templatePath);
        XWPFTemplate template = XWPFTemplate.compile(is).render(paramMap);
        try {
            // 将模板参数写入路径
            template.writeToFile(filePath);
            template.close();
        } catch (Exception e) {
            logger.error("生成word异常{}", e.getMessage());
            e.printStackTrace();
        }
        String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getFilePath("/" + "apply/applySafetychange"), fileName);
        return pathFileName;
    }

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

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

    /**
     * @param
     * @return 映射签名的文件名
     * @throws IOException
     */
    public String fileName(String filepath) {
        String newFilePath = filepath.replace("/profile", "");
        String pathName = RuoYiConfig.getProfile() + newFilePath;
        return pathName;
    }
}
