package com.huajun.pageoffice.controller;

import com.alibaba.fastjson.JSON;
import com.huajun.common.core.domain.R;
import com.huajun.common.core.utils.DateUtils;
import com.huajun.common.core.utils.IdUtils;
import com.huajun.common.core.utils.SecurityUtils;
import com.huajun.common.core.utils.StringUtils;
import com.huajun.common.core.web.domain.AjaxResult;
import com.huajun.common.core.web.page.TableDataInfo;
import com.huajun.duty.api.RemoteDutyReportService;
import com.huajun.duty.api.domain.DutyReport;
import com.huajun.event.api.RemoteEventPlanSelectedService;
import com.huajun.event.api.RemoteEventService;
import com.huajun.event.api.RemoteEvnMaterialScheduleService;
import com.huajun.event.api.RemoteEvnTeamScheduleService;
import com.huajun.event.api.domain.EvnMaterialSchedule;
import com.huajun.pageoffice.config.PageofficeConfig;
import com.huajun.system.api.*;
import com.huajun.system.api.domain.SysFile;
import com.huajun.system.api.domain.SysFileInfo;
import com.huajun.system.api.domain.SysTemplate;
import com.zhuozhengsoft.pageoffice.*;
import com.zhuozhengsoft.pageoffice.wordwriter.DataRegion;
import com.zhuozhengsoft.pageoffice.wordwriter.Table;
import com.zhuozhengsoft.pageoffice.wordwriter.WdAutoFitBehavior;
import com.zhuozhengsoft.pageoffice.wordwriter.WordDocument;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.huajun.event.api.domain.EvnPlanSelected;
import com.huajun.system.api.domain.SysDictData;
import com.huajun.event.api.domain.EvnEvent;
import com.huajun.common.core.domain.R;

/**
 * @author yangwt
 */
@RestController
public class PageofficeController {
    @Autowired
    private PageofficeConfig pageofficeConfig;

    @Autowired
    private RemoteFileService remoteFileService;
    @Autowired
    private RemoteFileInfoService fileInfoService;
    @Autowired
    private RemoteTemplateService templateService;
    @Autowired
    private RemoteDutyReportService dutyReportService;
    @Autowired
    private RemoteEventService remoteEventService;
    @Autowired
    RemoteEventPlanSelectedService remoteEventPlanSelectedService;
    @Autowired
    RemoteCategoryService remoteCategoryService;
    @Autowired
    RemoteDictDataService remoteDictDataService;
    @Autowired
    RemoteEvnMaterialScheduleService remoteEvnMaterialScheduleService;

    @Autowired
    RemoteEvnTeamScheduleService remoteEvnTeamScheduleService;

    /**
     * 文件上传
     */
    @RequestMapping("/save")
    public void upload(HttpServletRequest request, HttpServletResponse response) {
        FileSaver fs = new FileSaver(request, response);
        try {
            MultipartFile file = new MockMultipartFile(fs.getFileName(), fs.getFileName(), "application/octet-stream", fs.getFileStream());
            remoteFileService.upload(file);
            fs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件下载
     */
    @RequestMapping("/download")
    public Object download(String file) {
        ResponseEntity<byte[]> entity = remoteFileService.download(file);
        return entity;
    }


    @RequestMapping(value = "/word", method = RequestMethod.GET)
    public ModelAndView showWord(HttpServletRequest request, Map<String, Object> map, String file) {
        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        // 加按钮
        poCtrl.addCustomToolButton("保存", "Save", 1);//添加自定义保存按钮
        poCtrl.addCustomToolButton("盖章", "AddSeal", 2);//添加自定义盖章按钮
        poCtrl.addCustomToolButton("关闭并刷新父页面", "ClosePage", 21);//添加关闭按钮

        poCtrl.setServerPage("/poserver.zz");//设置服务页面
        poCtrl.setSaveFilePage("/save");//设置处理文件保存的请求方法

        // 演示替换数据标签
        WordDocument doc = new WordDocument();
        doc.openDataRegion("PO_TITLE").setEditing(false);// 不可编辑
        doc.openDataRegion("PO_TITLE").setValue("这是一个标题");// 设置值,可从前端传,可从接口中获取
        poCtrl.setWriter(doc);

        //打开word
        poCtrl.webOpen("/download?file=" + file, OpenModeType.docAdmin, SecurityUtils.getNickname());
        map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));

        ModelAndView mv = new ModelAndView("Word");
        return mv;
    }


    /**
     * 模板编辑页面跳转
     * <p>
     * 为什么要在jsp页面传过来userName,而不是直接session获取呢?
     * 因为本页面跳转,不需要登录,原因是为了适配谷歌等浏览器,因为谷歌浏览器打开本页面是用ie打开的,这时候该方法这时候就获取不到登录用户信息了
     *
     * @return
     */
    @RequestMapping(value = "/goTemplateModel", method = RequestMethod.GET)
    public ModelAndView goTemplateModel(HttpServletRequest request, Map<String, Object> map) {
        String type = request.getParameter("type");
        String mesId = request.getParameter("mesId");
        String filePath = fileInfoService.filelist(mesId);
        String eventId = request.getParameter("eventId");

        //模板id ,调用模板库时,不能为空值;
        String modelId = request.getParameter("modelId");

        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        // 隐藏菜单栏
        poCtrl.setMenubar(false);
        // 添加按钮
        poCtrl.setTimeSlice(30);
        poCtrl.addCustomToolButton("保存", "Save()", 1);
        poCtrl.addCustomToolButton("打印", "PrintFile()", 6);
        poCtrl.addCustomToolButton("全屏/还原", "IsFullScreen()", 4);
        poCtrl.addCustomToolButton("关闭", "CloseFile()", 21);

        poCtrl.setServerPage("poserver.zz");
        poCtrl.setSaveFilePage("/saveTemplateModel?type=" + type + "&mesId=" + mesId);
        poCtrl.setTheme(ThemeType.Office2007);
        poCtrl.setBorderStyle(BorderStyleType.BorderThin);
        poCtrl.setCaption("模板编辑");
        if (TextUtils.isEmpty(filePath)) {
            // 新建
            if (!TextUtils.isEmpty(modelId)) {
                // 没有文件,打开模板
                SysTemplate template = templateService.getDetail(type);
                if (template.getId() != null) {
                    // 替换数据标签
                    WordDocument doc = new WordDocument();
                    SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
                    switch (type) {
                        case "1"://值班报告
                            DutyReport report = dutyReportService.getDetail(mesId);
                            doc.openDataRegion("PO_ISSUENUM").setValue(report.getIssueNum() + "");
                            doc.openDataRegion("PO_ISSUENUM").setEditing(false);
                            doc.openDataRegion("PO_CALLEDTIME").setValue(format.format(report.getCreateTime()));
                            doc.openDataRegion("PO_CALLEDTIME").setEditing(false);
                            doc.openDataRegion("PO_CONTENT").setValue(report.getContent() + "");
                            doc.openDataRegion("PO_CONTENT").setEditing(true);
                            doc.openDataRegion("PO_DUTYER").setValue(report.getCreateName() + "");
                            doc.openDataRegion("PO_DUTYER").setEditing(false);
                            doc.openDataRegion("PO_SUBJECT").setValue(report.getTitle() + "");
                            doc.openDataRegion("PO_SUBJECT").setEditing(false);
                            poCtrl.setTheme(ThemeType.Office2007);
                            poCtrl.setBorderStyle(BorderStyleType.BorderThin);
                            poCtrl.setWriter(doc);
                            break;
                        case "2"://突发事件
                            DutyReport event = dutyReportService.getDetail(mesId);
                            doc.openDataRegion("PO_ISSUENUM").setValue(event.getIssueNum() + "");
                            doc.openDataRegion("PO_ISSUENUM").setEditing(false);
                            doc.openDataRegion("PO_DATE").setValue(format.format(event.getCreateTime()));
                            doc.openDataRegion("PO_DATE").setEditing(false);
                            doc.openDataRegion("PO_CONTENT").setValue(event.getContent() + "");
                            doc.openDataRegion("PO_CONTENT").setEditing(true);
                            doc.openDataRegion("PO_REPORTORG").setValue(event.getReportUnitName() + "");
                            doc.openDataRegion("PO_REPORTORG").setEditing(false);
                            doc.openDataRegion("PO_REPORTER").setValue(event.getCreateName() + "");
                            doc.openDataRegion("PO_REPORTER").setEditing(false);
                            doc.openDataRegion("PO_TITLE").setValue(event.getTitle() + "");
                            doc.openDataRegion("PO_TITLE").setEditing(false);
                            doc.openDataRegion("PO_TEL").setValue("65655555");
                            doc.openDataRegion("PO_TEL").setEditing(false);
                            poCtrl.setTheme(ThemeType.Office2007);
                            poCtrl.setBorderStyle(BorderStyleType.BorderThin);
                            poCtrl.setWriter(doc);
                            break;
                        case "emergency_command_plan"://应急指挥方案
                            EvnEvent eventInfo = getEventInfo(eventId);
                            String planName = "";
                            EvnPlanSelected planSelected = getPlan(eventId);
                            if (planSelected != null) {
                                planName = Optional.ofNullable(planSelected.getPlanName()).orElse("");
                                doc.openDataRegion("PO_PLANNAME").setValue(planName + "");
                                doc.openDataRegion("PO_PLANNAME").setEditing(false);
                            }
                            String eventTypeName = "";
                            String eventType = String.valueOf(eventInfo.getEventType());//事件类型代码
                            if (eventType.equals("null") && StringUtils.isEmpty(eventType)) {
                                //doing nothing
                            } else {
                                eventTypeName = getCategory(eventType);
                            }
                            String dictName = "";
                            String eventGrade = String.valueOf(eventInfo.getEventGrade());//事件等级代码
                            if (eventGrade.equals("null") && StringUtils.isEmpty(eventGrade)) {
                                //doing nothing
                            } else {
                                dictName = getDictName("event_grade", eventGrade);
                            }
                            doc.openDataRegion("PO_NAME").setValue(eventInfo.getName() + "");
                            doc.openDataRegion("PO_NAME").setEditing(false);
                            doc.openDataRegion("PO_CONTENT").setValue(eventInfo.getContent() + "");
                            doc.openDataRegion("PO_CONTENT").setEditing(true);
                            doc.openDataRegion("PO_CONTACTS").setValue(eventInfo.getContacts() + "");
                            doc.openDataRegion("PO_CONTACTS").setEditing(false);
                            doc.openDataRegion("PO_EVENTTIME").setValue(DateUtils.dateTime(eventInfo.getEventTime()));
                            doc.openDataRegion("PO_EVENTTIME").setEditing(false);
                            doc.openDataRegion("PO_EVENTTYPE").setValue(eventTypeName + "");
                            doc.openDataRegion("PO_EVENTTYPE").setEditing(false);
                            doc.openDataRegion("PO_EVENTGRADE").setValue(dictName + "");
                            doc.openDataRegion("PO_EVENTGRADE").setEditing(false);
                            doc.openDataRegion("PO_ADDRESS").setValue(eventInfo.getAddress() + "");
                            doc.openDataRegion("PO_ADDRESS").setEditing(false);
                            doc.openDataRegion("PO_EVENTCAUSE").setValue(eventInfo.getEventCause() + "");
                            doc.openDataRegion("PO_EVENTCAUSE").setEditing(false);

                            DataRegion dataRegion = doc.openDataRegion("PO_TESTONE");

                            Table table = dataRegion.openTable(1); //index代表当前书签中table位置的索引,从1开始

                            table.openCellRC(2, 1).setValue("A公司");//openCellRC(行, 列),索引从1开始
                            table.openCellRC(2, 2).setValue("开发部");
                            table.openCellRC(2, 3).setValue("李清");
                            table.openCellRC(2, 4).setValue("于吉利");
                            //插入一行,insertRowAfter方法中的参数代表在哪个单元格下面插入一个空行
                            table.insertRowAfter(table.openCellRC(2, 4));

                            table.openCellRC(3, 1).setValue("B公司");
                            table.openCellRC(3, 2).setValue("销售部");
                            table.openCellRC(3, 3).setValue("张三丰");
                            table.openCellRC(3, 4).setValue("李清照");

//                            Table table1 = doc.openDataRegion("PO_TESTONE").createTable(3, 4, WdAutoFitBehavior.wdAutoFitWindow);
//                            //给表格table1中剩余的单元格赋值
//                            for (int i = 1; i < 4; i++) {
//                                table1.openCellRC(i, 1).setValue("AA" + String.valueOf(i));
//                                table1.openCellRC(i, 2).setValue("BB" + String.valueOf(i));
//                                table1.openCellRC(i, 3).setValue("CC" + String.valueOf(i));
//                                table1.openCellRC(i, 4).setValue("DD" + String.valueOf(i));
//                            }


                            poCtrl.setTheme(ThemeType.Office2007);
                            poCtrl.setBorderStyle(BorderStyleType.BorderThin);
                            poCtrl.setWriter(doc);
                            break;
                        case "resource_guarantee_plan"://资源保障方案
                            EvnEvent eventInfoResource = getEventInfo(eventId);
                            String planNameResource = "";
                            EvnPlanSelected planSelectedResource = getPlan(eventId);
                            if (planSelectedResource != null) {
                                planNameResource = planSelectedResource.getPlanName();//得到预案名称
                                doc.openDataRegion("PO_PLANNAME").setValue(planNameResource + "");
                                doc.openDataRegion("PO_PLANNAME").setEditing(false);
                            }
                            String eventTypeNameResource = "";
                            String eventTypeResource = String.valueOf(eventInfoResource.getEventType());//事件类型代码
                            if (eventTypeResource.equals("null") && StringUtils.isEmpty(eventTypeResource)) {
                                //doing nothing
                            } else {
                                eventTypeNameResource = getCategory(eventTypeResource);
                            }
                            String dictNameResource = "";
                            String eventGradeResource = String.valueOf(eventInfoResource.getEventGrade());//事件等级代码
                            if (eventGradeResource.equals("null") && StringUtils.isEmpty(eventGradeResource)) {
                                //doing nothing
                            } else {
                                dictNameResource = getDictName("event_grade", eventGradeResource);
                            }
                            doc.openDataRegion("PO_NAME").setValue(eventInfoResource.getName() + "");
                            doc.openDataRegion("PO_NAME").setEditing(false);
                            doc.openDataRegion("PO_CONTENT").setValue(eventInfoResource.getContent() + "");
                            doc.openDataRegion("PO_CONTENT").setEditing(true);
                            doc.openDataRegion("PO_CONTACTS").setValue(eventInfoResource.getContacts() + "");
                            doc.openDataRegion("PO_CONTACTS").setEditing(false);
                            doc.openDataRegion("PO_EVENTTIME").setValue(DateUtils.dateTime(eventInfoResource.getEventTime()));
                            doc.openDataRegion("PO_EVENTTIME").setEditing(false);
                            doc.openDataRegion("PO_EVENTTYPE").setValue(eventTypeNameResource + "");
                            doc.openDataRegion("PO_EVENTTYPE").setEditing(false);
                            doc.openDataRegion("PO_EVENTGRADE").setValue(dictNameResource + "");
                            doc.openDataRegion("PO_EVENTGRADE").setEditing(false);
                            doc.openDataRegion("PO_ADDRESS").setValue(eventInfoResource.getAddress() + "");
                            doc.openDataRegion("PO_ADDRESS").setEditing(false);
                            doc.openDataRegion("PO_EVENTCAUSE").setValue(eventInfoResource.getEventCause() + "");
                            doc.openDataRegion("PO_EVENTCAUSE").setEditing(false);
                            //物资调度信息
                            TableDataInfo evnMaterial = remoteEvnMaterialScheduleService.list(eventId, "1", "10000");
                            if (evnMaterial != null && evnMaterial.getRows() != null && evnMaterial.getRows().size() > 0) {
                                List<EvnMaterialSchedule> listEvnMaterial = (List<EvnMaterialSchedule>) evnMaterial.getRows();
                                Table tableMaterial = doc.openDataRegion("PO_MATERIAL").createTable(listEvnMaterial.size(), 5, WdAutoFitBehavior.wdAutoFitWindow);
                                for (int i = 0; i < listEvnMaterial.size(); i++) {
                                    EvnMaterialSchedule evnMaterialSchedule = JSON.parseObject(JSON.toJSONString(listEvnMaterial.get(i)), EvnMaterialSchedule.class);
                                    tableMaterial.openCellRC(i, 1).setValue("AA" + String.valueOf(i));
                                    tableMaterial.openCellRC(i, 2).setValue("BB" + String.valueOf(i));
                                    tableMaterial.openCellRC(i, 3).setValue("CC" + String.valueOf(i));
                                    tableMaterial.openCellRC(i, 4).setValue("DD" + String.valueOf(i));
                                    tableMaterial.openCellRC(i, 5).setValue("ee" + String.valueOf(i));
                                }
                            } else {
                                //doing nothing
                            }
                            //队伍调度信息
                            TableDataInfo evnTeam = remoteEvnTeamScheduleService.list(eventId, "1", "10000");
                            if (evnTeam != null && evnTeam.getRows() != null && evnTeam.getRows().size() > 0) {

                            } else {

                                //doing nothing
                            }


                            poCtrl.setTheme(ThemeType.Office2007);
                            poCtrl.setBorderStyle(BorderStyleType.BorderThin);
                            break;
                        case "rescue_disposal_plan"://救援处置方案
                            EvnEvent eventInfoRescue = getEventInfo(eventId);
                            String planNameRescue = "";
                            EvnPlanSelected planSelectedRescue = getPlan(eventId);
                            if (planSelectedRescue != null) {
                                planNameRescue = planSelectedRescue.getPlanName();//得到预案名称
                                doc.openDataRegion("PO_PLANNAME").setValue(planNameRescue + "");
                                doc.openDataRegion("PO_PLANNAME").setEditing(false);
                            }
                            String eventTypeNameRescue = "";
                            String eventTypeRescue = String.valueOf(eventInfoRescue.getEventType());//事件类型代码
                            if (eventTypeRescue.equals("null") && StringUtils.isEmpty(eventTypeRescue)) {
                                //doing nothing
                            } else {
                                eventTypeNameRescue = getCategory(eventTypeRescue);
                            }
                            String dictNameRescue = "";
                            String eventGradeRescue = String.valueOf(eventInfoRescue.getEventGrade());//事件等级代码
                            if (eventGradeRescue.equals("null") && StringUtils.isEmpty(eventGradeRescue)) {
                                //doing nothing
                            } else {
                                dictNameRescue = getDictName("event_grade", eventGradeRescue);
                            }
                            doc.openDataRegion("PO_NAME").setValue(eventInfoRescue.getName() + "");
                            doc.openDataRegion("PO_NAME").setEditing(false);
                            doc.openDataRegion("PO_CONTENT").setValue(eventInfoRescue.getContent() + "");
                            doc.openDataRegion("PO_CONTENT").setEditing(true);
                            doc.openDataRegion("PO_CONTACTS").setValue(eventInfoRescue.getContacts() + "");
                            doc.openDataRegion("PO_CONTACTS").setEditing(false);
                            doc.openDataRegion("PO_EVENTTIME").setValue(DateUtils.dateTime(eventInfoRescue.getEventTime()));
                            doc.openDataRegion("PO_EVENTTIME").setEditing(false);
                            doc.openDataRegion("PO_EVENTTYPE").setValue(eventTypeNameRescue + "");
                            doc.openDataRegion("PO_EVENTTYPE").setEditing(false);
                            doc.openDataRegion("PO_EVENTGRADE").setValue(dictNameRescue + "");
                            doc.openDataRegion("PO_EVENTGRADE").setEditing(false);
                            doc.openDataRegion("PO_ADDRESS").setValue(eventInfoRescue.getAddress() + "");
                            doc.openDataRegion("PO_ADDRESS").setEditing(false);
                            doc.openDataRegion("PO_EVENTCAUSE").setValue(eventInfoRescue.getEventCause() + "");
                            doc.openDataRegion("PO_EVENTCAUSE").setEditing(false);
                            poCtrl.setTheme(ThemeType.Office2007);
                            poCtrl.setBorderStyle(BorderStyleType.BorderThin);
                            poCtrl.setWriter(doc);
                            break;
                        case "emergency_work_plan"://应急工作方案
                            EvnEvent eventInfoEmergency = getEventInfo(eventId);
                            String planNameEmergency = "";
                            EvnPlanSelected planSelectedEmergency = getPlan(eventId);
                            if (planSelectedEmergency != null) {
                                //得到预案名称
                                planNameEmergency = planSelectedEmergency.getPlanName();
                                doc.openDataRegion("PO_PLANNAME").setValue(planNameEmergency + "");
                                doc.openDataRegion("PO_PLANNAME").setEditing(false);
                            }
                            String eventTypeNameEmergency = "";
                            //事件类型代码
                            String eventTypeEmergency = String.valueOf(eventInfoEmergency.getEventType());
                            if (eventTypeEmergency.equals("null") && StringUtils.isEmpty(eventTypeEmergency)) {
                                //doing nothing
                            } else {
                                eventTypeNameEmergency = getCategory(eventTypeEmergency);
                            }
                            String dictNameEmergency = "";
                            String eventGradeEmergency = String.valueOf(eventInfoEmergency.getEventGrade());//事件等级代码
                            if (eventGradeEmergency.equals("null") && StringUtils.isEmpty(eventGradeEmergency)) {
                                //doing nothing
                            } else {
                                dictNameEmergency = getDictName("event_grade", eventGradeEmergency);
                            }
                            doc.openDataRegion("PO_PLANNAME").setValue(planNameEmergency + "");
                            doc.openDataRegion("PO_PLANNAME").setEditing(false);

                            doc.openDataRegion("PO_NAME").setValue(eventInfoEmergency.getName() + "");
                            doc.openDataRegion("PO_NAME").setEditing(false);
                            doc.openDataRegion("PO_CONTENT").setValue(eventInfoEmergency.getContent() + "");
                            doc.openDataRegion("PO_CONTENT").setEditing(true);
                            doc.openDataRegion("PO_CONTACTS").setValue(eventInfoEmergency.getContacts() + "");
                            doc.openDataRegion("PO_CONTACTS").setEditing(false);
                            doc.openDataRegion("PO_EVENTTIME").setValue(DateUtils.dateTime(eventInfoEmergency.getEventTime()));
                            doc.openDataRegion("PO_EVENTTIME").setEditing(false);
                            doc.openDataRegion("PO_EVENTTYPE").setValue(eventTypeNameEmergency + "");
                            doc.openDataRegion("PO_EVENTTYPE").setEditing(false);
                            doc.openDataRegion("PO_EVENTGRADE").setValue(dictNameEmergency + "");
                            doc.openDataRegion("PO_EVENTGRADE").setEditing(false);
                            doc.openDataRegion("PO_ADDRESS").setValue(eventInfoEmergency.getAddress() + "");
                            doc.openDataRegion("PO_ADDRESS").setEditing(false);
                            doc.openDataRegion("PO_EVENTCAUSE").setValue(eventInfoEmergency.getEventCause() + "");
                            doc.openDataRegion("PO_EVENTCAUSE").setEditing(false);
                            poCtrl.setTheme(ThemeType.Office2007);
                            poCtrl.setBorderStyle(BorderStyleType.BorderThin);
                            poCtrl.setWriter(doc);
                            break;
                        case "env_disaster_evaluation"://灾害快速评估专报
                            R<AjaxResult> ajaxResult = remoteEventService.getEventInfo(eventId);//夸服务调用时报没有权限,暂时把事件的权限去掉
                            if (StringUtils.isNull(ajaxResult) || StringUtils.isNull(ajaxResult.getData())) {

                            } else {

                                String name = String.valueOf(ajaxResult.getData().get("name"));
                                name = StringUtils.isNotNull(name) ? name : "";
                                String content = String.valueOf(ajaxResult.getData().get("content"));
                                content = StringUtils.isNotNull(content) ? content : "";
                                String contacts = String.valueOf(ajaxResult.getData().get("contacts"));
                                contacts = StringUtils.isNotNull(ajaxResult.getData().get("contacts")) ? contacts : "";
                                String eventTypeDis = String.valueOf(ajaxResult.getData().get("eventType"));
                                eventTypeDis = StringUtils.isNotNull(eventTypeDis) ? eventTypeDis : "";
                                String eventTime = String.valueOf(ajaxResult.getData().get("eventTime"));
                                eventTime = StringUtils.isNotNull(eventTime) ? eventTime : "";
                                String address = String.valueOf(ajaxResult.getData().get("address"));
                                address = StringUtils.isNotNull(address) ? address : "";
                                String eventCause = String.valueOf(ajaxResult.getData().get("eventCause"));
                                eventCause = StringUtils.isNotNull(eventCause) ? eventCause : "";
                                doc.openDataRegion("PO_NAME").setValue(name + "");
                                doc.openDataRegion("PO_NAME").setEditing(false);
                                doc.openDataRegion("PO_CONTENT").setValue(content + "");
                                doc.openDataRegion("PO_CONTENT").setEditing(true);
                                doc.openDataRegion("PO_CONTACTS").setValue(contacts + "");
                                doc.openDataRegion("PO_CONTACTS").setEditing(false);
                                doc.openDataRegion("PO_EVENTTIME").setValue(eventTime);
                                doc.openDataRegion("PO_EVENTTIME").setEditing(false);
                                doc.openDataRegion("PO_EVENTGRADE").setValue(address + "");
                                doc.openDataRegion("PO_EVENTGRADE").setEditing(false);
                                doc.openDataRegion("PO_ADDRESS").setValue(address + "");
                                doc.openDataRegion("PO_ADDRESS").setEditing(false);
                                doc.openDataRegion("PO_EVENTCAUSE").setValue(eventCause + "");
                                doc.openDataRegion("PO_EVENTCAUSE").setEditing(false);
                            }
                            poCtrl.setTheme(ThemeType.Office2007);
                            poCtrl.setBorderStyle(BorderStyleType.BorderThin);
                            poCtrl.setWriter(doc);
                            break;
                        case "env_sop"://标准作业流程SOP
                            poCtrl.setTheme(ThemeType.Office2007);
                            poCtrl.setBorderStyle(BorderStyleType.BorderThin);
                            poCtrl.setWriter(doc);
                            break;

                    }
                    poCtrl.webOpen("/downloadFile?mesId=" + template.getId(), OpenModeType.docAdmin, SecurityUtils.getNickname());
                } else {
                    //暂无模板
                }
            } else {
                //新建模板
                poCtrl.webCreateNew(SecurityUtils.getUsername(), DocumentVersion.Word2003);
            }
        } else {// 打开
            //打开word
            poCtrl.webOpen("/downloadFile?mesId=" + mesId, OpenModeType.docAdmin, SecurityUtils.getNickname());
        }
        map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));
        return new ModelAndView("Word");
    }

    /**
     * 得到事件信息
     * 于吉利  2021-10-15
     *
     * @param eventId
     * @return
     */
    public EvnEvent getEventInfo(String eventId) {
        EvnEvent evnEvent = null;
        R<AjaxResult> ajaxResultEventInfo = remoteEventService.getEventInfo(eventId);//夸服务调用时报没有权限,暂时把事件的权限去掉
        if (StringUtils.isNull(ajaxResultEventInfo) || StringUtils.isNull(ajaxResultEventInfo.getData())) {
        } else {
            //evnEvent=JSON.parseObject(JSON.toJSONString(ajaxResultEventInfo.getData()), EvnEvent.class);//去掉此种方法返回值,先处理null值
            evnEvent = new EvnEvent();
            String id = String.valueOf(ajaxResultEventInfo.getData().get("id"));
            evnEvent.setId(id);

            String name = String.valueOf(ajaxResultEventInfo.getData().get("name"));
            name = name.equals("null") ? "" : name;
            evnEvent.setName(name);

            String content = String.valueOf(ajaxResultEventInfo.getData().get("content"));
            content = content.equals("null") ? "" : content;
            evnEvent.setContent(content);

            String reportName = String.valueOf(ajaxResultEventInfo.getData().get("reportName"));
            reportName = reportName.equals("null") ? "" : reportName;
            evnEvent.setReportName(reportName);

            String reportUnit = String.valueOf(ajaxResultEventInfo.getData().get("reportUnit"));
            reportUnit = reportUnit.equals("null") ? "" : reportUnit;
            evnEvent.setReportUnit(reportUnit);

            String reportUnitTel = String.valueOf(ajaxResultEventInfo.getData().get("reportUnitTel"));
            reportUnitTel = reportUnitTel.equals("null") ? "" : reportUnitTel;
            evnEvent.setReportUnitTel(reportUnitTel);

            String reportTime = String.valueOf(ajaxResultEventInfo.getData().get("reportTime"));
            //reportTime = reportTime.equals("null") ? "" : reportTime;
            if (reportTime.equals("null")) {
            } else {
                evnEvent.setReportTime(DateUtils.parseDate(reportTime));
            }


            String contacts = String.valueOf(ajaxResultEventInfo.getData().get("contacts"));
            contacts = contacts.equals("null") ? "" : contacts;
            evnEvent.setContacts(contacts);

            String dutyReportId = String.valueOf(ajaxResultEventInfo.getData().get("dutyReportId"));
            dutyReportId = dutyReportId.equals("null") ? "" : dutyReportId;
            evnEvent.setDutyReportId(dutyReportId);


            String eventType = String.valueOf(ajaxResultEventInfo.getData().get("eventType"));
            eventType = eventType.equals("null") ? "" : eventType;
            evnEvent.setEventType(eventType);

            String eventGrade = String.valueOf(ajaxResultEventInfo.getData().get("eventGrade"));
            eventGrade = eventGrade.equals("null") ? "" : eventGrade;
            evnEvent.setEventGrade(eventGrade);

            String eventTime = String.valueOf(ajaxResultEventInfo.getData().get("eventTime"));
            //eventTime = eventTime.equals("null") ? "" : eventTime;
            if (eventTime.equals("null")) {
            } else {
                evnEvent.setEventTime(DateUtils.parseDate(eventTime));
            }


            String longitude = String.valueOf(ajaxResultEventInfo.getData().get("longitude"));
            longitude = longitude.equals("null") ? "" : longitude;
            evnEvent.setLongitude(longitude);

            String latitude = String.valueOf(ajaxResultEventInfo.getData().get("latitude"));
            latitude = latitude.equals("null") ? "" : latitude;
            evnEvent.setLatitude(latitude);


            String address = String.valueOf(ajaxResultEventInfo.getData().get("address"));
            address = address.equals("null") ? "" : address;
            evnEvent.setAddress(address);

            String districts = String.valueOf(ajaxResultEventInfo.getData().get("districts"));
            districts = districts.equals("null") ? "" : districts;
            evnEvent.setDistricts(districts);

            String eventCause = String.valueOf(ajaxResultEventInfo.getData().get("eventCause"));
            eventCause = eventCause.equals("null") ? "" : eventCause;
            evnEvent.setEventCause(eventCause);

            String eventDesc = String.valueOf(ajaxResultEventInfo.getData().get("eventDesc"));
            eventDesc = districts.equals("null") ? "" : eventDesc;
            evnEvent.setEventDesc(eventDesc);

            String signLeader = String.valueOf(ajaxResultEventInfo.getData().get("signLeader"));
            signLeader = signLeader.equals("null") ? "" : signLeader;
            evnEvent.setSignLeader(signLeader);

            String disasterDesc = String.valueOf(ajaxResultEventInfo.getData().get("disasterDesc"));
            disasterDesc = disasterDesc.equals("null") ? "" : disasterDesc;
            evnEvent.setDisasterDesc(disasterDesc);

            String takeSteps = String.valueOf(ajaxResultEventInfo.getData().get("takeSteps"));
            takeSteps = takeSteps.equals("null") ? "" : takeSteps;
            evnEvent.setTakeSteps(takeSteps);


            String rescueSituation = String.valueOf(ajaxResultEventInfo.getData().get("rescueSituation"));
            rescueSituation = rescueSituation.equals("null") ? "" : rescueSituation;
            evnEvent.setRescueSituation(rescueSituation);

            String supportRequest = String.valueOf(ajaxResultEventInfo.getData().get("supportRequest"));
            supportRequest = supportRequest.equals("null") ? "" : supportRequest;
            evnEvent.setSupportRequest(supportRequest);

            String securityLevel = String.valueOf(ajaxResultEventInfo.getData().get("securityLevel"));
            securityLevel = securityLevel.equals("null") ? "" : securityLevel;
            evnEvent.setSecurityLevel(securityLevel);

            String eventSource = String.valueOf(ajaxResultEventInfo.getData().get("eventSource"));
            eventSource = eventSource.equals("null") ? "" : eventSource;
            evnEvent.setEventSource(eventSource);

            String eventFocuson = String.valueOf(ajaxResultEventInfo.getData().get("eventFocuson"));
            eventFocuson = eventFocuson.equals("null") ? "" : eventFocuson;
            evnEvent.setEventFocuson(eventFocuson);

        }
        return evnEvent;
    }


    /**
     * 查询匹配后的预案信息
     * 于吉利  2021-10-15
     *
     * @param eventId
     * @return
     */
//    public EvnPlanSelected getPlan(String eventId) {
//        EvnPlanSelected planSelected = null;
//        TableDataInfo plan = remoteEventPlanSelectedService.list(eventId);//得到匹配后的预案信息
//        if (plan != null && plan.getRows() != null && plan.getRows().size() > 0) {
//            planSelected = JSON.parseObject(JSON.toJSONString(plan.getRows().get(0)), EvnPlanSelected.class);
//        } else {
//            //doing nothing
//        }
//        return planSelected;
//    }


        public EvnPlanSelected getPlan(String eventId) {
        EvnPlanSelected planSelected = null;
        TableDataInfo plan = remoteEventPlanSelectedService.list(eventId);//得到匹配后的预案信息
        if (plan != null && plan.getRows() != null && plan.getRows().size() > 0) {
            planSelected = JSON.parseObject(JSON.toJSONString(plan.getRows().get(0)), EvnPlanSelected.class);
        } else {
            //doing nothing
        }
        return planSelected;
    }

    /**
     * 根据字典值得到字典名称
     *
     * @param dictType
     * @param dictValue
     * @return
     */
    public String getDictName(String dictType, String dictValue) {
        TableDataInfo dictData = remoteDictDataService.getlist(dictType, dictValue);
        SysDictData sysDictData = null;
        if (dictData != null && dictData.getRows() != null && dictData.getRows().size() > 0) {
            sysDictData = JSON.parseObject(JSON.toJSONString(dictData.getRows().get(0)), SysDictData.class);
        } else {
            //doing nothing
        }
        return sysDictData.getDictLabel();//得到字典名称
    }

    /**
     * 得到分类字典
     *
     * @param categoryValue
     * @return
     */
    public String getCategory(String categoryValue) {
        String categoryName = "";
        R<AjaxResult> eventtype = remoteCategoryService.getInfo(categoryValue);
        if (StringUtils.isNull(eventtype) || StringUtils.isNull(eventtype.getData())) {
            //doing nothing
        } else {
            String name = String.valueOf(eventtype.getData().get("name"));
            categoryName = name.equals("null") ? "" : name;

        }
        return categoryName;
    }

    /**
     * 文件上传
     */
    @RequestMapping("/saveTemplateModel")
    public void uploadModel(HttpServletRequest request, HttpServletResponse response) {
        String type = request.getParameter("type");
        String mesId = request.getParameter("mesId");
        String filepath = fileInfoService.filelist(mesId);

        String fileType = "";
        String path = "";
        switch (type) {
            case "0"://模板管理
                if (TextUtils.isEmpty(filepath)) {
                    path = "system/template/";
                    SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
                    path = path + format.format(new Date()) + "模板.doc";
                } else {
                    path = filepath;
                }
                fileType = "120000";
                break;
            case "1"://值班报告
            case "2"://突发事件
                if (TextUtils.isEmpty(filepath)) {
                    path = "duty/report/";
                    path = path + DateUtils.datePath() + "/" + IdUtils.fastUUID() + ".doc";
                } else {
                    path = filepath;
                }
                fileType = "150000";
                break;
            case "emergency_command_plan"://应急指挥方案
                if (TextUtils.isEmpty(filepath)) {
                    path = "disposalplan/";
                    path = path + DateUtils.datePath() + "/" + IdUtils.fastUUID() + ".doc";
                } else {
                    path = filepath;
                }
                fileType = "160000";
                break;
            case "resource_guarantee_plan"://资源保障方案
                if (TextUtils.isEmpty(filepath)) {
                    path = "disposalplan/";
                    path = path + DateUtils.datePath() + "/" + IdUtils.fastUUID() + ".doc";
                } else {
                    path = filepath;
                }
                fileType = "160001";
                break;
            case "rescue_disposal_plan"://救援处置方案
                if (TextUtils.isEmpty(filepath)) {
                    path = "disposalplan/";
                    path = path + DateUtils.datePath() + "/" + IdUtils.fastUUID() + ".doc";
                } else {
                    path = filepath;
                }
                fileType = "160002";
                break;
            case "emergency_work_plan"://应急工作方案
                if (TextUtils.isEmpty(filepath)) {
                    path = "disposalplan/";
                    path = path + DateUtils.datePath() + "/" + IdUtils.fastUUID() + ".doc";
                } else {
                    path = filepath;
                }
                fileType = "160003";
                break;
            case "env_disaster_evaluation"://灾害快速评估专报
                if (TextUtils.isEmpty(filepath)) {
                    path = "disasterevaluation/";
                    path = path + DateUtils.datePath() + "/" + IdUtils.fastUUID() + ".doc";
                } else {
                    path = filepath;
                }
                fileType = "200000";
                break;
            case "env_sop"://标准作业流程SOP
                if (TextUtils.isEmpty(filepath)) {
                    path = "sop/";
                    path = path + DateUtils.datePath() + "/" + IdUtils.fastUUID() + ".doc";
                } else {
                    path = filepath;
                }
                fileType = "210000";
                break;

        }
        FileSaver fs = new FileSaver(request, response);
        try {
            MultipartFile file = new MockMultipartFile(fs.getFileName(), path, "application/octet-stream", fs.getFileStream());
            remoteFileService.upload(file);
            //删除原来的关联数据
            int f = fileInfoService.delFile(mesId);
            //存储文件
            SysFileInfo files = new SysFileInfo();
            files.setFilePath(path);

            files.setName(path.substring(path.lastIndexOf("/") + 1));
            files.setType(fileType);
            files.setResId(mesId);
            fileInfoService.addFile(files);
            fs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 文件下载
     */
    @RequestMapping("/downloadFile")
    public Object downloadFile(String mesId) {
        String file = fileInfoService.filelist(mesId);
        ResponseEntity<byte[]> entity = remoteFileService.download(file);
        return entity;
    }


    @RequestMapping(value = "/excel", method = RequestMethod.GET)
    public ModelAndView showExcel(HttpServletRequest request, Map<String, Object> map, String file) {
        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        // 加按钮
        poCtrl.addCustomToolButton("保存", "Save", 1);//添加自定义保存按钮
        poCtrl.addCustomToolButton("盖章", "AddSeal", 2);//添加自定义盖章按钮

        poCtrl.setServerPage("/poserver.zz");//设置服务页面
        poCtrl.setSaveFilePage("/save");//设置处理文件保存的请求方法

        //打开excel
        poCtrl.webOpen("/download?file=" + file, OpenModeType.xlsNormalEdit, SecurityUtils.getNickname());
        map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));

        ModelAndView mv = new ModelAndView("Excel");
        return mv;
    }

    /**
     * 添加PageOffice的服务器端授权程序Servlet(必须)
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        com.zhuozhengsoft.pageoffice.poserver.Server poserver = new com.zhuozhengsoft.pageoffice.poserver.Server();
        poserver.setSysPath(pageofficeConfig.getPosyspath());//设置PageOffice注册成功后,license.lic文件存放的目录
        ServletRegistrationBean srb = new ServletRegistrationBean(poserver);
        srb.addUrlMappings("/poserver.zz");
        srb.addUrlMappings("/posetup.exe");
        srb.addUrlMappings("/pageoffice.js");
        srb.addUrlMappings("/jquery.min.js");
        srb.addUrlMappings("/pobstyle.css");
        srb.addUrlMappings("/sealsetup.exe");
        return srb;
    }

    /**
     * 添加印章管理程序Servlet(可选)
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean2() {
        com.zhuozhengsoft.pageoffice.poserver.AdminSeal adminSeal = new com.zhuozhengsoft.pageoffice.poserver.AdminSeal();
        adminSeal.setAdminPassword(pageofficeConfig.getPopassword());//设置印章管理员admin的登录密码
        adminSeal.setSysPath(pageofficeConfig.getPosyspath());//设置印章数据库文件poseal.db存放的目录
        ServletRegistrationBean srb = new ServletRegistrationBean(adminSeal);
        srb.addUrlMappings("/adminseal.zz");
        srb.addUrlMappings("/sealimage.zz");
        srb.addUrlMappings("/loginseal.zz");
        return srb;
    }
}