package com.pqs9900.controller.linedata;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.DatePojo;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.runmanage.IntergralityData;
import com.njcn.pojo.commons.runmanage.OnlineRateData;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.pqs9900.pojo.linedata.*;
import com.pqs9900.service.linedata.TerminalRunService;
import com.pqs9900.service.terminal.VersionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * system
 * 告警策略
 * @author cdf
 * @date 2021/11/3
 */
@RestController
@RequestMapping("inStrategy")
public class TopStrategyController {

    private static final Logger logger = LoggerFactory.getLogger(TopStrategyController.class);

    @Resource
    private TerminalRunService terminalRunService;

    @Autowired
    UserLogDetailService userLog;


    /**
     * 新增
     *
     * @author cdf
     * @date 2021/11/3
     */
    @PostMapping("addForRun")
    public HttpResult addForRun(@RequestBody TerminalRun terminalRun) {
        Integer res = terminalRunService.addForRun(terminalRun);
        if (res == 1) {
            return PubUtils.assignmentResult(null, 200, "操作成功");
        } else if (res == -1) {
            return PubUtils.assignmentResult(null, 500, "已存在此等级策略，请勿重复操作");
        } else {
            return PubUtils.assignmentResult(null, 500, "操作失败");
        }
    }

    /**
     * 修改
     *
     * @author cdf
     * @date 2021/11/3
     */
    @PostMapping("updateForRun")
    public HttpResult updateForRun(@RequestBody TerminalRun terminalRun) {
        Integer res = terminalRunService.updateForRun(terminalRun);
        if (res == 1) {
            return PubUtils.assignmentResult(null, 200, "操作成功");
        } else {
            return PubUtils.assignmentResult(null, 500, "操作失败");
        }
    }


    /**
     * 查询
     *
     * @author cdf
     * @date 2021/11/3
     */
    @GetMapping("queryForRun")
    public HttpResult queryForRun(String dicIndex) {
        TerminalRun terminalRun = terminalRunService.queryForRun(dicIndex);
        if (Objects.nonNull(terminalRun)) {
            return PubUtils.assignmentResult(terminalRun, 200, "操作成功");
        } else {
            return PubUtils.assignmentResult(null, 500, "操作失败");
        }
    }

    /**
     * 获取所有等级的策略
     *
     * @author cdf
     * @date 2021/11/3
     */
    @GetMapping("queryListForRun")
    public HttpResult queryListForRun() {
        List<TerminalRun> interalStrategy = terminalRunService.queryListForRun();
        if (CollectionUtil.isNotEmpty(interalStrategy)) {
            return PubUtils.assignmentResult(interalStrategy, 200, "操作成功");
        } else {
            return PubUtils.assignmentResult(null, 500, "数据为空");
        }
    }

    /**
     * 删除
     *
     * @author cdf
     * @date 2021/11/3
     */
    @GetMapping("deleteForRun")
    public HttpResult deleteForRun(@RequestParam("dicIndex") String dicIndex) {
        Integer res = terminalRunService.deleteForRun(dicIndex);
        if (res == 1) {
            return PubUtils.assignmentResult(null, 200, "操作成功");
        } else {
            return PubUtils.assignmentResult(null, 500, "操作失败");
        }
    }

    /**
     * 运行管理中的终端在线率数据查询展示
     *
     * @param startTime 起始时间
     * @param endTime   截止时间
     * @param colorFlag   是否达标
     */
    @PostMapping("getOnlineRateData")
    @ResponseBody
    public HttpResult getOnlineRateData(String startTime, String endTime,Integer lineGrade,Integer colorFlag, HttpServletRequest request) {
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.BUSSINESS.toString(), 0);
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getOnlineRateData");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }
        List<OnlineRateData> onlineRateDatas;
        try {
            onlineRateDatas = terminalRunService.getOnlineRate(datePojo.getStartTime(), datePojo.getEndTime(),lineGrade,colorFlag);
            if (CollectionUtil.isEmpty(onlineRateDatas)) {
                result = PubUtils.assignmentResultLog(null, 500, "获取终端在线率数据为空", "查询在线率列表", "成功", result);
            } else {
                result = PubUtils.assignmentResultLog(onlineRateDatas, 200, "获取终端在线率数据成功", "查询在线率列表", "成功", result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取终端运行数据异常,异常为：" + e.toString());
            result = PubUtils.assignmentResultLog(null, 500, "获取终端在线率数据异常", "查询在线率列表", "失败", result);
        }
        return result;
    }


    /**
     * 运行管理--》监测点数据完整性
     *
     * @param startTime 起始时间
     * @param endTime   截止时间
     */
    @PostMapping("getIntegrityData")
    @ResponseBody
    public HttpResult getIntegrityData(String startTime, String endTime,Integer lineGrade,Integer colorFlag, HttpServletRequest request) {
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.BUSSINESS.toString(), 0);
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getIntegrityData");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }
        IntergralityData intergralityData;
        try {
            intergralityData = terminalRunService.getDataIntegralityTable(datePojo.getStartTime(), datePojo.getEndTime(),lineGrade,colorFlag);
            if (null == intergralityData) {
                result = PubUtils.assignmentResultLog(null, 500, "获取监测点数据完整性数据为空", "查询完整性列表", "成功", result);
            } else {
                result = PubUtils.assignmentResultLog(intergralityData, 200, "获取监测点数据完整性数据成功", "查询完整性列表", "成功", result);
            }
            // userLog.getLog("查询监测点数据完整性", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            logger.error("获取终端运行数据异常,异常为：" + e.toString());
            result = PubUtils.assignmentResultLog(null, 500, "获取监测点数据完整性数据异常", "查询完整性列表", "成功", result);
            // userLog.getLog("查询监测点数据完整性", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        }
        return result;
    }


    /**
     * 终端运行异常页面列表初始化
     * 获取每日终端异常消息
     * @author cdf
     * @date 2021/11/9
     */
    @PostMapping("getRunExceptionList")
    public HttpResult getRunExceptionList(String startTime, String endTime, Integer lineGrade) {
        HttpResult result;
        DatePojo datePojo = PubUtils.validateDate(startTime, endTime, "getRunExceptionList");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }
        List<TopView> list = terminalRunService.getRunExceptionList(datePojo.getStartTime(), datePojo.getEndTime(), lineGrade);
        return PubUtils.assignmentResult(list, 200, "获取成功");
    }


    /**
     * 获取指定日期运行异常的装置
     * @author cdf
     * @date 2021/11/15
     */
    @PostMapping("getRunExceptionDetail")
    public HttpResult getRunExceptionDetail(String timeId,Integer lineGrade) {
        if(StrUtil.isBlank(timeId)){
            return PubUtils.assignmentResult(null, 500, "参数校验失败");
        }
        Date time;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            time = sdf.parse(timeId);
        } catch (ParseException e) {
          return PubUtils.assignmentResult(null,500,"时间格式出错");
        }

        List<TopException> list = terminalRunService.getRunExceptionDetail(time,lineGrade);
        return PubUtils.assignmentResult(list, 200, "获取成功");
    }

    /**
     * 通过设备id获取指定日期运行异常的装置
     * @author cdf
     * @date 2021/11/15
     */
    @PostMapping("getRunExceptionDetailById")
    public HttpResult getRunExceptionDetailById(String timeId,Integer devIndex) {
        if(StrUtil.isBlank(timeId)){
            return PubUtils.assignmentResult(null, 500, "参数校验失败");
        }
        Date time;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            time = sdf.parse(timeId);
        } catch (ParseException e) {
            return PubUtils.assignmentResult(null,500,"时间格式出错");
        }

        TopException topException= terminalRunService.getRunExceptionDetailById(time,devIndex);
        return PubUtils.assignmentResult(topException, 200, "获取成功");
    }


    /**
     * 获取指定日期数据完整性统计
     * @author dhj
     * @date 2021/12/07
     */
    @PostMapping("getDataIntegralityStatis")
    public HttpResult getDataIntegralityStatis(String startTime,String endTime,Long lineId) {
        List<DataIntegralityStatis> dataIntegralityStatis = new ArrayList<>();
        if(StrUtil.isBlank(startTime) && StrUtil.isBlank(endTime)){
            return PubUtils.assignmentResult(null, 500, "参数校验失败");
        }
        try {
            dataIntegralityStatis = terminalRunService.getDataIntegralityStatis(lineId,startTime,endTime);
        } catch (Exception e) {
            return PubUtils.assignmentResult(null,500,"获取失败");
        }
        return PubUtils.assignmentResult(dataIntegralityStatis, 200, "获取成功");
    }


    //稳态数据补招补招
    @RequestMapping(value = "socketonIntegrityData", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult socketonIntegrityData(HttpServletRequest request, String type, Long LineId, String startTime,String endTime) {
        String result = "";
        try {
            result = terminalRunService.socketonIntegrityData(type, LineId, startTime,endTime);
            if("稳态数据补招命令接收成功".equals(result)){
                userLog.getLog("稳态数据补招", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
                return PubUtils.assignmentResult(null,200,result);
            }else{
                return PubUtils.assignmentResult(null,500,result);
            }

        } catch (Exception e) {
            userLog.getLog("稳态数据补招", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            logger.error("socket异常，异常是" + e.getMessage());
            return PubUtils.assignmentResult(null,500,"稳态数据补招异常");
        }
    }

    /**
     * 在线率cld主页面
     * @author cdf
     * @date 2021/12/16
     */
    @GetMapping("getOnlineRateCldList")
    public HttpResult getOnlineRateCldList(String startTime,String endTime,Integer lineGrade,Integer colorFlag) {

        DatePojo datePojo = PubUtils.validateDate(startTime, endTime, "getOnlineRateCldList");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            return PubUtils.assignmentResult(null, 500, datePojo.getMsg());
        }
        List<OnlineRateCldRVO> list = terminalRunService.getOnlineRateCldList(datePojo.getStartTime(),datePojo.getEndTime(),lineGrade,colorFlag);
        return PubUtils.assignmentResult(list, 200, "获取成功");
    }



}
