package com.pqs9300.controller.flowChart;

import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.AppConfig;
import com.njcn.utils.PubUtils;
import com.pqs9300.controller.technical.TechnicalInfoController;
import com.pqs9300.controller.transaction.TransactionController;
import com.pqs9300.mapper.transaction.OverRunLogMapper;
import com.pqs9300.pojo.transaction.OverRunLogDetail;
import com.pqs9300.pojo.transaction.Supervise;
import com.pqs9300.service.flowChart.FlowChartService;
import com.pqs9300.service.transaction.SuperviseService;
import com.pqs9300.util.WordUtil2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.Integer.parseInt;

@Controller
@RequestMapping("flowChart")
public class FlowChartController {

    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(TechnicalInfoController.class);

    @Autowired
    private FlowChartService flowChartService;

    @Resource
    private SuperviseService superviseService;

    @Resource
    private AppConfig appConfig;

    @Resource
    private OverRunLogMapper overRunLogMapper;

    /**
     * @Author: xuyang
     * @Date: 2020/7/1 14:50
     * @Description:  展示流程图
     */
    @RequestMapping(value = "getFlowChart")
    public String vdWaveform(HttpServletRequest request, HttpSession session,String flowChartSupIndex,int flowChartType,int flowChartProgress) {
        String filePath = "";
        session.setAttribute("flowChartSupIndex", flowChartSupIndex);
        session.setAttribute("flowChartType", flowChartType);
        session.setAttribute("flowChartProgress", flowChartProgress);
        if (flowChartType == 0){
            filePath = "business/flowChart/flowChart";
        } else {
            filePath = "business/flowChart/flowGaoJingChart";
        }
        return filePath;
    }

    /**
     * @Author: xuyang
     * @Date: 2020/7/2 12:57
     * @Description:    根据supIndex获取当前电压等级
     */
    @RequestMapping(value = "getPowerLever")
    @ResponseBody
    public String powerLever(@RequestParam("flowChartSupIndex") String flowChartSupIndex){
        return flowChartService.getPowerLever(flowChartSupIndex);
    }

    /**
     * 打开数据列表
     */
    @GetMapping("/openFlowChartData")
    public ModelAndView flowChartData(String supIndex, Integer excuteStep, String stepCount) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("supIndex", supIndex);
        modelAndView.addObject("excuteStep", excuteStep);
        modelAndView.addObject("stepCount", stepCount);
        modelAndView.setViewName("business/flowChart/flowChartData");
        return modelAndView;
    }

    /**
     * 根据事务索引校验后台的事务索引和报告文档是否存在
     * @param supIndex 事务索引
     */
    @PostMapping("checkTransaction")
    @ResponseBody
    public HttpResult checkTransaction(String supIndex, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.BUSSINESS.toString(), 0);
        //先判断事务是否存在
        Supervise supervise;
        try {
            supervise = superviseService.isExist(supIndex);
            if (null == supervise) {
                result = PubUtils.assignmentResultLog(null, 500, "当前事务数据丢失", "预/告警单下载", "成功", result);
            } else {
                //再开始判断当前功能需求的模板文档是否存在
                Integer type = supervise.getType();
                InputStream ins;
                //判断有文件后，进行文档准备，保存进指定文件夹，待会提供下载
                String path = appConfig.getTmppath();
                String rtfPath = "";
                if (type == 0) {
                    //去找预警模板
                    ins = TransactionController.class.getClassLoader().getResourceAsStream("file"+ File.separator+"earlyWarn.docx");
                    if (null == ins) {
                        result = PubUtils.assignmentResultLog(null, 500, "模板丢失", "预/告警单下载", "成功", result);
                    } else {
                        ins.close();
                        path = path + File.separator+"njcn"+File.separator+"transaction"+File.separator+"earlyWarn"+File.separator + supervise.getName();
                        rtfPath = getClass().getClassLoader().getResource("file"+File.separator+"earlyWarn.docx").getPath();
                        rtfPath = rtfPath.replaceAll("%20", " ");
                    }
                } else {
                    //去找告警模板
                    ins = TransactionController.class.getClassLoader().getResourceAsStream("file"+File.separator+"alarm.docx");
                    if (null == ins) {
                        result = PubUtils.assignmentResultLog(null, 500, "模板丢失", "预/告警单下载", "成功", result);
                    } else {
                        ins.close();
                        path = path + File.separator+"njcn"+File.separator+"transaction"+File.separator+"alarm"+File.separator + supervise.getName();
                        rtfPath = getClass().getClassLoader().getResource("file"+File.separator+"alarm.docx").getPath();
                        rtfPath = rtfPath.replaceAll("%20", " ");
                    }
                }

                //获取所有的监测点越限信息
                List<OverRunLogDetail> overRunLogList = overRunLogMapper.getMonitorDetailData(supIndex);
                if (CollectionUtils.isEmpty(overRunLogList)) {
                    //该事物没有监测点预警或者告警信息
                    result = PubUtils.assignmentResultLog(null, 500, "该事件没有监测点详细越限数据", "预/告警单下载", "成功", result);
                } else {
                    List<Map<String, Object>> totalData = new ArrayList<>();
                    for (OverRunLogDetail overRunLogDetail : overRunLogList) {
                        Map<String, Object> reportmap = new HashMap<>();
                        reportmap.put("date", PubUtils.date2String(overRunLogDetail.getOverRunLog().getUpdateTime(), "yyyy年MM月dd日"));
                        reportmap.put("gdName", overRunLogDetail.getGdName());
                        reportmap.put("deptsName", overRunLogDetail.getDeptsName());
                        reportmap.put("mark", overRunLogDetail.getOverRunLog().getOverRunDescribe());
                        reportmap.put("fileName", overRunLogDetail.getOverRunLog().getName() + ".docx");
                        totalData.add(reportmap);
                    }
                    //收集完信息，开始一个个的保存到对应的文件夹中，每个文件名：监测点名+年月日
                    WordUtil2 oRTF = new WordUtil2();
                    try {
                        oRTF.getWordWarn(rtfPath, totalData, path, response, session);
                    } catch (Exception e) {
                    }
                    result = PubUtils.assignmentResultLog(null, 200, "可以后台下载", "预/告警单下载", "成功", result);
                }
            }
        } catch (Exception e) {
            logger.error("获取出各监测点越限的详细数据异常,异常为：" + e.toString());
            result = PubUtils.assignmentResultLog(null, 500, "下载异常", "预/告警单下载", "失败", result);
        }
        return result;
    }

    /**
     * 根据事务索引校验后台的报告文档是否存在
     * @param supIndex 事务索引
     */
    @PostMapping("checkTransactionNotice")
    @ResponseBody
    public HttpResult checkTransactionNotice(String supIndex, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.BUSSINESS.toString(), 0);
        //先判断事务是否存在
        Supervise supervise;
        try {
            supervise = superviseService.isExist(supIndex);
            if (null == supervise) {
                result = PubUtils.assignmentResultLog(null, 500, "当前事务数据丢失", "整改通知单下载", "成功", result);
            } else {
                //再开始判断当前功能需求的模板文档是否存在
                Integer type = supervise.getType();
                InputStream ins;
                //判断有文件后，进行文档准备，保存进指定文件夹，待会提供下载
                String path = appConfig.getTmppath();
                String rtfPath = "";
                //去找预警模板
                ins = TransactionController.class.getClassLoader().getResourceAsStream("file"+File.separator+"notice.docx");
                if (null == ins) {
                    result = PubUtils.assignmentResultLog(null, 500, "模板丢失", "整改通知单下载", "成功", result);
                } else {
                    ins.close();
                    path = path + File.separator+"njcn"+File.separator+"transaction"+File.separator+"notice"+File.separator + supervise.getName();
                    rtfPath = getClass().getClassLoader().getResource("file"+File.separator+"notice.docx").getPath();
                    rtfPath = rtfPath.replaceAll("%20", " ");
                }
                //获取所有的监测点越限信息
                List<OverRunLogDetail> overRunLogList = overRunLogMapper.getMonitorDetailData(supIndex);
                if (CollectionUtils.isEmpty(overRunLogList)) {
                    //该事物没有监测点预警或者告警信息
                    result = PubUtils.assignmentResultLog(null, 500, "该事件没有监测点详细越限数据", "整改通知单下载", "成功", result);
                } else {
                    List<Map<String, Object>> totalData = new ArrayList<>();
                    for (OverRunLogDetail overRunLogDetail : overRunLogList) {
                        Map<String, Object> reportmap = new HashMap<>();
                        reportmap.put("date", PubUtils.date2String(overRunLogDetail.getOverRunLog().getUpdateTime(), "yyyy年MM月dd日"));
                        reportmap.put("gdName", overRunLogDetail.getGdName());
                        reportmap.put("deptsName", overRunLogDetail.getDeptsName());
                        reportmap.put("mark", overRunLogDetail.getOverRunLog().getOverRunDescribe());
                        reportmap.put("fileName", overRunLogDetail.getOverRunLog().getName()+ ".docx");
                        totalData.add(reportmap);
                    }
                    //收集完信息，开始一个个的保存到对应的文件夹中，每个文件名：监测点名+年月日
                    WordUtil2 oRTF = new WordUtil2();
                    try {
                        oRTF.getWordWarn(rtfPath, totalData, path, response, session);
                    } catch (Exception e) {
                        logger.error("产生了异常，异常是"+e.getMessage());
                    }
                    result = PubUtils.assignmentResultLog(null, 200, "可以后台下载", "整改通知单下载", "成功", result);
                    //更新当前记录的各个状态，主表的流程+1，监测点谐波详细表的文件路径
                    //superviseService.finishEarlyNotice(supervise);
                }
            }
        } catch (Exception e) {
            logger.error("获取出各监测点越限的详细数据异常,异常为：" + e.toString());
            result = PubUtils.assignmentResultLog(null, 500, "下载异常", "整改通知单下载", "失败", result);
        }
        return result;
    }

    @RequestMapping(value = "getProgress")
    @ResponseBody
    public Integer shiwuProgress(@RequestParam("supIndex") String supIndex){
        return flowChartService.getProgress(supIndex);
    }

}
