package com.rongwei.sfcommon.sys.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aspose.words.*;
import com.aspose.words.Font;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwe.scentity.domian.*;
import com.rongwe.scentity.vo.AspSafetyEmergencyDrillPlanVo;
import com.rongwe.scentity.vo.AspSafetyTeamMemberVo;
import com.rongwe.scentity.vo.AspSafetyTeamVo;
import com.rongwei.rwadmincommon.system.domain.SysDictDo;
import com.rongwei.rwadmincommon.system.service.SysDictService;
import com.rongwei.rwcommon.base.exception.CustomException;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.safecommon.utils.JSCommonUtils;
import com.rongwei.sfcommon.sys.dao.AspSafetyDrillProgrammeDao;
import com.rongwei.sfcommon.sys.service.AspSafetyDrillProgrammeMsgNotifyRecordService;
import com.rongwei.sfcommon.sys.service.AspSafetyDrillProgrammeService;
import com.rongwei.sfcommon.sys.service.AspSafetyEmergencyPlanService;
import com.rongwei.sfcommon.utils.AsposeWordsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 安全应急-演练方案 服务实现类
 * </p>
 *
 * @author wm
 * @since 2023-11-13
 */
@Service
@Slf4j
public class AspSafetyDrillProgrammeServiceImpl extends ServiceImpl<AspSafetyDrillProgrammeDao, AspSafetyDrillProgrammeDo> implements AspSafetyDrillProgrammeService {

    @Autowired
    private AspSafetyEmergencyPlanService aspSafetyEmergencyPlanService;

    @Autowired
    private SysDictService dictService;

    @Autowired
    private AspSafetyDrillProgrammeMsgNotifyRecordService drillProgrammeMsgNotifyRecordService;

    /**
     * 发布演练方案（定时处理）
     */
    @Override
    public void publish() {

        //找出所有未演练状态的演练方案
        LambdaQueryWrapper<AspSafetyDrillProgrammeDo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AspSafetyDrillProgrammeDo::getDrillstatus, "20");

        Date nowDate = new Date();
        String format = DateUtil.format(nowDate, "yyyy-MM-dd");
        DateTime dateTime = DateUtil.parse(format.concat(" 00:00:00"), "yyyy-MM-dd HH:mm:ss");

        queryWrapper.between(AspSafetyDrillProgrammeDo::getDrilltime, dateTime, nowDate);
        queryWrapper.apply("DRILLTIME < now()");
//        queryWrapper.apply("DAY( DRILLTIME ) = DAY (NOW())");
        List<AspSafetyDrillProgrammeDo> list = list(queryWrapper);

        if (ObjectUtil.isEmpty(list)) {
            return;
        }

        List<AspSafetyDrillProgrammeDo> updateList = new ArrayList<>(list.size());
        list.forEach(item -> {
            AspSafetyDrillProgrammeDo entity = new AspSafetyDrillProgrammeDo();
            entity.setId(item.getId());
            entity.setDrillstatus("30");
            updateList.add(entity);
        });

        this.updateBatchById(updateList);
    }

    /**
     * 消息发布
     *
     * @param id
     */
    @Override
    public void sendMsg(String id) {
        AspSafetyDrillProgrammeDo programmeDo = getById(id);
        AspSafetyEmergencyPlan plan = aspSafetyEmergencyPlanService.getById(programmeDo.getPlanid());
        notifyMsg(programmeDo, plan);
    }

    /**
     * 前三天和当天提醒
     */
    @Override
    public void notify3Day() {
        //找出所有未演练状态的演练方案
        LambdaQueryWrapper<AspSafetyDrillProgrammeDo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AspSafetyDrillProgrammeDo::getDrillstatus, "20");

        queryWrapper.apply("DATE_FORMAT( DRILLTIME, '%Y-%m-%d' ) = DATE_FORMAT( DATE_SUB( NOW(), INTERVAL -3 DAY ), '%Y-%m-%d' )");

        List<AspSafetyDrillProgrammeDo> list = list(queryWrapper);

        notifyMsg(list);
    }

    /**
     * 由于存在定时修改状态，需要提醒当天已演练和未演练
     */
    @Override
    public void notifyCurrentDay() {
        //找出所有未演练状态的演练方案
        LambdaQueryWrapper<AspSafetyDrillProgrammeDo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(AspSafetyDrillProgrammeDo::getDrillstatus, "20", "30");
        queryWrapper.apply("DATE_FORMAT( DRILLTIME, '%Y-%m-%d' ) = DATE_FORMAT(NOW(), '%Y-%m-%d' )");
        queryWrapper.notExists("select * from asp_safety_drill_programme_msg_notify_record where DATE_FORMAT( asp_safety_drill_programme.DRILLTIME, '%Y-%m-%d' ) = DATE_FORMAT(asp_safety_drill_programme_msg_notify_record.CREATEDATE, '%Y-%m-%d' ) and PROGRAMMEID = asp_safety_drill_programme.ID");

        List<AspSafetyDrillProgrammeDo> list = list(queryWrapper);

        notifyMsg(list);
    }

    @Override
    public void exportEmergencyDrillPlanWord(String startDate, String endDate, HttpServletResponse response) throws Exception {
        boolean wordLicense = AsposeWordsUtils.getWordLicense();
        //根据时间段查询数据
        List<AspSafetyEmergencyDrillPlanVo> list = this.baseMapper.selectSafetyEmergencyDrillPlanByDate(startDate, endDate);

        // 创建空白文档
        Document doc = new Document();

        DocumentBuilder builder = new DocumentBuilder(doc);

        builder.getPageSetup().setPaperSize(PaperSize.A4);//A4纸
        builder.getPageSetup().setOrientation(Orientation.PORTRAIT);//方向
        builder.getPageSetup().setVerticalAlignment(PageVerticalAlignment.TOP); //垂直对准
        builder.getPageSetup().setLeftMargin(42);//页面左边距
        builder.getPageSetup().setRightMargin(42);//页面右边距

        //获取ParagraphFormat对象，关于行的样式基本都在这里
        ParagraphFormat ph = builder.getParagraphFormat();
        //文字对齐方式
        ph.setAlignment(ParagraphAlignment.CENTER);
        // 单倍行距 = 12 ， 1.5 倍 = 18
        ph.setLineSpacing(12);
        Font font = builder.getFont();
        //大小22
        font.setSize(22);
        //粗体
        font.setBold(true);
        //颜色
        font.setColor(Color.BLACK);
        //字体
        font.setNameFarEast("宋体");
        //添加文字
        String title = startDate.split("-")[0] + "年综合或专项应急演练计划";
        builder.writeln(title);


        font.setSize(10);
        font.setBold(false);


        //开始添加表格
        Table table = builder.startTable();
        //开始添加第一行，并设置表格行高
        RowFormat rowf = builder.getRowFormat();
        rowf.setHeight(40);
        // ....这里rowf可以有很多的设置
        //插入一个单元格
        builder.insertCell();
        //设置单元格是否水平合并
        builder.getCellFormat().setHorizontalMerge(CellMerge.NONE);
        //设置单元格是否垂直合并，None为不合并
        builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
        //设置单元格宽
        builder.getCellFormat().setWidth(40);
        //单元格垂直对齐方向
        builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
        //单元格水平对齐方向
        builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
//        builder.getCellFormat().setFitText(true);//单元格内文字设为多行（默认为单行，会影响单元格宽）


        //单元格内添加文字
        builder.write("序号");
        builder.insertCell();
        builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
        builder.write("演练单位");
        builder.insertCell();
        builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
        builder.write("演练项目");
        builder.insertCell();
        builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
        builder.write("演练时间");
        builder.insertCell();
        builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
        builder.write("演练类别");
        builder.insertCell();
        builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
        builder.write("演练地点");
        builder.insertCell();
        builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
        builder.write("组织部门");
        builder.insertCell();
        builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
        builder.write("负责人");
        builder.insertCell();
        builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
        builder.write("主要参演单位");
        builder.insertCell();
        builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
        builder.write("备注");
        //结束第一行
        builder.endRow();
        for (int i = 1; i <= list.size(); i++) {
            AspSafetyEmergencyDrillPlanVo item = list.get(i - 1);
            //开始行
//            builder.getRowFormat();
//            builder.insertParagraph();
            builder.insertCell();
            builder.write(i + "");
            builder.insertCell();
            builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
            builder.write(item.getDrillunit());
            builder.insertCell();
            builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
            builder.write(item.getDrillname());
            builder.insertCell();
            builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
            builder.write(DateUtil.format(item.getDrilldate(), "yyyy-MM-dd"));
            builder.insertCell();
            builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
            builder.write(item.getDrillCategoryName());
            builder.insertCell();
            builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
            builder.write(item.getDrilllocation());
            builder.insertCell();
            builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
            builder.write(item.getDeptname());
            builder.insertCell();
            builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
            builder.write(item.getDirectornames());
            builder.insertCell();
            builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
            builder.write(item.getJoinunit());
            builder.insertCell();
            builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
            builder.write(item.getRemark());
            //结束行
            builder.endRow();
        }
        //结束表格
        builder.endTable();
//        //设置这个表格的上下左右，内部水平，垂直的线为白色（当背景为白色的时候就相当于隐藏边框了）
//        table.setBorder(BorderType.LEFT, LineStyle.DOUBLE, 1, Color.WHITE, false);
//        table.setBorder(BorderType.TOP, LineStyle.DOUBLE, 1, Color.WHITE, false);
//        table.setBorder(BorderType.RIGHT, LineStyle.DOUBLE, 1, Color.WHITE, false);
//        table.setBorder(BorderType.BOTTOM, LineStyle.DOUBLE, 1, Color.WHITE, false);
//        table.setBorder(BorderType.VERTICAL, LineStyle.DOUBLE, 1, Color.WHITE, false);
        response.setContentType("application/octet-stream;charset=UTF-8");
//        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(title + ".docx", "UTF-8"));
        doc.save(response.getOutputStream(), com.aspose.words.SaveFormat.DOCX);

    }

    @Override
    public void exportAnnualDrillPlanWord(String id, HttpServletResponse response) throws Exception {
        boolean wordLicense = AsposeWordsUtils.getWordLicense();
        //获取数据
        //1、固定数据
        List<AspSafetyOnsiteDisposalPlan> onsiteDisposalPlanList = this.baseMapper.selectOnsiteDisposalPlan();

        //2、主表数据
        AspSafetyAnnualDrillPlan annualDrillPlan = this.baseMapper.selectAnnualDrillPlanById(id);

        //3、月表数据
        List<AspSafetyAnnualDrillPlanMonth> annualDrillPlanMonthList = this.baseMapper.selectAnnualDrillPlanMonthById(id);

        // 创建空白文档
        Document doc = new Document();

        DocumentBuilder builder = new DocumentBuilder(doc);

        builder.getPageSetup().setPaperSize(PaperSize.A4);//A4纸
        builder.getPageSetup().setOrientation(Orientation.PORTRAIT);//方向
        builder.getPageSetup().setVerticalAlignment(PageVerticalAlignment.TOP); //垂直对准
        builder.getPageSetup().setLeftMargin(42);//页面左边距
        builder.getPageSetup().setRightMargin(42);//页面右边距

        //获取ParagraphFormat对象，关于行的样式基本都在这里
        ParagraphFormat ph = builder.getParagraphFormat();
        //文字对齐方式
        ph.setAlignment(ParagraphAlignment.CENTER);
        // 单倍行距 = 12 ， 1.5 倍 = 18
        ph.setLineSpacing(12);
        Font font = builder.getFont();
        //大小22
        font.setSize(22);
        //粗体
        font.setBold(true);
        //颜色
        font.setColor(Color.BLACK);
        //字体
        font.setNameFarEast("宋体");
        //添加文字
        String title = DateUtil.format(annualDrillPlan.getYyyy(), "yyyy") + "年现场处置方案演练计划";
        builder.writeln(title);


        font.setSize(10);
        font.setBold(false);


        //开始添加表格
        Table table = builder.startTable();
        //开始添加第一行，并设置表格行高
        RowFormat rowf = builder.getRowFormat();
        rowf.setHeight(40);
        // ....这里rowf可以有很多的设置
        //插入一个单元格
        builder.insertCell();
        //设置单元格是否水平合并
        builder.getCellFormat().setHorizontalMerge(CellMerge.NONE);
//        //设置单元格是否垂直合并，None为不合并
//        builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
        //设置单元格宽
        builder.getCellFormat().setWidth(40);
        //单元格垂直对齐方向
        builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
        //单元格水平对齐方向
        builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
        builder.getCellFormat().setVerticalMerge(CellMerge.FIRST);

        //单元格内添加文字
        builder.write("部门");
        builder.insertCell();
        builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
        builder.getCellFormat().setHorizontalMerge(CellMerge.FIRST);
        builder.write("月份");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.NONE);
        builder.getCellFormat().setVerticalMerge(CellMerge.FIRST);
        builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
        builder.write("负责人");
        builder.insertCell();
        builder.getCellFormat().setVerticalMerge(CellMerge.FIRST);
        builder.getCellFormat().setWidth(-1);//当不需要规定这个单元格的宽度的时候，设置成-1，会是自动宽度
        builder.write("演练内容及代码");
        //结束第一行
        builder.endRow();
        //第二行开始
        builder.insertCell();
        builder.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
        builder.write("1");
        builder.insertCell();
        builder.write("2");
        builder.insertCell();
        builder.write("3");
        builder.insertCell();
        builder.write("4");
        builder.insertCell();
        builder.write("5");
        builder.insertCell();
        builder.write("6");
        builder.insertCell();
        builder.write("7");
        builder.insertCell();
        builder.write("8");
        builder.insertCell();
        builder.write("9");
        builder.insertCell();
        builder.write("10");
        builder.insertCell();
        builder.write("11");
        builder.insertCell();
        builder.write("12");

        builder.insertCell();
        builder.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.endRow();

        for (int i = 0; i < annualDrillPlanMonthList.size(); i++) {
            AspSafetyAnnualDrillPlanMonth item = annualDrillPlanMonthList.get(i);
            builder.insertCell();
            builder.getCellFormat().setHorizontalMerge(CellMerge.NONE);
            builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
            builder.write(item.getDeptname());
            builder.insertCell();
            builder.write(item.getJan());
            builder.insertCell();
            builder.write(item.getFeb());
            builder.insertCell();
            builder.write(item.getMar());
            builder.insertCell();
            builder.write(item.getApr());
            builder.insertCell();
            builder.write(item.getMay());
            builder.insertCell();
            builder.write(item.getJun());
            builder.insertCell();
            builder.write(item.getJul());
            builder.insertCell();
            builder.write(item.getAug());
            builder.insertCell();
            builder.write(item.getSept());
            builder.insertCell();
            builder.write(item.getOct());
            builder.insertCell();
            builder.write(item.getNov());
            builder.insertCell();
            builder.write(item.getDdec());
            builder.insertCell();
            builder.write(item.getDirector());
            if (i == 0) {
                //插入合并大型固定数据
                builder.insertCell();
                builder.getCellFormat().setVerticalMerge(CellMerge.FIRST);
                for (AspSafetyOnsiteDisposalPlan item2 : onsiteDisposalPlanList) {
                    String word = item2.getNo() + "、" + item2.getTreatment();
                    builder.writeln(word);
                }
            } else {
                builder.insertCell();
                builder.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS);
                builder.write("");
            }
            builder.endRow();
        }
        //结尾
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.NONE);
        builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
        builder.write("共计");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.FIRST);
        builder.write("各类现场处置方案演练共计" + annualDrillPlan.getDrillplancount() + "次");
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.insertCell();
        builder.write("");
        builder.endRow();

        //结束表格
        builder.endTable();
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(title + ".docx", "UTF-8"));
        doc.save(response.getOutputStream(), com.aspose.words.SaveFormat.DOCX);

    }

    @Override
    public void exportDrillProgramme(String mainId, HttpServletResponse response) throws Exception {
        boolean wordLicense = AsposeWordsUtils.getWordLicense();

        Map<String, Object> map = new HashMap<>();
        //查询小组表信息
        List<AspSafetyTeamVo> list = this.baseMapper.selectTeam();
        //查询小组对应成员信息
        for (AspSafetyTeamVo item : list) {
            String id = item.getID();
            String teamName = item.getTeamName();
            String content = item.getContent();
            List<AspSafetyTeamMemberVo> memberList = this.baseMapper.selectTeamMemberByTeamId(id);
            item.setMemberList(memberList);
            if (teamName.equals("演练指挥小组")) {
                for (AspSafetyTeamMemberVo vo : memberList) {
                    String roleName = vo.getRoleName();
                    String name = vo.getName();
                    if (roleName.equals("总指挥")) {
                        map.put("item1", name);
                    }
                    if (roleName.equals("副总指挥")) {
                        map.put("item2", name);
                    }
                    if (roleName.equals("成员")) {
                        map.put("item3", name);
                    }
                }
            }
            if (teamName.equals("指挥领导小组")) {
                map.put("item4", content);
            }
            if (teamName.equals("总指挥")) {
                map.put("item5", content);
            }
            if (teamName.equals("副总指挥")) {
                map.put("item6", content);
            }
            List<String> teamNameList = new LinkedList<>();
            teamNameList.add("抢险技术组");
            teamNameList.add("抢险抢修组");
            teamNameList.add("医疗救护组");
            teamNameList.add("监测洗消组");
            teamNameList.add("消防救援组");
            teamNameList.add("后勤物资保障组");
            teamNameList.add("警戒疏散联络组");
            teamNameList.add("财力保障组");
            int index = 7;
            if (teamNameList.contains(teamName)) {
                int i = teamNameList.indexOf(teamName);
                int startIndex = index + i * 4;
                for (AspSafetyTeamMemberVo vo : memberList) {
                    String roleName = vo.getRoleName();
                    String name = vo.getName();
                    if (roleName.equals("组长")) {
                        map.put("item" + startIndex, name);
                    }
                    if (roleName.equals("副组长")) {
                        map.put("item" + (startIndex + 1), name);
                    }
                    if (roleName.equals("成员")) {
                        map.put("item" + (startIndex + 2), name);
                    }
                }
                map.put("item" + (startIndex + 3), content);
            }

        }
        //主表数据
        AspSafetyDrillProgrammeDo aspSafetyDrillProgrammeDo = this.baseMapper.selectById(mainId);
        map.put("PLANNAME", aspSafetyDrillProgrammeDo.getPlanname());
        map.put("DRILLTIME", DateUtil.format(aspSafetyDrillProgrammeDo.getDrilltime(), "yyyy年MM月dd日 HH时mm分"));
        map.put("DRILLLOCATION", aspSafetyDrillProgrammeDo.getDrilllocation());
        map.put("PARTICIPANTNAME", aspSafetyDrillProgrammeDo.getParticipantname());
        map.put("OBSERVERNAMES", aspSafetyDrillProgrammeDo.getObservernames());
        map.put("CAMERACREWNAME", aspSafetyDrillProgrammeDo.getCameracrewname());

        map.put("PREPARATION", aspSafetyDrillProgrammeDo.getPreparation());
        map.put("MOBILIZATIONTRAINING", aspSafetyDrillProgrammeDo.getMobilizationtraining());
        map.put("DRILLPROCESS", aspSafetyDrillProgrammeDo.getDrillprocess());
        map.put("EVALUATIONSUMMARY", aspSafetyDrillProgrammeDo.getEvaluationsummary());

        //增加所需器材组装字段（equipments）
        String equipments = this.baseMapper.selectEquimentByMainId(mainId);
        map.put("equipments", equipments);

        ClassPathResource classPathResource = new ClassPathResource("template/ExercisePlan.docx");


        Document doc = new Document(classPathResource.getInputStream());
        doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_FIELDS);
        try {
            doc.getMailMerge().execute(map.keySet().toArray(new String[0]), map.values().toArray());
            doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_TABLE_ROWS);
            doc.getMailMerge().deleteFields();
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(aspSafetyDrillProgrammeDo.getPlanname() + "演练方案.docx", "UTF-8"));
            doc.save(response.getOutputStream(), com.aspose.words.SaveFormat.DOCX);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("演练方案导出异常");
        }

    }

    /**
     * 消息提醒
     *
     * @param list
     */
    private void notifyMsg(List<AspSafetyDrillProgrammeDo> list) {
        if (ObjectUtil.isEmpty(list)) {
            return;
        }

        log.info("notify size: {}", list.size());

        List<AspSafetyDrillProgrammeMsgNotifyRecordDo> recordDos = new ArrayList<>();

        list.forEach(item -> {
            AspSafetyEmergencyPlan plan = aspSafetyEmergencyPlanService.getById(item.getPlanid());
            AspSafetyDrillProgrammeMsgNotifyRecordDo record = new AspSafetyDrillProgrammeMsgNotifyRecordDo();
            record.setProgrammeid(item.getId());
            record.setMsgType("sysmsg");
            record.setDeleted("0");
            record.setCreatedate(new Date());
            record.setModifydate(new Date());
            record.setId(SecurityUtil.getUUID());
            recordDos.add(record);
            notifyMsg(item, plan);
        });

        drillProgrammeMsgNotifyRecordService.saveBatch(recordDos);
    }

    /**
     * 消息提醒
     *
     * @param programmeDo
     * @param plan
     */
    private void notifyMsg(AspSafetyDrillProgrammeDo programmeDo, AspSafetyEmergencyPlan plan) {

        List<SysDictDo> planPlanType = dictService.getByRedis("emergency_plan_plan_type");

        if (ObjectUtil.isEmpty(plan.getPlantype())) {
            return;
        }

        List<String> planTypeList = new ArrayList<>();
        for (String planType : plan.getPlantype().split(",")) {
            Optional<SysDictDo> sysDictDo = planPlanType.stream().filter(item -> item.getValue().equals(planType)).findFirst();
            planTypeList.add(sysDictDo.get().getName());
        }

        StringBuilder sb = new StringBuilder();
        sb.append("【");
        sb.append(programmeDo.getPlanname());
        sb.append("】【");
        sb.append(StringUtils.join(planTypeList, ","));
        sb.append("】【");
        sb.append(DateUtil.format(programmeDo.getDrilltime(), "yyyy-MM-dd HH: mm:ss"));
        sb.append("】【");
        sb.append(programmeDo.getDrilllocation());
        sb.append("】即将开始进行演练，请悉知；");

        List<String> userIdList = new ArrayList<>();
        if (!ObjectUtil.isEmpty(programmeDo.getObserverids())) {
            userIdList.addAll(Arrays.stream(programmeDo.getObserverids().split(",")).collect(Collectors.toList()));
        }

        if (!ObjectUtil.isEmpty(programmeDo.getParticipantid())) {
            userIdList.addAll(Arrays.stream(programmeDo.getParticipantid().split(",")).collect(Collectors.toList()));
        }

        //发送消息
        JSCommonUtils.sendNotify("安全应急",
                sb.toString(),
                null,
                userIdList,
                programmeDo.getId(),
                "safetyemergency");
    }
}
