package com.pqs9000.controller.responsibility;

import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.DatePojo;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.utils.PubUtils;
import com.pqs9000.exception.UserDataException;
import com.pqs9000.pojo.responsibility.*;
import com.pqs9000.service.responsibility.IUserExcelDataService;
import com.pqs9000.service.responsibility.ResponsibilityService;
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.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author hongawen
 * @Date: 2019/3/26 09:57
 */
@Controller
@RequestMapping("responsibility")
public class ResponsibilityCalculateController {

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

    @Autowired
    private ResponsibilityService responsibilityService;

    @Autowired
    private IUserExcelDataService userExcelDataService;

    @Autowired
    UserLogDetailService userLog;

    /**
     * 责任划分列表--》贡献度计算页面
     */
    @GetMapping("calculate")
    public String responsibilityList() {
        return "business/responsibility/calculate";
    }


    /**
     * 根据用户参数查询出条件下的历史谐波数据
     *
     * @param lineIndex 监测点索引
     * @param startTime 起始时间
     * @param endTime   截止时间
     * @param type      谐波类型
     * @param time      谐波次数
     */
    @PostMapping("historyData")
    @ResponseBody
    public HttpResult getHistoryData(Integer lineIndex, String startTime, String endTime, String type, Integer time, HttpServletRequest request) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getHistoryData");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }
        //首先校验前台传的参数正确性
        if (lineIndex == null || time == null) {
            //xuyang_add time增加正则判断，只能读取非0的正整数
            String pattern = "^\\+?[1-9][0-9]*$";
            if (!Pattern.matches(pattern,String.valueOf(time))){
                result = PubUtils.assignmentResult(null, 500, "前台参数异常");
                return result;
            }
        }
        List<Responsibility> historyData;
        try {
            historyData = responsibilityService.getHistoryData(lineIndex, datePojo.getStartTime(), datePojo.getEndTime(), type, time);
            if (CollectionUtils.isEmpty(historyData)) {
                historyData = new ArrayList<>();
            }
            Float overLimt=responsibilityService.getLimitByTimeAndType(lineIndex,time,type);
            HarmHistoryDataResult historyResult=new HarmHistoryDataResult();
            if(null==overLimt){
                historyResult.setOverlimit(0.0f);
            }else{
                historyResult.setOverlimit(overLimt);
            }
            historyResult.setHistoryData(historyData);
            result = PubUtils.assignmentResult(historyResult, 200, "获取谐波历史数据成功");
            userLog.getLog("查询责任量化历史谐波数据", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (UserDataException u) {
            result = PubUtils.assignmentResult(new ArrayList<>(), 501, u.getMessage());
            userLog.getLog("查询责任量化历史谐波数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            logger.error("获取历史谐波数据异常，异常为" + e.toString());
            userLog.getLog("查询责任量化历史谐波数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            result = PubUtils.assignmentResult(null, 500, "获取历史谐波数据异常");
        }
        return result;
    }


    /**
     * 上传用采数据，并对用采数据进行数据分析并缓存
     * 借用hutool中excel工具操作表格数据
     *
     * @param file 上传的表格
     */
    @PostMapping("uploadExcelData")
    @ResponseBody
    public HttpResult uploadExcelData(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request) {
        HttpResult result;
        //获取文件名
        String fileName = file.getOriginalFilename();
        /**
         * ---------------------------------------------------------------------------------------------------
         * xuyang 2020.08.27
         * 修改：对上传文件做判断
         * 1.文件类型 2.文件大小
         */
        //文件大小(此大小为kb)
        Long fileSize  = file.getSize()/1024;
        //判断文件大小
        if (fileSize > 3072){
            result = PubUtils.assignmentResult(null, 500, "上传失败,上传文件超过3M，文件过大!");
            userLog.getLog("上传用采数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            return result;
        }
        /**
         * over
         * ---------------------------------------------------------------------------------------------------
         */

        if (!fileName.matches("^.+\\.(?i)(xlsx)$") && !fileName.matches("^.+\\.(?i)(xls)$")) {
            result = PubUtils.assignmentResult(null, 500, "上传文件类型错误!");
            return result;
        }
        String dealInfo;
        try {
            dealInfo = responsibilityService.dealExcelData(file);
            if (dealInfo.equalsIgnoreCase("用采数据上传成功")) {
                result = PubUtils.assignmentResult(null, 200, "用采数据上传成功");
            } else {
                result = PubUtils.assignmentResult(null, 200, dealInfo.substring(1));
            }
            userLog.getLog("上传用采数据", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            logger.error("上传用采数据异常，异常信息为：" + e.toString());
            userLog.getLog("上传用采数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            result = PubUtils.assignmentResult(null, 500, e.getMessage());
        }
        return result;
    }


    /**
     * 根据谐波数据和功率数据获取动态数据以及责任量化值
     *
     * @param startTime     起始时间
     * @param endTime       截止时间
     * @param type          干扰源类型终
     * @param lineIndex     监测点号
     * @param time          次数
     * @param userDataIndex 用采数据索引
     */
    @PostMapping("getDynamicData")
    @ResponseBody
    public HttpResult getDynamicData(String startTime, String endTime, String type, Integer lineIndex, Integer time, String userDataIndex, int calFlag,HttpServletRequest request) {
        HttpResult result;
        DatePojo datePojo;

        datePojo = PubUtils.validateDate(startTime, endTime, "getHistoryData");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }
        //首先校验前台传的参数正确性
        if (lineIndex == null || time == null) {
            result = PubUtils.assignmentResult(null, 500, "前台参数异常");
            return result;
        }
        ResponsibilityResult datas;
        try {
            //以谐波数据和功率数据获取最终值
            datas = responsibilityService.getDynamicDataAndResponsibiltyByPData(datePojo.getStartTime(), datePojo.getEndTime(), type, lineIndex, time, userDataIndex, calFlag);
            result = PubUtils.assignmentResult(datas, 200, "获取动态谐波责任数据和谐波责任成功");
            userLog.getLog("查询动态谐波责任数据", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (UserDataException u) {
            //捕获到该异常表示，可识别的某种理想异常
            logger.error("获取动态谐波责任数据和责任量化数据异常，异常为：" + u.getMessage());
            result = PubUtils.assignmentResult(null, 501, u.getMessage());
            userLog.getLog("查询动态谐波责任数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            logger.error("获取动态谐波责任数据和谐波责任异常，异常为：" + e.toString());
            e.printStackTrace();
            userLog.getLog("查询动态谐波责任数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            result = PubUtils.assignmentResult(null, 500, e.getMessage());
        }
        return result;
    }

    /**
     * 根据谐波数据和功率数据获取动态数据以及责任量化值
     *
     * @param startTime     起始时间
     * @param endTime       截止时间
     * @param time          次数
     */
    @PostMapping("getResponsibilityData")
    @ResponseBody
    public HttpResult getResponsibilityData(String startTime, String endTime,  Integer time,float limitValue,String limitStartTime,String limitEndTime,String responsibilityIndex) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getHistoryData");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }
        //首先校验前台传的参数正确性
        if (StringUtils.isEmpty(responsibilityIndex) || time == null) {
            result = PubUtils.assignmentResult(null, 500, "前台参数异常");
            return result;
        }
        Date limitS;
        Date limitE;
        //如果两个是时间点是用户自己选择的，那么起始时间可能存在大于截止时间
        try {
            Date start=datePojo.getStartTime();
            Date end=datePojo.getEndTime();
            if(StringUtils.isEmpty(limitStartTime)){
                limitS=start;
            }else{
                limitS=PubUtils.string2Date(limitStartTime,"yyyy-MM-dd HH:mm:ss");
            }
            if(StringUtils.isEmpty(limitEndTime)) {
                limitE=end;
            }else{
                limitE=PubUtils.string2Date(limitEndTime,"yyyy-MM-dd HH:mm:ss");
            }
            Date temp;
            if(limitS.compareTo(limitE)>0){
                //调换两个时间位置
                temp=limitS;
                limitS=limitE;
                limitE=temp;
            }
            //判断限值起始时间是否小于起始时间以及限值截止时间是否大于截止时间
            if(start.compareTo(limitS)>0){
                limitS=start;
            }
            if(end.compareTo(limitE)<0){
                limitE=end;
            }
        } catch (Exception e) {
            //解释两个时间点异常，直接返回前台提示
            result = PubUtils.assignmentResult(null, 500, "解析时间点异常");
            logger.error("解析限值时间点为Date出异常，异常为："+e.toString());
            return result;
        }
        ResponsibilityResult datas;
        try {
            //以谐波数据和功率数据获取最终值
            datas = responsibilityService.getDynamicDataAndResponsibiltyByFkData(datePojo.getStartTime(), datePojo.getEndTime(), time,limitValue,limitS,limitE,responsibilityIndex);
            result = PubUtils.assignmentResult(datas, 200, "获取责任量化值成功");
        } catch (UserDataException u) {
            //捕获到该异常表示，可识别的某种理想异常
            logger.error("获取责任量化值异常，异常为：" + u.getMessage());
            result = PubUtils.assignmentResult(null, 501, u.getMessage());
        } catch (Exception e) {
            logger.error("获取动责任量化值异常，异常为：" + e.toString());
            result = PubUtils.assignmentResult(null, 500, e.getMessage());
        }
        return result;
    }


    /**
     * 库中查询用采数据列表，让用户选择某数据，进行责任划分分析
     */
    @PostMapping("getUserDataList")
    @ResponseBody
    public HttpResult getUserDataList() {
        HttpResult result;
        List<UserExcelData> userExcelDataList;
        try {
            userExcelDataList = userExcelDataService.getUserExcelDataList();
            if (CollectionUtils.isEmpty(userExcelDataList)) {
                result = PubUtils.assignmentResult(null, 500, "暂无用采数据");
            } else {
                result = PubUtils.assignmentResult(userExcelDataList, 200, "获取用采数据列表成功");
            }
        } catch (Exception e) {
            logger.error("获取用采数据列表异常，异常为：" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "获取用采数据列表异常");
        }
        return result;
    }


}
