package com.pqs9000.controller.area;

import cn.hutool.core.io.FileUtil;
import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.*;
import com.njcn.pojo.data.Detailed;
import com.njcn.pojo.data.LimitrateDays;
import com.njcn.service.commons.IWaveService;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.service.user.DeptsService;
import com.njcn.shiro.cache.VCache;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.AppConfig;
import com.njcn.utils.PubUtils;
import com.njcn.utils.ZipUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipOutputStream;

/**
 * 区域业务的controller
 */
@Controller
@RequestMapping("/area")
public class AreaController {

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

    @Autowired
    private IWaveService waveService;

    @Autowired
    private AppConfig appConfig;

    static VCache cache;

    @Resource
    private DeptsService deptsService;

    @Autowired
    UserLogDetailService userLog;


    /**
     * 暂降事件列表中波形查看 最新优化的波形数据获取方式
     *
     * @param session    会话
     * @param eventIndex 事件索引
     */
    @RequestMapping(value = "getWavedata", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getWavedata(HttpSession session, String eventIndex, HttpServletRequest request) {
        session.removeAttribute("eventIndex");
        HttpResult result;
        if (StringUtils.isBlank(eventIndex)) {
            result = PubUtils.assignmentResult(null, 500, "没有获取到事件的索引");
            logger.error("根据事件编号获取波形数据失败，方法名：getWaveData");
        } else {
            WaveData waveData;
            try {
                waveData = waveService.getWavedata(eventIndex, 1);
                result = PubUtils.assignmentResult(waveData, 200, "获取波形数据成功");
                userLog.getLog("查询波形数据", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            } catch (Exception e) {
                logger.error("事件编号为：" + eventIndex + "，获取波形数据异常，异常为：" + e);
                result = PubUtils.assignmentResult(null, 500, "因为异常导致获取波形数据失败");
                userLog.getLog("查询波形数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            }
        }
        return result;
    }

    /**
     * 暂降事件列表批量下载波形，先判断波形文件存在与否
     */
    @PostMapping("downloadWave")
    @ResponseBody
    public HttpResult downloadWave(@RequestParam("index[]") List<String> index, HttpServletRequest request) {
        HttpResult result;
        if (CollectionUtils.isEmpty(index)) {
            result = PubUtils.assignmentResult(null, 500, "请选中需要下载的波形");
            return result;
        }
        try {
            //下载前，清空备份
            String item = "njcntemp" + File.separator + "waveTemp9000";
            FileUtil.clean(new File(appConfig.getTmppath() + item));
            Map<String, List<String>> indexList = waveService.getEventDetailIndexList(index);
            if (CollectionUtils.isEmpty(indexList)) {
                result = PubUtils.assignmentResult(null, 500, "没有波形数据");
            } else {
                result = PubUtils.assignmentResult(indexList, 200, "波形数据准备完毕");
                cache.set(TokenManager.getUserId() + TokenManager.getSysType() + "waveFiles9200", indexList);
            }
            userLog.getLog("下载波形文件", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            logger.error("后台获取数据出错，方法名为：downloadWave，异常为：" + e);
            userLog.getLog("下载波形文件", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            result = PubUtils.assignmentResult(null, 500, "获取暂降事件数据出错，请联系管理员");
        }
        return result;
    }

    /**
     * 下载波形文件
     */
    @RequestMapping("downWaveZip")
    public void downZIPFile(HttpServletResponse response) throws Exception {
        Map<String, List<String>> files = cache.get(TokenManager.getUserId() + TokenManager.getSysType() + "waveFiles9200");
        if (CollectionUtils.isEmpty(files)) {
            return;
        }
        String zipName = "Comtrade.zip";
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
        try {
            Iterator<Map.Entry<String, List<String>>> it = files.entrySet().iterator();
            String item = "njcntemp/waveTemp9000";
            File comtrade = new File(appConfig.getTmppath() + item);
            FileUtil.clean(comtrade);
            while (it.hasNext()) {
                Map.Entry<String, List<String>> entry = it.next();
                List<String> filePaths = entry.getValue();
                File directoryFile = new File(appConfig.getTmppath() + item + File.separator + entry.getKey());
                for (String path : filePaths) {
                    FileUtils.copyFileToDirectory(new File(path), directoryFile);
                }
            }
            ZipUtils.doCompress(comtrade.getPath(), out);
            //压缩完毕后，清除这个文件夹下的所有的文件
            FileUtil.clean(comtrade);
            response.flushBuffer();
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            out.close();
        }
    }

    /**
     * 根据当前身份或者前台区域获取父子节点地区
     */
    @PostMapping("getMapInfo")
    @ResponseBody
    public HttpResult getMapInfo(String area, HttpServletRequest request) {
        HttpResult httpResult;
        SimpleValue simpleValue;
        try {
            simpleValue = deptsService.getMapInfo(area);
            httpResult = PubUtils.assignmentResult(simpleValue, 200, "获取地图信息成功");
            userLog.getLog("查询地图信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            httpResult = PubUtils.assignmentResult(null, 500, "获取地图信息失败");
            userLog.getLog("查询地图信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            logger.error("获取地图信息异常，异常为：" + e.toString());
        }
        return httpResult;
    }

    @PostMapping("getDataByTime")
    @ResponseBody
    public HttpResult getDataByTime(String name, String start, String end, String type, HttpServletRequest request) {
        HttpResult httpResult;

        DatePojo datePojo;
        datePojo = PubUtils.validateDate(start, end, "getDataByTime");

        if (!datePojo.getValidity()) {
            httpResult = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return httpResult;
        }

        try {
            List<LimitrateDays> list = deptsService.getLimitRateDays(name, datePojo.getStartTime(), datePojo.getEndTime(), Integer.parseInt(type));
            httpResult = PubUtils.assignmentResult(list, 200, "获取稳态越限天数统计成功");
            userLog.getLog("查询稳态越限天数", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            httpResult = PubUtils.assignmentResult(null, 500, "获取稳态越限天数统计失败");
            logger.error("获取稳态越限天数统计异常，异常为：" + e.toString());
            userLog.getLog("查询稳态越限天数", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        }
        return httpResult;
    }

    @PostMapping("getdetailed")
    @ResponseBody
    public HttpResult getdetailed(String guid, String time, String type, String timetype, HttpServletRequest request) {
        HttpResult httpResult;
        Calendar calendar = Calendar.getInstance();
        Calendar calendar1 = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date date = sdf.parse(time);
            calendar.setTime(date);
            calendar1.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
            calendar1.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
            calendar1.set(Calendar.HOUR_OF_DAY, 23);
            calendar1.set(Calendar.MINUTE, 59);
            calendar1.set(Calendar.SECOND, 59);

            if (timetype.equals("0")) { //日
                calendar1.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH));
            } else {
                calendar1.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            }
        } catch (ParseException e) {
            httpResult = PubUtils.assignmentResult(null, 500, e.getMessage());
            return httpResult;
        }

        try {
            List<Detailed> list = deptsService.getDetailed(calendar.getTime(), calendar1.getTime(), guid, type);
            httpResult = PubUtils.assignmentResult(list, 200, "获取越限详细信息成功");
            userLog.getLog("查询越限详细信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            httpResult = PubUtils.assignmentResult(null, 500, "获取越限详细信息失败");
            userLog.getLog("查询越限详细信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            logger.error("获取越限详细信息异常，异常为：" + e.toString());
        }

        return httpResult;
    }
}