package com.ruoyi.project.invoice.controller;

import com.alibaba.fastjson.JSON;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.data.Texts;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SpringContextUtils;
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.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.invoice.domain.TApproveReserveInvoice;
import com.ruoyi.project.invoice.domain.TInvoiceBookingworkticket;
import com.ruoyi.project.invoice.domain.TInvoiceWorkcontent;
import com.ruoyi.project.invoice.mapper.TInvoiceWorkcontentMapper;
import com.ruoyi.project.invoice.service.ITApproveReserveInvoiceService;
import com.ruoyi.project.invoice.service.ITInvoiceBookingworkticketService;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.system.service.ISysUserService;
import io.jsonwebtoken.lang.Assert;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 预约作业票台账Controller
 *
 * @author ruoyi
 * @date 2022-08-25
 */
@RestController("tInvoiceBookingworkticketController")
@RequestMapping("/invoice/bookingworkticket")
public class TInvoiceBookingworkticketController extends BaseController {
    @Autowired
    private ITInvoiceBookingworkticketService tInvoiceBookingworkticketService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ITApproveReserveInvoiceService tApproveReserveInvoiceService;

    @Resource
    private TInvoiceWorkcontentMapper tInvoiceWorkcontentMapper;

    /**
     * 筛选出不同作业类型的台账数据
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:list')")
    @GetMapping("/list")
    public TableDataInfo workType(TInvoiceBookingworkticket tInvoiceBookingworkticket) {
        startPage();
        //先找到子表内容
        List<TInvoiceWorkcontent> tInvoiceWorkcontentList = tInvoiceBookingworkticketService.selectTInvoiceWorkcontentList(tInvoiceBookingworkticket);
        if (tInvoiceWorkcontentList.size() > 0) {
            ExecutorService executorService = Executors.newFixedThreadPool(20);
            final CountDownLatch latch = new CountDownLatch(tInvoiceWorkcontentList.size());
            for (TInvoiceWorkcontent workcontent : tInvoiceWorkcontentList) {
                executorService.execute(() -> {
                    try {
                        TInvoiceBookingworkticket bookingworkticket = tInvoiceBookingworkticketService.selectTInvoiceBookingworkticketById(workcontent.getBookingticketId());
                        workcontent.setBookingworkticket(bookingworkticket);
                    } catch (Exception e) {
                        logger.error("e:", e);
                    } finally {
                        latch.countDown();
                    }
                });
            }
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            executorService.shutdown();
        }
        return getDataTable(tInvoiceWorkcontentList);
    }


    /**
     * 导出预约作业票台账列表
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:export')")
    @Log(title = "预约作业票台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TInvoiceBookingworkticket tInvoiceBookingworkticket) {
        List<TInvoiceBookingworkticket> list = tInvoiceBookingworkticketService.selectTInvoiceBookingworkticketList(tInvoiceBookingworkticket);
        ExcelUtil<TInvoiceBookingworkticket> util = new ExcelUtil<TInvoiceBookingworkticket>(TInvoiceBookingworkticket.class);
        return util.exportExcel(list, "bookingworkticket");
    }

    @GetMapping("/exportBook")
    public AjaxResult exportBook(TInvoiceBookingworkticket tInvoiceBookingworkticket) throws IOException {
        logger.info(JSON.toJSONString(tInvoiceBookingworkticket));
        //字典查询
        List<SysDictData> book_work_type = iSysDictTypeService.selectDictDataByType("book_work_type");

        List<TInvoiceWorkcontent> tInvoiceWorkcontentList = tInvoiceBookingworkticketService.selectTInvoiceWorkcontentList(tInvoiceBookingworkticket);
        for (TInvoiceWorkcontent workcontent : tInvoiceWorkcontentList) {
            TInvoiceBookingworkticket bookingworkticket = tInvoiceBookingworkticketService.selectTInvoiceBookingworkticketById(workcontent.getBookingticketId());
            workcontent.setBookingworkticket(bookingworkticket);
        }
        if (tInvoiceBookingworkticket.getStatus() != null && tInvoiceBookingworkticket.getStatus() == 7) {
            //除去作废的票 以及 续票
            Iterator<TInvoiceWorkcontent> iterator = tInvoiceWorkcontentList.iterator();
            while (iterator.hasNext()) {
                TInvoiceWorkcontent t = iterator.next();
                if (t.getBookingworkticket().getStatus() == 7 || t.getXpxp().equals("12")) {
                    iterator.remove();
                }
            }
        } else {
            //除去未完成的票 以及 续票
            Iterator<TInvoiceWorkcontent> iterator = tInvoiceWorkcontentList.iterator();
            while (iterator.hasNext()) {
                TInvoiceWorkcontent t = iterator.next();
                if (t.getBookingworkticket().getStatus() != 3 || t.getXpxp().equals("12")) {
                    iterator.remove();
                }
            }
        }

        List<TInvoiceWorkcontent> newWorkcontentList = new ArrayList<>();
        //多个工作类型拆分成多条数据
        for (TInvoiceWorkcontent t : tInvoiceWorkcontentList
        ) {
            String[] wtArr = t.getWorkType().split(",");
            if (wtArr.length > 1) {
                for (int i = 0; i < wtArr.length; i++) {
                    TInvoiceWorkcontent arrItem = new TInvoiceWorkcontent();
                    BeanUtils.copyProperties(t, arrItem);
                    arrItem.setWorkType(wtArr[i]);
                    newWorkcontentList.add(arrItem);
                }
            } else {
                newWorkcontentList.add(t);
            }
        }


        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        CellStyle wrapStyle = wb.createCellStyle();
        wrapStyle.setWrapText(true);    //设置自动换行
        //创建sheet页
        Sheet sheet = wb.createSheet("sheet1");
        //设置列的宽度，第一个参数为列的序号，从0开始，第二参数为列宽，单位1/256个字节
        sheet.setColumnWidth(0, 15 * 256);
        sheet.setColumnWidth(1, 16 * 256);
        sheet.setColumnWidth(2, 13 * 256);
        sheet.setColumnWidth(3, 13 * 256);
        sheet.setColumnWidth(4, 13 * 256);
        sheet.setColumnWidth(5, 13 * 256);
        sheet.setColumnWidth(6, 13 * 256);
        sheet.setColumnWidth(7, 13 * 256);
        sheet.setColumnWidth(8, 13 * 256);
        sheet.setColumnWidth(9, 13 * 256);
        sheet.setColumnWidth(10, 13 * 256);
        sheet.setColumnWidth(11, 13 * 256);
        sheet.setColumnWidth(12, 13 * 256);
        sheet.setColumnWidth(13, 13 * 256);
        sheet.setColumnWidth(14, 13 * 256);
        sheet.setColumnWidth(15, 13 * 256);
        sheet.setColumnWidth(16, 13 * 256);
        sheet.setColumnWidth(17, 13 * 256);
        sheet.setColumnWidth(18, 13 * 256);
        sheet.setColumnWidth(19, 13 * 256);
        sheet.setColumnWidth(20, 13 * 256);
        sheet.setColumnWidth(21, 13 * 256);
        sheet.setColumnWidth(22, 13 * 256);

        //设置开始行和开始列
        Row row0 = sheet.createRow(0);
        CellStyle style = wb.createCellStyle();
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        Font headerFont = wb.createFont();
//        headerFont.setFontName("Arial");
//        headerFont.setFontHeightInPoints((short) 12);
//        headerFont.setBold(false);
//        headerFont.setColor(IndexedColors.BLACK.getIndex());
//        style.setFont(headerFont);
        Cell cell0 = row0.createCell(0);
        row0.createCell(0).setCellValue("企业名称");
        row0.getCell(0).setCellStyle(style);
        row0.createCell(1).setCellValue("作业类型");
        row0.getCell(1).setCellStyle(style);
        row0.createCell(2).setCellValue("作业开始时间");
        row0.getCell(2).setCellStyle(style);
        row0.createCell(3).setCellValue("作业结束时间");
        row0.getCell(3).setCellStyle(style);
        row0.createCell(4).setCellValue("作业地址");
        row0.getCell(4).setCellStyle(style);
        row0.createCell(5).setCellValue("是否承包商作业");
        row0.getCell(5).setCellStyle(style);
        row0.createCell(6).setCellValue("作业单位");
        row0.getCell(6).setCellStyle(style);
        row0.createCell(7).setCellValue("负责人");
        row0.getCell(7).setCellStyle(style);
        row0.createCell(8).setCellValue("联系电话");
        row0.getCell(8).setCellStyle(style);
        row0.createCell(9).setCellValue("作业是否变更");
        row0.getCell(9).setCellStyle(style);
        row0.createCell(10).setCellValue("变更原因");
        row0.getCell(10).setCellStyle(style);
        row0.createCell(11).setCellValue("作业是否取消");
        row0.getCell(11).setCellStyle(style);
        row0.createCell(12).setCellValue("取消原因");
        row0.getCell(12).setCellStyle(style);
//        row0.createCell(13).setCellValue("装置批准人");row0.getCell(13).setCellStyle(style);
//        row0.createCell(14).setCellValue("短号");row0.getCell(14).setCellStyle(style);
//        row0.createCell(15).setCellValue("用户单位");row0.getCell(15).setCellStyle(style);
//        row0.createCell(16).setCellValue("用户主管");row0.getCell(16).setCellStyle(style);
//        row0.createCell(17).setCellValue("短号");row0.getCell(17).setCellStyle(style);
//        row0.createCell(18).setCellValue("危害工作许可证号");row0.getCell(18).setCellStyle(style);
//        row0.createCell(19).setCellValue("动火作业许可证号");row0.getCell(19).setCellStyle(style);
//        row0.createCell(20).setCellValue("限制空间许可证号");row0.getCell(20).setCellStyle(style);
//        row0.createCell(21).setCellValue("盲板作业许可证号");row0.getCell(21).setCellStyle(style);
//        row0.createCell(22).setCellValue("高处作业许可证号");row0.getCell(22).setCellStyle(style);
        //填充数据
        int rowIndex = 1;
        int columnIndex = 1;
        StringBuilder contentUserWorkType = new StringBuilder();
        String cuw = "";
        for (TInvoiceWorkcontent t : newWorkcontentList) {
//            if (t.getBookingworkticket().getStatus() != 3) {
//                continue;
//            }
            Row row = sheet.createRow(rowIndex);
            row.createCell(0).setCellValue("扬子石化-巴斯夫有限责任公司");
            //作业类型
            if (t.getWorkType() != null) {
                String newStr = t.getWorkType() + ",";
                String[] wtArr = newStr.split(",");
                List<String> contentlist = Arrays.asList(wtArr);
                for (SysDictData p : book_work_type) {
                    for (String c : contentlist)
                        if (c.equals(p.getDictValue())) {
                            contentUserWorkType.append("," + p.getDictLabel());//作业类型
                        }
                }
                if (contentUserWorkType.toString().startsWith(",")) {
                    cuw = contentUserWorkType.substring(1);
                }
                row.createCell(1).setCellValue(cuw);
            }
            if (t.getBookingworkticket().getWorkStartTime() != null) {
                row.createCell(2).setCellValue(new SimpleDateFormat("yyyy/MM/dd").format(t.getBookingworkticket().getWorkStartTime()));
            }
            //
            if (t.getBookingworkticket().getWorkStartTime() != null) {
                row.createCell(3).setCellValue(new SimpleDateFormat("yyyy/MM/dd").format(t.getBookingworkticket().getWorkStartTime()));
            }
            //作业地址
            if (t.getWorkDescription() != null) {
                row.createCell(4).setCellValue(t.getWorkDescription());
            }
            row.createCell(5).setCellValue("是");
            //作业单位
            if (t.getBookingworkticket().getWorkUnit() != null) {
                row.createCell(6).setCellValue(t.getBookingworkticket().getWorkUnit());
            }
            //
            row.createCell(7).setCellValue(t.getBookingworkticket().getContact());
            //
            row.createCell(8).setCellValue(t.getBookingworkticket().getPhonenumber());
            //
            row.createCell(9).setCellValue("否");
            //
            row.createCell(10).setCellValue("");
            //
            row.createCell(11).setCellValue("否");
            //
            row.createCell(12).setCellValue("");
//            //装置批准人
//            row.createCell(13).setCellValue(t.getBookingworkticket().getUserSupName());
//            //装置批准人短号
//            row.createCell(14).setCellValue(t.getBookingworkticket().getUserSupPhone());
//            //用户单位
//            row.createCell(15).setCellValue(t.getBookingworkticket().getUserUnit());
//            //用户主管
//            row.createCell(16).setCellValue(t.getBookingworkticket().getUserMgName());
//            //用户主管短号
//            row.createCell(17).setCellValue(t.getBookingworkticket().getUserMgPhone());
//            //危害工作许可证号
//            row.createCell(18).setCellValue(t.getWhgzxkzh());
//            //动火作业许可证号
//            row.createCell(19).setCellValue(t.getDhzyxkzh());
//            //限制空间许可证号
//            row.createCell(20).setCellValue(t.getXzkjxkzh());
//            //盲板作业许可证号
//            row.createCell(21).setCellValue(t.getMbzyxkzh());
//            //高处作业许可证号
//            row.createCell(22).setCellValue(t.getGczyxkzh());


            rowIndex++;
            contentUserWorkType.delete(0, contentUserWorkType.length());
        }
        // 接着上面的最后一行追加
        int rowIndex1 = sheet.getLastRowNum() + 1;
        int columnIndex1 = 1;
        CellStyle setBorder = wb.createCellStyle();
        //设置背景颜色
        setBorder.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        setBorder.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //设置自动换行
        setBorder.setWrapText(true);
        //边框样式
        //设置上边框线条类型
        setBorder.setBorderTop(BorderStyle.THIN);
        //设置右边框线条类型
        setBorder.setBorderRight(BorderStyle.THIN);
        //设置下边框线条类型
        setBorder.setBorderBottom(BorderStyle.THIN);
        //设置左边框线条类型
        setBorder.setBorderLeft(BorderStyle.THIN);
        //设置上边框线条颜色
        setBorder.setTopBorderColor(IndexedColors.BLACK.getIndex());
        //设置右边框线条颜色
        setBorder.setRightBorderColor(IndexedColors.BLACK.getIndex());
        //设置下边框线条颜色
        setBorder.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        //设置左边框线条颜色
        setBorder.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        //对齐方式
        //设置水平对齐方式
        setBorder.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐方式
        setBorder.setVerticalAlignment(VerticalAlignment.CENTER);

        Row row1 = sheet.createRow(rowIndex1);
        row1.createCell(0).setCellValue("日期");
        row1.getCell(0).setCellStyle(setBorder);
        row1.createCell(1).setCellValue("一级动火");
        row1.getCell(1).setCellStyle(setBorder);
        row1.createCell(2).setCellValue("二级动火");
        row1.getCell(2).setCellStyle(setBorder);
        row1.createCell(3).setCellValue("特级动火");
        row1.getCell(3).setCellStyle(setBorder);
        row1.createCell(4).setCellValue("高处作业");
        row1.getCell(4).setCellStyle(setBorder);
        row1.createCell(5).setCellValue("受限空间");
        row1.getCell(5).setCellStyle(setBorder);
        row1.createCell(6).setCellValue("大型吊装");
        row1.getCell(6).setCellStyle(setBorder);
        row1.createCell(7).setCellValue("临时用电");
        row1.getCell(7).setCellStyle(setBorder);
        row1.createCell(8).setCellValue("动土作业");
        row1.getCell(8).setCellStyle(setBorder);
        row1.createCell(9).setCellValue("断路作业");
        row1.getCell(9).setCellStyle(setBorder);
        row1.createCell(10).setCellValue("盲板抽堵");
        row1.getCell(10).setCellStyle(setBorder);
        row1.createCell(11).setCellValue("检维修作业");
        row1.getCell(11).setCellStyle(setBorder);
        row1.createCell(12).setCellValue("清灌作业");
        row1.getCell(12).setCellStyle(setBorder);
        row1.createCell(13).setCellValue("倒灌作业");
        row1.getCell(13).setCellStyle(setBorder);
        row1.createCell(14).setCellValue("切水作业");
        row1.getCell(14).setCellStyle(setBorder);
        row1.createCell(15).setCellValue("变更作业");
        row1.getCell(15).setCellStyle(setBorder);
        row1.createCell(16).setCellValue("承包商作业");
        row1.getCell(16).setCellStyle(setBorder);
        row1.createCell(17).setCellValue("停车装置数");
        row1.getCell(17).setCellStyle(setBorder);
        row1.createCell(18).setCellValue("总计");
        row1.getCell(18).setCellStyle(setBorder);
        //
        int workType0 = 0;
        int workType1 = 0;
        int workType2 = 0;
        int workType3 = 0;
        int workType4 = 0;
        int workType5 = 0;
        int workType6 = 0;
        int workType7 = 0;
        int workType8 = 0;
        int workType9 = 0;
        int workType10 = 0;
        int workType11 = 0;
        int workType12 = 0;
        int workType13 = 0;
        int workType14 = 0;
        int workType15 = 0;
        int workType16 = 0;
        int workType17 = 0;
        //填充下一个表格
        int count = 0;
        for (TInvoiceWorkcontent t : newWorkcontentList) {
            if (t.getBookingworkticket().getStatus() != 3) {
                continue;
            }
            //先将字符串 分割数组 再转成集合 防止出现 1，11这种情况判断不清
            String newStr = t.getWorkType() + ",";
            String[] wtArr = newStr.split(",");
            List<String> contentlist = Arrays.asList(wtArr);
            if (contentlist.contains("2")) {
                workType0++;
            }
            if (contentlist.contains("3")) {
                workType1++;
            }
            if (contentlist.contains("1")) {
                workType2++;
            }
            if (contentlist.contains("5") || contentlist.contains("6") || contentlist.contains("7") || contentlist.contains("8")) {
                workType3++;
            }
            if (contentlist.contains("15")) {
                workType4++;
            }
            if (contentlist.contains("12") || contentlist.contains("13") || contentlist.contains("14")) {
                workType5++;
            }
            if (contentlist.contains("4")) {
                workType6++;
            }
            if (contentlist.contains("9")) {
                workType7++;
            }
            if (contentlist.contains("10")) {
                workType8++;
            }
            if (contentlist.contains("11")) {
                workType9++;//盲板
            }
            if (contentlist.contains("17")) {
                workType11++;//清罐
            }
            if (contentlist.contains("16")) {
                workType12++;//倒灌
            }
            if (contentlist.contains("18")) {
                workType13++;//切水
            } else {
                //变更、承包、停车装置暂无数据
            }
            count++;
        }

        Row row = sheet.createRow(rowIndex1 + 1);
        row.createCell(0).setCellValue("");
        row.createCell(1).setCellValue(workType0);
        row.createCell(2).setCellValue(workType1);
        row.createCell(3).setCellValue(workType2);
        row.createCell(4).setCellValue(workType3);
        row.createCell(5).setCellValue(workType4);
        row.createCell(6).setCellValue(workType5);
        row.createCell(7).setCellValue(workType6);
        row.createCell(8).setCellValue(workType7);
        row.createCell(9).setCellValue(workType8);
        row.createCell(10).setCellValue(workType9);
        row.createCell(11).setCellValue(0);
        row.createCell(12).setCellValue(workType11);
        row.createCell(13).setCellValue(workType12);
        row.createCell(14).setCellValue(workType13);
        row.createCell(15).setCellValue(0);
        row.createCell(16).setCellValue(0);
        row.createCell(17).setCellValue(0);
        row.createCell(18).setCellValue(count);


        OutputStream out = null;
        String filename = ExcelUtil.encodingFilename("预约票台账导出");
        out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
        wb.write(out);
        wb.close();
        out.close();
        return AjaxResult.success(filename);
    }

    /**
     * 值班导出excel
     *
     * @param tInvoiceBookingworkticket
     * @return
     * @throws IOException
     */
    @GetMapping("/exportBookZb")
    public AjaxResult exportBookZb(TInvoiceBookingworkticket tInvoiceBookingworkticket) throws IOException {
        logger.info(JSON.toJSONString(tInvoiceBookingworkticket));
        //字典查询
        List<SysDictData> book_work_type = iSysDictTypeService.selectDictDataByType("book_work_type");

        List<TInvoiceWorkcontent> tInvoiceWorkcontentList = tInvoiceBookingworkticketService.selectTInvoiceWorkcontentList(tInvoiceBookingworkticket);
//        List<TInvoiceWorkcontent> tInvoiceWorkcontentList = tInvoiceWorkcontentList2.subList(0, 100);

        if (tInvoiceWorkcontentList.size() < 1 ) {
            return AjaxResult.error("无导出内容");
        }
        logger.info("tInvoiceWorkcontentList::::::::::::::",tInvoiceWorkcontentList.size());
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        final CountDownLatch latch = new CountDownLatch(tInvoiceWorkcontentList.size()); //相同线程数量的计数
        for (TInvoiceWorkcontent workcontent : tInvoiceWorkcontentList) {
            executorService.execute(() -> {
                try {
                    TInvoiceBookingworkticket bookingworkticket = tInvoiceBookingworkticketService.selectTInvoiceBookingworkticketById(workcontent.getBookingticketId());
                    SysUser mg = sysUserService.selectUserById(bookingworkticket.getUserMg());
                    bookingworkticket.setUserMgDeptName(mg.getDept().getDeptName());
                    if (bookingworkticket.getUserSupId() != null) {
                        SysUser sup = sysUserService.selectUserById(Long.parseLong(bookingworkticket.getUserSupId()));
                        bookingworkticket.setUserSupDeptName(sup.getDept().getDeptName());
                    }
                    workcontent.setBookingworkticket(bookingworkticket);
                } catch (Exception e) {
                    logger.error("e:", e);
                }finally {
                    latch.countDown();
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        //除去作废的票 以及 续票
        Iterator<TInvoiceWorkcontent> iterator = tInvoiceWorkcontentList.iterator();
        while (iterator.hasNext()) {
            TInvoiceWorkcontent t = iterator.next();
            if (t.getBookingworkticket().getStatus() != 3 || t.getXpxp().equals("12")) {
                iterator.remove();
            }
        }

//        List<TInvoiceWorkcontent> newWorkcontentList = new ArrayList<>();
        //多个工作类型拆分成多条数据
//        for (TInvoiceWorkcontent t: tInvoiceWorkcontentList
//        ) {
//            String[] wtArr=t.getWorkType().split(",");
//            if (wtArr.length > 1) {
//                for (int i = 0; i < wtArr.length; i++) {
//                    TInvoiceWorkcontent arrItem = new TInvoiceWorkcontent();
//                    BeanUtils.copyProperties(t, arrItem);
//                    arrItem.setWorkType(wtArr[i]);
//                    newWorkcontentList.add(arrItem);
//                }
//            }else {
//                newWorkcontentList.add(t);
//            }
//        }


        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        CellStyle wrapStyle = wb.createCellStyle();
        wrapStyle.setWrapText(true);    //设置自动换行
        //创建sheet页
        Sheet sheet = wb.createSheet("sheet1");
        //设置列的宽度，第一个参数为列的序号，从0开始，第二参数为列宽，单位1/256个字节
        sheet.setColumnWidth(0, 12 * 256);
        sheet.setColumnWidth(1, 26 * 256);
        sheet.setColumnWidth(2, 13 * 256);
        sheet.setColumnWidth(3, 26 * 256);
        sheet.setColumnWidth(4, 26 * 256);
        sheet.setColumnWidth(5, 12 * 256);
        sheet.setColumnWidth(6, 12 * 256);
        sheet.setColumnWidth(7, 12 * 256);
        sheet.setColumnWidth(8, 26 * 256);
        sheet.setColumnWidth(9, 40 * 256);
        sheet.setColumnWidth(10, 40 * 256);
        sheet.setColumnWidth(11, 40 * 256);
        sheet.setColumnWidth(12, 40 * 256);
        sheet.setColumnWidth(13, 40 * 256);
        sheet.setColumnWidth(14, 40 * 256);
        sheet.setColumnWidth(15, 40 * 256);
        sheet.setColumnWidth(16, 40 * 256);
        sheet.setColumnWidth(17, 40 * 256);
        sheet.setColumnWidth(18, 40 * 256);
        sheet.setColumnWidth(19, 40 * 256);
        sheet.setColumnWidth(20, 40 * 256);
        sheet.setColumnWidth(21, 40 * 256);
        sheet.setColumnWidth(22, 40 * 256);

        //设置开始行和开始列
        Row row0 = sheet.createRow(0);
        CellStyle style = wb.createCellStyle();
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        Cell cell0 = row0.createCell(0);
        row0.createCell(0).setCellValue("作业开始时间");
        row0.getCell(0).setCellStyle(style);
        row0.createCell(1).setCellValue("作业类型");
        row0.getCell(1).setCellStyle(style);
        row0.createCell(2).setCellValue("作业区域单元");
        row0.getCell(2).setCellStyle(style);
        row0.createCell(3).setCellValue("作业地址");
        row0.getCell(3).setCellStyle(style);
        row0.createCell(4).setCellValue("工艺主管");
        row0.getCell(4).setCellStyle(style);
        row0.createCell(5).setCellValue("作业单位");
        row0.getCell(5).setCellStyle(style);
        row0.createCell(6).setCellValue("负责人");
        row0.getCell(6).setCellStyle(style);
        row0.createCell(7).setCellValue("联系电话");
        row0.getCell(7).setCellStyle(style);
        row0.createCell(8).setCellValue("用户");
        row0.getCell(8).setCellStyle(style);
        row0.createCell(9).setCellValue("票号");
        row0.getCell(9).setCellStyle(style);

        //填充数据
        int rowIndex = 1;
        int columnIndex = 1;
        StringBuilder contentUserWorkType = new StringBuilder();
        String cuw = "";
        for (TInvoiceWorkcontent t : tInvoiceWorkcontentList) {
            try {
                if (t.getBookingworkticket().getStatus() != 3) {
                    continue;
                }
                Row row = sheet.createRow(rowIndex);
                //开始时间
                if (t.getBookingworkticket().getWorkStartTime() != null) {
                    row.createCell(0).setCellValue(new SimpleDateFormat("yyyy/MM/dd").format(t.getBookingworkticket().getWorkStartTime()));
                }
                //作业类型
                if (t.getWorkType() != null) {
                    String newStr = t.getWorkType() + ",";
                    String[] wtArr = newStr.split(",");
                    List<String> contentlist = Arrays.asList(wtArr);
                    for (SysDictData p : book_work_type) {
                        for (String c : contentlist)
                            if (c.equals(p.getDictValue())) {
                                contentUserWorkType.append("," + p.getDictLabel());//作业类型
                            }
                    }
                    if (contentUserWorkType.toString().startsWith(",")) {
                        cuw = contentUserWorkType.substring(1);
                    }
                    row.createCell(1).setCellValue(cuw);
                }
                if (t.getBookingworkticket().getWorkArea() != null) {
                    row.createCell(2).setCellValue(t.getBookingworkticket().getWorkArea());
                }
                //作业地址
                if (t.getWorkDescription() != null) {
                    row.createCell(3).setCellValue(t.getWorkDescription());
                }
                //工艺主管

                row.createCell(4).setCellValue(t.getBookingworkticket().getUserSupDeptName() + " " + t.getBookingworkticket().getUserSupName() + " " + t.getBookingworkticket().getUserSupPhone());
                //作业单位
                if (t.getBookingworkticket().getWorkUnit() != null) {
                    row.createCell(5).setCellValue(t.getBookingworkticket().getWorkUnit());
                }
                //负责人
                row.createCell(6).setCellValue(t.getBookingworkticket().getContact());
                //电话
                row.createCell(7).setCellValue(t.getBookingworkticket().getPhonenumber());
                //用户  承包商和用户单位一致时，用户显示为空；用户单位为CBP/C 时，用户显示为空；
                if (t.getBookingworkticket().getWorkUnit().equals(t.getBookingworkticket().getUserMgDeptName()) || t.getBookingworkticket().getUserMgDeptName().equals("CBP/C")) {
                    row.createCell(8).setCellValue("");
                } else {
                    row.createCell(8).setCellValue(t.getBookingworkticket().getUserMgDeptName() + " " + t.getBookingworkticket().getUserMgName() + " " + t.getBookingworkticket().getUserMgPhone());
                }
                //票号
                String ticketNo = t.getWhgzxkzh() + t.getDhzyxkzh() + t.getGczyxkzh() + t.getMbzyxkzh() + t.getXzkjxkzh() + t.getYqxkzh();
                row.createCell(9).setCellValue(ticketNo.replaceAll("null", ""));
                rowIndex++;
                contentUserWorkType.delete(0, contentUserWorkType.length());
            } catch (Exception e) {
                logger.error("e" , e);
            }

        }

        OutputStream out = null;
        String filename = ExcelUtil.encodingFilename("预约票台账导出");
        out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
        wb.write(out);
        wb.close();
        out.close();
        return AjaxResult.success(filename);
    }

    /**
     * 获取预约作业票台账详细信息
     */
//    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TInvoiceBookingworkticket t = tInvoiceBookingworkticketService.selectTInvoiceBookingworkticketById(id);
        List<TInvoiceWorkcontent> list = tInvoiceBookingworkticketService.selectTInvoiceWorkcontentBybookingticketId(t.getId());
        t.settInvoiceWorkcontentList(list);
        return AjaxResult.success(t);
    }

    @GetMapping(value = "/infoById/{id}")
    public AjaxResult getInfoById(@PathVariable("id") Long id) {
        TInvoiceBookingworkticket t = tInvoiceBookingworkticketService.selectBookingworkticketById(id);
        List<TInvoiceWorkcontent> list = tInvoiceBookingworkticketService.selectTInvoiceWorkcontentBybookingticketId(t.getId());
        t.settInvoiceWorkcontentList(list);
        return AjaxResult.success(t);
    }

    /**
     * 票号生成文件
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:edit')")
    @GetMapping(value = "/assion{id}")
    public AjaxResult assion(@PathVariable("id") Long id) {
        TInvoiceBookingworkticket tInvoiceBookingworkticket = tInvoiceBookingworkticketService.selectTInvoiceBookingworkticketById(id);
        String url = null;
        try {
            url = PreView(id);
        } catch (IOException e) {
            e.printStackTrace();
        }

        tInvoiceBookingworkticket.setFilename(url);
        tInvoiceBookingworkticketService.updateTInvoiceBookingworkticket(tInvoiceBookingworkticket);
        return AjaxResult.success(url);
    }


    /**
     * 新增预约作业票台账
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:add')")
    @Log(title = "预约作业票台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TInvoiceBookingworkticket tInvoiceBookingworkticket) {
        List<TInvoiceWorkcontent> workcontentList = tInvoiceBookingworkticket.gettInvoiceWorkcontentList();
        if ("12".equals(workcontentList.get(0).getXpxp())) { //续票
            TInvoiceWorkcontent tw = workcontentList.get(0);
//            if (StringUtils.isEmpty(tw.getGczyxkzh()) && StringUtils.isEmpty(tw.getDhzyxkzh()) && StringUtils.isEmpty(tw.getXzkjxkzh()) && StringUtils.isEmpty(tw.getMbzyxkzh()) && StringUtils.isEmpty(tw.getWhgzxkzh())) {
//                return AjaxResult.error("没有工作票号，无法预约");
//            }
//            int i = tInvoiceWorkcontentMapper.countXp(workcontentList.get(0));
//            logger.info("预约票数量:" + i);
//            if (i >= 10) {
//                return AjaxResult.error("超过预约票数量上限10");
//            }
        }
        //先查当前登录的用户关联的承包商信息， 将名称 联系人 电话 都关联起来
        String createAccount = SecurityUtils.getUsername();
        SysUser sysUser = sysUserService.selectUserByUserName(createAccount);
        tInvoiceBookingworkticket.setCreaterCode(getUserId());
        tInvoiceBookingworkticket.setContact(sysUser.getNickName());
        tInvoiceBookingworkticket.setPhonenumber(sysUser.getPhonenumber());
        tInvoiceBookingworkticketService.insertTInvoiceBookingworkticket(tInvoiceBookingworkticket);
        Long didi = tInvoiceBookingworkticket.getId();
        for (int i = 0; i < workcontentList.size(); i++) {
            TInvoiceWorkcontent wt = workcontentList.get(i);
            wt.setBookingticketId(didi);
            //关联的票号
            tInvoiceBookingworkticketService.insertTInvoiceWorkcontent(wt);
       /*     wt.setReservationNumber("Steam Cracker"+tInvoiceBookingworkticket.getId().toString()+"-"+wt.getId().toString());
            tInvoiceBookingworkticketService.updateTInvoiceWorkcontent(wt);*/
        }
        return AjaxResult.success(didi);
    }

    /**
     * 修改预约作业票台账
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:edit')")
    @Log(title = "预约作业票台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TInvoiceBookingworkticket tInvoiceBookingworkticket) {
        //这是修改时上传的 list ，先全部清空，在重新添加现有的
        List<Long> ids = new ArrayList<>();
        List<TInvoiceWorkcontent> tInvoiceWorkcontentList = tInvoiceBookingworkticket.gettInvoiceWorkcontentList();
        List<TInvoiceWorkcontent> oldtInvoiceWorkcontentList = tInvoiceBookingworkticketService.selectTInvoiceWorkcontentBybookingticketId(tInvoiceBookingworkticket.getId());
        for (TInvoiceWorkcontent workcontent : oldtInvoiceWorkcontentList) {
            ids.add((workcontent.getId()));
        }
        Long[] workcontentIds = ids.toArray(new Long[0]);
        tInvoiceBookingworkticketService.deleteTInvoiceWorkcontentByIds(workcontentIds);
        for (TInvoiceWorkcontent workcontent : tInvoiceWorkcontentList) {
            workcontent.setBookingticketId(tInvoiceBookingworkticket.getId());
            tInvoiceBookingworkticketService.insertTInvoiceWorkcontent(workcontent);
        }

        return toAjax(tInvoiceBookingworkticketService.updateTInvoiceBookingworkticket(tInvoiceBookingworkticket));
    }

    /**
     * 删除预约作业票台账
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:remove')")
    @Log(title = "预约作业票台账", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tInvoiceBookingworkticketService.deleteTInvoiceBookingworkticketByIds(ids));
    }

    /**
     * 删除预约作业票台账
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:remove')")
    @Log(title = "预约作业票台账作废", businessType = BusinessType.DELETE)
    @DeleteMapping("cancel/{id}")
    public AjaxResult cancelBook(@PathVariable Long id) {
        return toAjax(tInvoiceBookingworkticketService.cancelTInvoiceBookingworkticketById(id));
    }


    /**
     * @param id 生成文件名
     * @return
     * @throws IOException
     */
    public String PreView(Long id) throws IOException {
        ITInvoiceBookingworkticketService tInvoiceBookingworkticketService = (ITInvoiceBookingworkticketService) SpringContextUtils.getBean("tInvoiceBookingworkticketService");
        //根据ID查询并生成
        TInvoiceBookingworkticket tInvoiceBookingworkticket = tInvoiceBookingworkticketService.selectTInvoiceBookingworkticketById(id);
        String url = this.createBookingworkticketWord(tInvoiceBookingworkticket);
        return url;
    }

    /**
     * 生成word
     */
    public String createBookingworkticketWord(TInvoiceBookingworkticket invoiceBookingworkticket) throws IOException {
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(invoiceBookingworkticket);
        // 模板路径
        String templatePath = "static/word/invoice/book.docx";
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "ticketWord";
        // 生成word的文件名称
        // 承包商+联系人+当前时间
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"));
        String fileName = invoiceBookingworkticket.getWorkUnit() + invoiceBookingworkticket.getContact() + invoiceBookingworkticket.getId() + ".docx";
        String wordPath = this.createWord(templatePath, fileDir, fileName, params);

        return wordPath;
    }

    /**
     * 获取word数据
     */
    public Map<String, Object> getWordData(TInvoiceBookingworkticket ticket) {
        Map<String, Object> params = new HashMap<>();
        ITApproveReserveInvoiceService tApproveReserveInvoiceService = (ITApproveReserveInvoiceService) SpringContextUtils.getBean("tApproveReserveInvoiceService");
        ISysUserService sysUserService = (ISysUserService) SpringContextUtils.getBean("sysUserService");
        ISysDictTypeService iSysDictTypeService = (ISysDictTypeService) SpringContextUtils.getBean("sysDictTypeService");
        ITInvoiceBookingworkticketService tInvoiceBookingworkticketService = (ITInvoiceBookingworkticketService) SpringContextUtils.getBean("tInvoiceBookingworkticketService");
        List<TInvoiceWorkcontent> tInvoiceWorkcontentList = tInvoiceBookingworkticketService.selectTInvoiceWorkcontentBybookingticketId(ticket.getId());
        //字典查询
        List<SysDictData> book_work_type = iSysDictTypeService.selectDictDataByType("book_work_type");
        List<SysDictData> book_user_unit = iSysDictTypeService.selectDictDataByType("book_user_unit");
        List<SysDictData> book_risk_level = iSysDictTypeService.selectDictDataByType("book_risk_level");
        //构造模板的value
        StringBuilder content = new StringBuilder();
        StringBuilder contentUserUnit = new StringBuilder();
        StringBuilder contentUserWorkType = new StringBuilder();
        StringBuilder contentTicket = new StringBuilder();
        String ct = new String();
        String cuw = new String();
        //关联的申请流程
        TApproveReserveInvoice tApproveReserveInvoice = tApproveReserveInvoiceService.selectTApproveReserveInvoiceByinvoiceId(ticket.getId().toString());
        for (int i = 0; i < tInvoiceWorkcontentList.size(); i++) {
            TInvoiceWorkcontent tInvoiceWorkcontent = tInvoiceWorkcontentList.get(i);
            //不为空的字段进行拼接
            if (tInvoiceWorkcontent.getRiskLevel() != null) {
                for (SysDictData p : book_risk_level) {
                    if (tInvoiceWorkcontent.getRiskLevel().toString().equals(p.getDictValue())) {
                        content.append(ticket.getWorkArea() + "," + tInvoiceWorkcontent.getWorkDescription());//装置名称
                    }
                }
            }
            params.put("content" + i, Texts.of(content.toString()).fontSize(10).bold().create());
            //用户单位
            if (ticket.getUserUnit() != null) {
                for (SysDictData p : book_user_unit) {
                    if (ticket.getUserUnit().toString().equals(p.getDictValue())) {
                        contentUserUnit.append(p.getDictLabel());//用户单位
                    }
                }
                if (!params.containsKey("userUnit")) {
                    params.put("userUnit", Texts.of(contentUserUnit.toString()).fontSize(10).bold().create());
                }
            }
            //用户主管
            if (ticket.getUserMg() != null) {
                SysUser sysUser = sysUserService.selectUserById(ticket.getUserMg());
                if (!params.containsKey("userMg")) {
                    if (sysUser.getSignUrl() != null && new File(sysUser.getSignUrl()).exists()) {
                        params.put("userMg", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(100, 40).create());
                    }
                }
                if (!params.containsKey("userNumber")) {
                    params.put("userNumber", Texts.of(sysUser.getPhonenumber()).fontSize(10).bold().create());
                }
            }
            //承包商
            if (ticket.getWorkUnit() != null) {
                if (!params.containsKey("workUnit")) {
                    params.put("workUnit", Texts.of(ticket.getWorkUnit()).fontSize(10).bold().create());
                }
            }
            //申请人签名
            if (tApproveReserveInvoice.getUserId() != null) {
                if (!params.containsKey("userName")) {
                    SysUser sysUser = sysUserService.selectUserById(tApproveReserveInvoice.getUserId());
                    if (sysUser.getSignUrl() != null && new File(sysUser.getSignUrl()).exists()) {
                        params.put("userName", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(100, 40).create());
                    }
                }
            }
            //联系电话
            if (tApproveReserveInvoice.getUserId() != null) {
                SysUser sysUser = sysUserService.selectUserById(tApproveReserveInvoice.getUserId());
                String dName = sysUser.getPhonenumber();
                //如果没有添加过  找到用户所属的部门添加进去
                if (!params.containsKey("conUnit")) {
                    params.put("conUnit", Texts.of(dName).fontSize(10).bold().create());
                }
            }
            //作业类型 遍历查找 追加到该条作业内容
            if (tInvoiceWorkcontent.getWorkType() != null) {
                //先将字符串 分割数组 再转成集合 防止出现 1，11这种情况判断不清
                String newStr = tInvoiceWorkcontent.getWorkType() + ",";
                String[] wtArr = newStr.split(",");
                List<String> contentlist = Arrays.asList(wtArr);
                for (SysDictData p : book_work_type) {
                    for (String t : contentlist)
                        if (t.equals(p.getDictValue())) {
                            contentUserWorkType.append("," + p.getDictLabel());//作业类型
                        }
                }
                if (contentUserWorkType.toString().startsWith(",")) {
                    cuw = contentUserWorkType.substring(1);
                }
                params.put("workType" + i, Texts.of(cuw).fontSize(10).bold().create());

            }
            //作业开始时间
            if (ticket.getWorkStartTime() != null) {
                params.put("workStartTime", Texts.of(DateUtils.dateTime(ticket.getWorkStartTime())).fontSize(10).bold().create());
            }
            //作业结束时间
            if (ticket.getWorkEndTime() != null) {
                params.put("workEndTime", Texts.of(DateUtils.dateTime(ticket.getWorkEndTime())).fontSize(10).bold().create());
            }
            //关联票号  有几个许可证 就追加几个
            if (ticket != null) {
                if (!StringUtils.isEmpty(tInvoiceWorkcontent.getWhgzxkzh())) {
                    contentTicket.append(tInvoiceWorkcontent.getWhgzxkzh());
                }
                if (!StringUtils.isEmpty(tInvoiceWorkcontent.getDhzyxkzh())) {
                    contentTicket.append("," + tInvoiceWorkcontent.getDhzyxkzh());
                }
                if (!StringUtils.isEmpty(tInvoiceWorkcontent.getXzkjxkzh())) {
                    contentTicket.append("," + tInvoiceWorkcontent.getXzkjxkzh());
                }
                if (!StringUtils.isEmpty(tInvoiceWorkcontent.getMbzyxkzh())) {
                    contentTicket.append("," + tInvoiceWorkcontent.getMbzyxkzh());
                }
                if (!StringUtils.isEmpty(tInvoiceWorkcontent.getGczyxkzh())) {
                    contentTicket.append("," + tInvoiceWorkcontent.getGczyxkzh());
                }
                if (contentTicket.toString().startsWith(",")) {
                    ct = contentTicket.substring(1);
                } else {
                    ct = contentTicket.toString();
                }
                params.put("associated" + i, Texts.of(ct).fontSize(10).bold().create());
            }

            //申请单编号  字体红色
            if (!params.containsKey("application")) {
                params.put("application", Texts.of(DateUtils.dateTimeNow()).fontSize(10).color("FF0000").bold().create());
            }
            //暂定的批准日期
            if (tApproveReserveInvoice.getEnddate() != null) {
                if (!params.containsKey("applyDate")) {
                    params.put("applyDate", Texts.of(DateUtils.dateTime(tApproveReserveInvoice.getEnddate())).fontSize(10).bold().create());
                }
            }
            //装置批准人
            if (tApproveReserveInvoice.getDevSupId() != null) {
                if (!params.containsKey("zzUser")) {
                    SysUser sysUser = sysUserService.selectUserById(tApproveReserveInvoice.getDevSupId());
                    if (sysUser.getSignUrl() != null && new File(sysUser.getSignUrl()).exists()) {
                        params.put("zzUser", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(100, 40).create());
                    }
                }
                //装置批准人的电话
                if (!params.containsKey("zjNumber")) {
                    SysUser sysUser = sysUserService.selectUserById(tApproveReserveInvoice.getDevSupId());
                    if (sysUser.getPhonenumber() != null) {
                        params.put("zjNumber", Texts.of(sysUser.getPhonenumber()).fontSize(10).bold().create());
                    }
                }
            }
            //装置工程师  如果涉及
            if (tApproveReserveInvoice.getDevEngineerId() != null) {
                if (!params.containsKey("zjgcs")) {
                    SysUser sysUser = sysUserService.selectUserById(tApproveReserveInvoice.getDevEngineerId());
                    if (sysUser.getSignUrl() != null && new File(sysUser.getSignUrl()).exists()) {
                        params.put("zjgcs", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(100, 40).create());
                    }
                }
                //批准日期
                if (!params.containsKey("DateOne")) {
                    if (tApproveReserveInvoice.getEnddate() != null) {
                        params.put("DateOne", Texts.of(DateUtils.dateTime(tApproveReserveInvoice.getEnddate())).fontSize(10).bold().create());
                    }
                }
            }
            //装置经理(副)  如果涉及
            if (tApproveReserveInvoice.getManagerconId() != null) {
                if (!params.containsKey("zzjl")) {
                    SysUser sysUser = sysUserService.selectUserById(tApproveReserveInvoice.getManagerconId());
                    if (sysUser.getSignUrl() != null && new File(sysUser.getSignUrl()).exists()) {
                        params.put("zzjl", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(100, 40).create());
                    }
                }
                if (!params.containsKey("DateTwo")) {
                    if (tApproveReserveInvoice.getEnddate() != null) {
                        params.put("DateTwo", Texts.of(DateUtils.dateTime(tApproveReserveInvoice.getEnddate())).fontSize(10).bold().create());
                    }
                }

            }
            content.delete(0, content.length());
            contentUserWorkType.delete(0, contentUserWorkType.length());
            contentTicket.delete(0, contentTicket.length());
        }
        // 渲染文本
        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("/" + "ticketWord"), fileName);
        return pathFileName;
    }

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