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.TApplyOfflinevalve;
import com.ruoyi.project.apply.service.ITApplyLockService;
import com.ruoyi.project.apply.service.ITApplyOfflinevalveService;
import com.ruoyi.project.approve.damain.DevTask;
import com.ruoyi.project.listener.apply.valve.EndFailListener;
import com.ruoyi.project.listener.apply.valve.EndSuccessListener;
import com.ruoyi.project.listener.apply.valve.FlowListener;
import com.ruoyi.project.listener.apply.valve.NextTaskListener;
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-08
 */
@RestController
@RequestMapping("/apply/offlinevalve")
public class TApplyOfflinevalveController extends BaseController {
    @Autowired
    private ITApplyOfflinevalveService tApplyOfflinevalveService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ITApplyLockService tApplyLockService;

    /**
     * 查询安全阀离线切出申请列表
     */
    @PreAuthorize("@ss.hasPermi('apply:offlinevalve:list')")
    @GetMapping("/list")
    public TableDataInfo list(TApplyOfflinevalve tApplyOfflinevalve) {
        startPage();
        List<TApplyOfflinevalve> list = tApplyOfflinevalveService.selectTApplyOfflinevalveList(tApplyOfflinevalve);
        return getDataTable(list);
    }

    @GetMapping("/listSAFA")
    public AjaxResult listSAFA(TApplyOfflinevalve tApplyOfflinevalve) {
        List<TApplyOfflinevalve> list = tApplyOfflinevalveService.selectSAFA(tApplyOfflinevalve);
        return AjaxResult.success(list);
    }

    /**
     * 导出安全阀离线切出申请列表
     */
    @PreAuthorize("@ss.hasPermi('apply:offlinevalve:export')")
    @Log(title = "安全阀离线切出申请", businessType = BusinessType.EXPORT)
    @PutMapping("/export")
    public AjaxResult export(@RequestBody TApplyOfflinevalve tApplyOfflinevalve) {
        List<TApplyOfflinevalve> list = tApplyOfflinevalveService.selectTApplyOfflinevalveList(tApplyOfflinevalve);
        ExcelUtil<TApplyOfflinevalve> util = new ExcelUtil<TApplyOfflinevalve>(TApplyOfflinevalve.class);
        return util.exportExcel(list, "offlinevalve");
    }

    /**
     * 获取安全阀离线切出申请详细信息
     */
//    @PreAuthorize("@ss.hasPermi('apply:offlinevalve:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tApplyOfflinevalveService.selectTApplyOfflinevalveById(id));
    }

    /**
     * 新增安全阀离线切出申请
     */
    @PreAuthorize("@ss.hasPermi('apply:offlinevalve:add')")
    @Log(title = "安全阀离线切出申请", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@RequestBody TApplyOfflinevalve tApplyOfflinevalve) {
        Long userId = getUserId();
        // 新增申请数据
        tApplyOfflinevalve.setApplicant(userId.toString());
        tApplyOfflinevalve.setApplicantName(getNickName());
        tApplyOfflinevalve.setApplicationTime(new Date());
        tApplyOfflinevalve.setCreatedate(new Date());
        tApplyOfflinevalve.setCreaterCode(userId.toString());
        if (StringUtils.isNotEmpty(tApplyOfflinevalve.getRemarks()) && (!tApplyOfflinevalve.getRemarks().endsWith("；") || !tApplyOfflinevalve.getRemarks().endsWith(";")))
            tApplyOfflinevalve.setRemarks("申请人-" + getNickName() + "：" + tApplyOfflinevalve.getRemarks() + "；");
        tApplyOfflinevalveService.insertTApplyOfflinevalve(tApplyOfflinevalve);

        // 开始申请流程
        tApplyOfflinevalve.setApNo(DateUtils.dateTimeNow() + userId);
        long businessKey = tApplyOfflinevalve.getId();
        String applyUser = userId.toString();
        //开始工作流、监听
        Authentication.setAuthenticatedUserId(applyUser);//设置当前申请人
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyuser", applyUser);
        String confirmer = tApplyOfflinevalve.getConfirmer();
//        StringBuilder confirmer = new StringBuilder();
//        for (String staffId : confirmers.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", confirmer);
        variables.put("infoconfirmer", confirmer);
        TStaffmgr tStaffmgr = new TStaffmgr();
        tStaffmgr.setActualposts("12");
        StringBuilder executor = new StringBuilder();
        for (SysUser user : userService.selectUserPost(tStaffmgr)) {
            executor.append(user.getUserId().toString()).append(",");
        }
        if (StringUtils.isNotEmpty(executor.toString())) {
            executor = new StringBuilder(executor.substring(0, executor.length() - 1));
        }
        variables.put("executor", executor.toString());
        variables.put("nextTaskListener", new NextTaskListener());
        variables.put("flowListener", new FlowListener());
        variables.put("endSuccessListener", new EndSuccessListener());
        variables.put("endFailListener", new EndFailListener());
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("offlinevalve", String.valueOf(businessKey), variables);
        logger.info("流程定义id：" + pi.getProcessDefinitionId());
        logger.info("流程实例id：" + pi.getProcessInstanceId());
        tApplyOfflinevalve.setProcessId(pi.getProcessInstanceId());
        tApplyOfflinevalveService.updateTApplyOfflinevalve(tApplyOfflinevalve);


        // 申请人申请直接通过
        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 AjaxResult.success();
    }

    @Log(title = "安全阀离线切出申请审核处理", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping("/handle")
    public AjaxResult handle(@RequestBody DevTask devTask) {
        //更新数据
        TApplyOfflinevalve form = devTask.getOfflinevalve();
        //使用任务服务完成任务(提交任务)
        String taskId = devTask.getTaskId();
        // 使用任务id,获取任务对象，获取流程实例id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //利用任务对象，获取流程实例id
        String processInstancesId = task.getProcessInstanceId();
        // 旧数据
        TApplyOfflinevalve tApplyOfflinevalve = tApplyOfflinevalveService.selectTApplyOfflinevalveById(form.getId());
        String taskName = task.getName();//实例名
        // 添加备注
        String remarks = StringUtils.isEmpty(tApplyOfflinevalve.getRemarks()) ? "" : tApplyOfflinevalve.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");
            //修改锁状态
            if (StringUtils.isNotEmpty(tApplyOfflinevalve.getLockNo())) {
                for (String lockNo : tApplyOfflinevalve.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);
            //修改锁状态
            if (StringUtils.isNotEmpty(tApplyOfflinevalve.getLockNo())) {
                for (String lockNo : tApplyOfflinevalve.getLockNo().split(",")) {
                    TApplyLock tApplyLock = tApplyLockService.selectTApplyLockByLockCode(lockNo.substring(0, lockNo.indexOf("(")));
                    if (tApplyLock != null) {
                        tApplyLock.setStatus(0L);//将锁状态改为挂锁
                        tApplyLockService.updateTApplyLock(tApplyLock);
                    }
                }
            }
        }
        // 根据实例名判断当前流程节点
        Map<String, Object> param = new HashMap<>();
        switch (task.getName()) {
            case "临时措施制定人":
                form.setConfirmer(getUserId().toString());
                form.setConfirmerName(getNickName());
                if (StringUtils.isNotEmpty(form.getLockNo())&&"1".equals(devTask.getCondition())) {
                    for (String lockNo : form.getLockNo().split(",")) {
                        TApplyLock tApplyLock = tApplyLockService.selectTApplyLockByLockCode(lockNo.substring(0, lockNo.indexOf("(")));
                        if (tApplyLock != null) {
                            if (tApplyLock.getStatus() == 1 || tApplyLock.getStatus() == 2) {
                                return AjaxResult.error("该锁不可用。");
                            }
                            //修改锁状态
                            tApplyLock.setStatus(1L);//将锁状态改为已拆锁
                            tApplyLockService.updateTApplyLock(tApplyLock);
                        }
                    }
                }
                break;
            case "临时措施确认人":
                form.setConfirmer(getUserId().toString());
                form.setConfirmerName(getNickName());
                form.setTemporaryTime(new Date());
                //查询经理
                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));
                }
                param.put("approver", approvers.toString());
                break;
            case "临时措施执行人":
                form.setExecutor(getUserId().toString());
                form.setExecutorName(getNickName());
                form.setExecutionTime(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 "信息确认人":
                tStaffmgr = new TStaffmgr();
                tStaffmgr.setActualposts("12");
                StringBuilder lockConfirmer = new StringBuilder();
                for (SysUser user : userService.selectUserPost(tStaffmgr)) {
                    lockConfirmer.append(user.getUserId().toString()).append(",");
                }
                if (StringUtils.isNotEmpty(lockConfirmer.toString())) {
                    lockConfirmer = new StringBuilder(lockConfirmer.substring(0, lockConfirmer.length() - 1));
                }
                param.put("lockConfirmer", lockConfirmer.toString());//设置上锁确认人
                form.setLockConfirmer1(null);
                break;
            case "确认人":
                // 如果上锁确认人1不为空上锁确认人2即信息确认人2
                form.setInfoConfirmer(getUserId().toString());
                form.setInfoConfirmerName(getNickName());
                form.setStatus(1L);//信息确认人2确认后申请单状态为已完成
                form.setConfirmTime(new Date());
                if (StringUtils.isNotEmpty(tApplyOfflinevalve.getLockConfirmer1())) {
                    form.setLockConfirmer2(getUserId().toString());
                    form.setLockConfirmer2Name(getNickName());
                } else {
                    form.setLockConfirm("NA");//否则确认是否已上锁为NA
                }
                //修改锁状态
                if (StringUtils.isNotEmpty(tApplyOfflinevalve.getLockNo())) {
                    for (String lockNo : tApplyOfflinevalve.getLockNo().split(",")) {
                        TApplyLock tApplyLock = tApplyLockService.selectTApplyLockByLockCode(lockNo.substring(0, lockNo.indexOf("(")));
                        if (tApplyLock != null) {
                            tApplyLock.setStatus(0L);//将锁状态改为挂锁
                            tApplyLockService.updateTApplyLock(tApplyLock);
                        }
                    }
                }
                break;
            case "上锁人":
                form.setLockConfirmer1(getUserId().toString());
                form.setLockConfirmer1Name(getNickName());
                break;
        }
        //网关判断
        if (StringUtils.isNotEmpty(tApplyOfflinevalve.getDisassembly()) && "是".equals(tApplyOfflinevalve.getDisassembly())) {
            param.put("is_unlock", "1");
        } else if (StringUtils.isNotEmpty(tApplyOfflinevalve.getDisassembly()) && !"是".equals(tApplyOfflinevalve.getDisassembly())) {
            param.put("is_unlock", "0");
        }
        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);
        //任务完成更新数据
        tApplyOfflinevalveService.updateTApplyOfflinevalve(form);
        return AjaxResult.success();
    }

    /**
     * 修改安全阀离线切出申请
     */
    @PreAuthorize("@ss.hasPermi('apply:offlinevalve:edit')")
    @Log(title = "安全阀离线切出申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TApplyOfflinevalve tApplyOfflinevalve) {
        tApplyOfflinevalve.setUpdatedate(new Date());
        tApplyOfflinevalve.setUpdaterCode(getUserId());
        return toAjax(tApplyOfflinevalveService.updateTApplyOfflinevalve(tApplyOfflinevalve));
    }

    /**
     * 删除安全阀离线切出申请
     */
    @PreAuthorize("@ss.hasPermi('apply:offlinevalve:remove')")
    @Log(title = "安全阀离线切出申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tApplyOfflinevalveService.deleteTApplyOfflinevalveByIds(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查询并生成
        TApplyOfflinevalve tApplyOfflinevalve = tApplyOfflinevalveService.selectTApplyOfflinevalveById(id);
        String url = this.createApplyOfflinevalveWord(tApplyOfflinevalve);
        return url;
    }


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

    /**
     * 获取word数据
     */
    public Map<String, Object> getWordData(TApplyOfflinevalve tApplyOfflinevalve) {
        Map<String, Object> params = new HashMap<>();
        params.put("devNo", Texts.of(tApplyOfflinevalve.getDevNo()).fontSize(10).bold().create());
        params.put("lockNo", Texts.of(tApplyOfflinevalve.getLockNo()).fontSize(10).bold().create());
        params.put("unit", Texts.of(tApplyOfflinevalve.getUnit()).fontSize(10).bold().create());
        params.put("offlineReason", Texts.of(tApplyOfflinevalve.getOfflineReason()).fontSize(10).bold().create());
        params.put("safa", Texts.of(tApplyOfflinevalve.getSafa()).fontSize(10).bold().create());
        if (StringUtils.isNotEmpty(tApplyOfflinevalve.getExecutor())) {
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplyOfflinevalve.getExecutor()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("execP", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("executor", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }
        if (tApplyOfflinevalve.getExecutionTime() != null) {//临时措施执行时间
            params.put("execT", Texts.of(DateUtils.dateTimeMin(tApplyOfflinevalve.getExecutionTime())).fontSize(9).bold().create());
        }
        if (StringUtils.isNotEmpty(tApplyOfflinevalve.getConfirmer())) {
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplyOfflinevalve.getConfirmer()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("tpP", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("confirmer", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }
        if (tApplyOfflinevalve.getTemporaryTime() != null) {//临时措施确认时间
            params.put("tpT", Texts.of(DateUtils.dateTimeMin(tApplyOfflinevalve.getTemporaryTime())).fontSize(9).bold().create());
        }
        if (StringUtils.isNotEmpty(tApplyOfflinevalve.getApplicant())) {
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplyOfflinevalve.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 (tApplyOfflinevalve.getApplicationTime() != null) {//申请时间
            params.put("applicationTime", Texts.of(DateUtils.dateTimeMin(tApplyOfflinevalve.getApplicationTime())).fontSize(9).bold().create());
        }
        if (StringUtils.isNotEmpty(tApplyOfflinevalve.getApprover())) {
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplyOfflinevalve.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 (tApplyOfflinevalve.getApproveTime() != null) {//批准时间
            params.put("approveTime", Texts.of(DateUtils.dateTimeMin(tApplyOfflinevalve.getApproveTime())).fontSize(9).bold().create());
        }
        if (StringUtils.isNotEmpty(tApplyOfflinevalve.getLockConfirmer1())) {
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplyOfflinevalve.getLockConfirmer1()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("lockConfirmer1P", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("lockConfirmer1", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }
        if (StringUtils.isNotEmpty(tApplyOfflinevalve.getLockConfirmer2())) {
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplyOfflinevalve.getLockConfirmer2()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("lockConfirmer2P", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("lockConfirmer2", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }
        if (StringUtils.isNotEmpty(tApplyOfflinevalve.getInfoConfirmer())) {
            SysUser sysUser = userService.selectUserById(Long.parseLong(tApplyOfflinevalve.getInfoConfirmer()));
            if (sysUser.getSignUrl() != null && new File(fileName(sysUser.getSignUrl())).exists()) {
                params.put("infoConfirmerP", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(50, 20).create());
            } else {
                params.put("infoConfirmer", Texts.of(sysUser.getNickName()).fontSize(10).bold().create());
            }
        }
        if (tApplyOfflinevalve.getConfirmTime() != null) {//确认时间
            params.put("confirmTime", Texts.of(DateUtils.dateTimeMin(tApplyOfflinevalve.getConfirmTime())).fontSize(9).bold().create());
        }
        params.put("remarks", Texts.of(tApplyOfflinevalve.getRemarks()).fontSize(10).bold().create());
        getCheck(params, tApplyOfflinevalve.getDisassembly(), "d1", "d2");
        getCheck(params, tApplyOfflinevalve.getDisassembly(), "d3");
        getCheck(params, tApplyOfflinevalve.getResetConfirm(), "reset1", "reset2");
        getCheck(params, tApplyOfflinevalve.getLeakConfirm(), "leak1", "leak2");
        getCheck(params, tApplyOfflinevalve.getRevokeConfirm(), "revoke1", "revoke2");
        getCheck(params, tApplyOfflinevalve.getLockConfirm(), "lock1", "lock2");
        getCheck(params, tApplyOfflinevalve.getLockConfirm(), "lock3");
        // 渲染文本
        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/applyOfflinevalve"), 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;
    }
}
