package com.pqs9000.controller.area;

import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.AreaGeneralData;
import com.njcn.pojo.commons.DatePojo;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.SteadyTypeData;
import com.njcn.pojo.commons.runmanage.SteadyResult;
import com.njcn.pojo.commons.runmanage.SteadyTable;
import com.njcn.pojo.data.Legder;
import com.njcn.pojo.data.LegderExcel;
import com.njcn.service.configuration.LineService;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.njcn.pojo.advanced.HarmonicRateInfo;
import com.njcn.utils.UserUtil;
import com.pqs9000.util.ExcelUtil;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author hongawen
 * @Date: 2018/6/22 09:15
 */
@Controller
@RequestMapping("area")
public class SteadyStateController {

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

    @Autowired
    private LineService lineService;


    @Autowired
    UserLogDetailService userLog;


    List<Legder> listLegder;



    /**
     * 跳转区域统计的稳态指标
     */
    @GetMapping("steady")
    public String steady() {
        return "business/area/steady";
    }

    @GetMapping("harmonicrate")
    public String harmonicrate() {
        return "business/manage/harmonicrate";
    }


    /**
     * 跳转运行管理--》稳态指标列表
     */
    @GetMapping("steadytable")
    public ModelAndView steadyTable(String starttime,String endtime,String area,String interval) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("business/manage/steadyTable");
        if(StringUtils.isEmpty(starttime)&&StringUtils.isEmpty(endtime)){
            modelAndView.addObject("startTime", "");
            modelAndView.addObject("endTime", "");
        }else{
            DatePojo datePojo=PubUtils.validateDate(starttime,endtime,"steadytable");
            if(!StringUtils.isEmpty(datePojo.getMsg())){
                modelAndView.addObject("startTime", "");
                modelAndView.addObject("endTime", "");
            }else{
                modelAndView.addObject("startTime", starttime);
                modelAndView.addObject("endTime", endtime);
            }
        }
        modelAndView.addObject("area", area);
        modelAndView.addObject("interval", interval);
        return modelAndView;
    }

    @GetMapping("ledger")
    public String ledger() {
        return "business/area/ledger";
    }

    @GetMapping("steadystat")
    public String steadystat() {
        return "business/area/steadystat";
    }

    /**
     * -
     * 运行管理--》稳态指标列表
     *
     * @param area      区域
     * @param startTime 起始时间
     * @param endTime   截止时间
     */
    @PostMapping("getSteadyData")
    @ResponseBody
    public HttpResult getSteadyData(String area, String startTime, String endTime, HttpServletRequest request) {
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.BUSSINESS.toString(), 0);
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getSteadyData");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }
        SteadyResult steadyResult;
        try {
            steadyResult = lineService.getSteadyData(datePojo.getStartTime(), datePojo.getEndTime(), area);
            if (null == steadyResult) {
                result = PubUtils.assignmentResultLog(null, 500, "获取监测点稳态指标合格率数据为空", "查询稳态指标列表", "成功", result);
            } else {
                result = PubUtils.assignmentResultLog(steadyResult, 200, "获取监测点稳态指标合格率数据成功", "查询稳态指标列表", "成功", result);
            }
            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.assignmentResultLog(null, 500, "获取监测点稳态指标合格率数据异常", "查询稳态指标列表", "失败", result);
        }
        return result;
    }


    /**
     * 区域统计--》指标合格率全部
     *
     * @param startTime 起始时间
     * @param endTime   截止时间
     */
    @PostMapping("allData")
    @ResponseBody
    public HttpResult allData(String area, String startTime, String endTime, HttpServletRequest request) {
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.BUSSINESS.toString(), 0);
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "allData");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }
        SteadyTypeData steadyTypeData;
        try {
            steadyTypeData = lineService.getAllData(datePojo.getStartTime(), datePojo.getEndTime(), area);
            if (null == steadyTypeData) {
                result = PubUtils.assignmentResultLog(null, 500, "获取全部数据为空", "查询稳态指标合格率", "成功", result);
            } else {
                result = PubUtils.assignmentResultLog(steadyTypeData, 200, "获取全部数据成功", "查询稳态指标合格率", "成功", result);
            }
            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.assignmentResultLog(null, 500, "获取全部数据异常", "查询稳态指标合格率", "失败", result);
        }
        return result;
    }

    /**
     * 跳转稳态越限详情页面
     *
     * @param areaIndex 部门索引
     * @param startTime 起始时间
     * @param endTime   截止时间
     */
    @GetMapping("outOfLimitDetailView")
    public ModelAndView outOfLimitDetailView(String areaIndex, String startTime, String endTime) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("business/area/steadyOutOfLimitDetail");
        modelAndView.addObject("startTime", startTime);
        modelAndView.addObject("endTime", endTime);
        modelAndView.addObject("area", areaIndex);
        return modelAndView;
    }

    @GetMapping("statoutOfLimitDetailView")
    public ModelAndView statoutOfLimitDetailView(String areaIndex, String startTime, String endTime) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("business/area/steadystatOutOfLimitDetail");
        modelAndView.addObject("startTime", startTime);
        modelAndView.addObject("endTime", endTime);
        modelAndView.addObject("area", areaIndex);
        return modelAndView;
    }

    /**
     * 获取稳态越限详情数据
     *
     * @param area      部门索引
     * @param startTime 起始时间
     * @param endTime   截止时间
     */
    @PostMapping("outOfLimitDetail")
    @ResponseBody
    public HttpResult outOfLimitDetail(String area, String startTime, String endTime, HttpServletRequest request) {
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.BUSSINESS.toString(), 0);
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "allData");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }
        List<SteadyTable> steadyTables;
        try {
            steadyTables = lineService.getSteadyOutOfLimitData(datePojo.getStartTime(), datePojo.getEndTime(), area);
            if (null == steadyTables) {
                result = PubUtils.assignmentResultLog(null, 500, "获取稳态越限详情数据为空", "查询稳态越限详情", "成功", result);
            } else {
                result = PubUtils.assignmentResultLog(steadyTables, 200, "获取稳态越限详情数据成功", "查询稳态越限详情", "成功", result);
            }
        } catch (Exception e) {
            logger.error("获取终端运行数据异常,异常为：" + e.toString());
            result = PubUtils.assignmentResultLog(null, 500, "获取稳态越限详情数据异常", "查询稳态越限详情", "失败", result);
        }
        return result;
    }

    @PostMapping("getHarmonicRate")
    @ResponseBody
    public HttpResult getHarmonicRate(String startTime, String endTime, HttpServletRequest request) {
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.BUSSINESS.toString(), 0);
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getHarmonicRate");

        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }

        List<HarmonicRateInfo> list;
        try {
            list = lineService.getHarmonicRate(datePojo.getStartTime(), datePojo.getEndTime());
            Collections.sort(list);
            if (null == list) {
                result = PubUtils.assignmentResultLog(null, 500, "获取谐波总畸变率数据为空", "查询谐波总畸变率", "成功", result);
            } else {
                result = PubUtils.assignmentResultLog(list, 200, "获取谐波总畸变率数据成功", "查询谐波总畸变率", "成功", result);
            }
        } catch (Exception e) {
            logger.error("获取谐波总畸变率数据异常,异常为：" + e.toString());
            result = PubUtils.assignmentResultLog(null, 500, "获取谐波总畸变率数据异常", "查询谐波总畸变率", "失败", result);
        }

        return result;
    }

    @PostMapping("getledger")
    @ResponseBody
    public HttpResult getLedger(String area, String voltage, String factory, String type, String appear, String nature, HttpServletRequest request) {
        HttpResult httpResult = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.BUSSINESS.toString(), 0);

        try {
            this.listLegder = lineService.getLedger(area, voltage, factory, type, appear, nature);

            if (null == this.listLegder) {
                httpResult = PubUtils.assignmentResultLog(null, 500, "获取台账统计数据为空", "查询台账统计", "成功", httpResult);
            } else {
                httpResult = PubUtils.assignmentResultLog(this.listLegder, 200, "获取谐台账统计数据成功", "查询台账统计", "成功", httpResult);
            }
        } catch (Exception e) {
            logger.error("获取台账统计数据异常,异常为：" + e.toString());
            httpResult = PubUtils.assignmentResultLog(null, 500, "获取台账统计数据异常", "查询台账统计", "失败", httpResult);
        }

        return httpResult;
    }

    @GetMapping(value = "exportExcel")
    public void exportExcel(HttpServletResponse response,HttpServletRequest request) {
        List<LegderExcel> list1 = new ArrayList<>();
        int count = 0;
        int count1 = 0;

        for (Legder legder : this.listLegder) {
            for (Legder.pData pData : legder.getList()) {
                for (Legder.Data data : pData.getList()) {
                    LegderExcel legderExcel = new LegderExcel();
                    legderExcel.setAreaName(legder.getAreaName());
                    legderExcel.setTypeName(pData.getName());
                    legderExcel.setChildType(data.getDicName());
                    legderExcel.setBdCount(data.getGdCount());
                    legderExcel.setDeviceCount(data.getSubCount());
                    legderExcel.setLineCount(data.getLineCount());

                    count++;
                    count1++;

                    list1.add(legderExcel);
                }

                list1.get(list1.size() - 1).setRowCount(count);
                count = 0;
            }

            list1.get(list1.size() - 1).setRowCount1(count1);
            count1 = 0;
        }
        userLog.getLog("导出台账信息表", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        writeExcel(response, list1);
    }

    private void writeExcel(HttpServletResponse response, List<LegderExcel> list) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("台账统计");
        int rowId = 0;
        int cellId = 0;

        //表头部分
        XSSFRow row = sheet.createRow(rowId++);
        XSSFCell cell = null;
        XSSFCellStyle style = setStyleHeader(workbook, sheet);

        setHeader(row, cell, "区域", cellId++, style);
        setHeader(row, cell, "类型", cellId++, style);
        setHeader(row, cell, "分类型", cellId++, style);
        setHeader(row, cell, "变电站个数", cellId++, style);
        setHeader(row, cell, "终端个数", cellId++, style);
        setHeader(row, cell, "监测点个数", cellId++, style);
        cellId = 0;

        //表格内容
        XSSFCellStyle style1 = setStyleBody(workbook, sheet);
        setBody(row, cell, rowId, cellId, list, sheet, style1);

        OutputStream outputStream = null;
        try {
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName = " + new String("台账统计".getBytes("GB2312"), "iso8859-1") + ".xlsx");// 设置文件名
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            try {
                if(null!=outputStream){
                    outputStream.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }

    private void setBody(XSSFRow row, XSSFCell cell, int rowId, int cellId, List<LegderExcel> list, XSSFSheet sheet, XSSFCellStyle style) {
        for (LegderExcel legderExcel : list) {
            row = sheet.createRow(rowId++);
            //第一列只考虑count1
            cell = row.createCell(cellId++);

            if (legderExcel.getRowCount1() == 0) {
                cell.setCellValue(legderExcel.getAreaName());
            } else {
                cell.setCellValue(legderExcel.getAreaName());
                //合并单元格
                sheet.addMergedRegion(new CellRangeAddress(rowId - legderExcel.getRowCount1(), rowId - 1, 0, 0));
            }

            cell.setCellStyle(style);

            //第二列只考虑count
            cell = row.createCell(cellId++);

            if (legderExcel.getRowCount() == 0) {
                cell.setCellValue(legderExcel.getTypeName());
            } else {
                cell.setCellValue(legderExcel.getTypeName());
                //合并单元格
                sheet.addMergedRegion(new CellRangeAddress(rowId - legderExcel.getRowCount(), rowId - 1, 1, 1));
            }

            cell.setCellStyle(style);

            //第三列
            cell = row.createCell(cellId++);
            cell.setCellValue(legderExcel.getChildType());
            cell.setCellStyle(style);

            //第四列
            cell = row.createCell(cellId++);
            cell.setCellValue(legderExcel.getBdCount());
            cell.setCellStyle(style);
            //第五列
            cell = row.createCell(cellId++);
            cell.setCellValue(legderExcel.getDeviceCount());
            cell.setCellStyle(style);
            //第六列
            cell = row.createCell(cellId++);
            cell.setCellValue(legderExcel.getLineCount());
            cell.setCellStyle(style);

            cellId = 0;
        }
    }

    private void setHeader(XSSFRow row, XSSFCell cell, String value, int cellId, XSSFCellStyle style) {
        cell = row.createCell(cellId++);
        cell.setCellValue(value);
        cell.setCellStyle(style);
    }

    private XSSFCellStyle setStyleHeader(XSSFWorkbook workbook, XSSFSheet sheet) {
        XSSFFont font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 10);
        XSSFCellStyle style4;
        style4 = workbook.createCellStyle();
        font.setBold(true);
        style4.setVerticalAlignment(VerticalAlignment.CENTER);
        style4.setAlignment(HorizontalAlignment.CENTER_SELECTION);
        style4.setFont(font);
        //设置列宽
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 12 * 256);
        sheet.setColumnWidth(2, 20 * 256);
        return style4;
    }

    private XSSFCellStyle setStyleBody(XSSFWorkbook workbook, XSSFSheet sheet) {
        XSSFFont font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 10);
        XSSFCellStyle style6;
        style6 = workbook.createCellStyle();
        style6.setVerticalAlignment(VerticalAlignment.CENTER);
        style6.setAlignment(HorizontalAlignment.CENTER_SELECTION);
        style6.setFont(font);
        return style6;
    }
}
