package com.pqs9000.serviceimpl.report;

import cn.hutool.core.collection.CollectionUtil;
import com.njcn.enums.LogTypeEnum;
import com.njcn.mapper.configuration.RptDataMapper;
import com.njcn.mapper.configuration.RptPloyMapper;
import com.njcn.pojo.commons.AreaGeneralData;
import com.njcn.pojo.commons.device.ExportDev;
import com.njcn.pojo.configuration.RptData;
import com.njcn.pojo.configuration.RptPloy;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.njcn.utils.ThreeDes;
import com.njcn.utils.UserUtil;
import com.pqs9000.mapper.report.ExcelReportMapper;
import com.pqs9000.pojo.report.PloySetting;
import com.pqs9000.service.report.ExcelReportService;
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.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.*;

@Service
public class ExcelReportServiceImpl implements ExcelReportService {
    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(ExcelReportServiceImpl.class);

    private Map<String, XSSFWorkbook> map = new HashMap();

    @Autowired
    private RptPloyMapper rptPloyMapper;
    @Autowired
    private RptDataMapper rptDataMapper;
    @Autowired
    private ExcelReportMapper excelReportMapper;
    @Autowired
    private UserUtil userUtil;
    @Resource
    private UserLogDetailService userLog;


    @Override
    public List<RptPloy> getPloyData() {
        RptPloy rptPloy = new RptPloy();
        rptPloy.setState(new Integer(1));
        rptPloy.setPloyType(new Integer(2));
        return rptPloyMapper.select(rptPloy);
    }

    @Override
    public List<PloySetting> setPloy(String guid) {
        //获取最后一层选择
        List<RptData> list = excelReportMapper.getDatasByPloy(guid);

        //筛选出parentId
        Set<String> sets = new TreeSet<>();

        for (RptData rptData : list) {
            sets.add(rptData.getParentGUID());
        }

        //筛选的结果获取节点详细信息
        List<RptData> list1 = excelReportMapper.getDatas(sets);

        //转换结果
        List<PloySetting> listPloys = new ArrayList<>();

        for (RptData rptData : list1) {
            PloySetting ploySetting = new PloySetting();
            ploySetting.setName(rptData.getRdDescribe());
            List<Integer> list2 = new ArrayList<>();

            for (RptData rptData1 : list) {
                if (rptData1.getParentGUID().equals(rptData.getRdIndex())) {
                    switch (rptData1.getRdDescribe()) {
                        case "最大值":
                            list2.add(new Integer(1));
                            break;
                        case "最小值":
                            list2.add(new Integer(2));
                            break;
                        case "平均值":
                            list2.add(new Integer(3));
                            break;
                        case "CP95值":
                            list2.add(new Integer(4));
                            break;
                        case "谐波电压含有率":
                            list2.add(new Integer(5));
                            break;
                        case "谐波电流含有率":
                            list2.add(new Integer(6));
                            break;
                        case "电压偏差":
                            list2.add(new Integer(7));
                            break;
                        case "三相电压不平衡度":
                            list2.add(new Integer(8));
                            break;
                        case "电压谐波畸变率":
                            list2.add(new Integer(9));
                            break;
                        case "频率偏差":
                            list2.add(new Integer(10));
                            break;
                        case "电压长时闪变":
                            list2.add(new Integer(11));
                            break;
                    }
                }
            }

            ploySetting.setListTarget(list2);
            listPloys.add(ploySetting);
        }

        return listPloys;
    }

    /**
     * 获取当前用户的所有台账信息
     *
     * @author cdf
     * @date 2021/3/5
     */
    @Override
    public Integer getExportDev(HttpServletResponse response, HttpServletRequest request, String sysType) throws Exception {
        String userIndex = TokenManager.getToken().getUserIndex();

        List<Integer> list = userUtil.listLineByUserId(userIndex);
        if (CollectionUtil.isEmpty(list)) {
            return 0;
        }
        List<ExportDev> ll = excelReportMapper.getExportDev(list, sysType);
        if (CollectionUtil.isEmpty(ll)) {
            return 0;
        }

        // 第一步，创建一个webbook，对应一个Excel文件
        XSSFWorkbook wb = new XSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        XSSFSheet sheet = wb.createSheet("sheet1");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        XSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        XSSFCellStyle style = wb.createCellStyle();

        XSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("批量导入模板（请严格按照模板标准填入数据）");
        cell.setCellStyle(style);

        row = sheet.createRow((int) 1);
        cell = row.createCell((short) 0);
        cell.setCellValue("项目名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("省份");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("所属公司");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("所属部门");
        cell.setCellStyle(style);
        cell = row.createCell((short) 4);
        cell.setCellValue("变电站名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 5);
        cell.setCellValue("变电站电压等级");
        cell.setCellStyle(style);
        cell = row.createCell((short) 6);
        cell.setCellValue("经度");
        cell.setCellStyle(style);
        cell = row.createCell((short) 7);
        cell.setCellValue("纬度");
        cell.setCellStyle(style);
        cell = row.createCell((short) 8);
        cell.setCellValue("装置编号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 9);
        cell.setCellValue("IP地址");
        cell.setCellStyle(style);
        cell = row.createCell((short) 10);
        cell.setCellValue("终端厂家");
        cell.setCellStyle(style);
        cell = row.createCell((short) 11);
        cell.setCellValue("终端模型");
        cell.setCellStyle(style);
        cell = row.createCell((short) 12);
        cell.setCellValue("终端型号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 13);
        cell.setCellValue("所属前置机名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 14);
        cell.setCellValue("端口号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 15);
        cell.setCellValue("识别码");
        cell.setCellStyle(style);
        cell = row.createCell((short) 16);
        cell.setCellValue("秘钥");
        cell.setCellStyle(style);
        cell = row.createCell((short) 17);
        cell.setCellValue("母线名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 18);
        cell.setCellValue("母线号(1-6)");
        cell.setCellStyle(style);
        cell = row.createCell((short) 19);
        cell.setCellValue("电压等级");
        cell.setCellStyle(style);
        cell = row.createCell((short) 20);
        cell.setCellValue("监测点名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 21);
        cell.setCellValue("监测点号(1-6)");
        cell.setCellStyle(style);
        cell = row.createCell((short) 22);
        cell.setCellValue("PT变比");
        cell.setCellStyle(style);
        cell = row.createCell((short) 23);
        cell.setCellValue("CT变比");
        cell.setCellStyle(style);
        cell = row.createCell((short) 24);
        cell.setCellValue("短路容量(默认值10)");
        cell.setCellStyle(style);
        cell = row.createCell((short) 25);
        cell.setCellValue("设备容量(默认值10)");
        cell.setCellStyle(style);
        cell = row.createCell((short) 26);
        cell.setCellValue("协议容量(默认值10)");
        cell.setCellStyle(style);
        cell = row.createCell((short) 27);
        cell.setCellValue("国网ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 28);
        cell.setCellValue("国网ID");
        cell.setCellStyle(style);

        int rowid = 2;

        if (!ll.isEmpty()) {
            for (int i = 0; i < ll.size(); i++) {
                ExportDev rowinfo = ll.get(i);
                row = sheet.createRow(rowid);
                cell = row.createCell((short) 0);
                cell.setCellValue(rowinfo.getProjname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 1);
                cell.setCellValue(rowinfo.getProname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 2);
                cell.setCellValue(rowinfo.getGdname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 3);
                cell.setCellValue(rowinfo.getDeptsname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 4);
                cell.setCellValue(rowinfo.getSubname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 5);
                cell.setCellValue(rowinfo.getSubScale());
                cell.setCellStyle(style);
                cell = row.createCell((short) 6);
                cell.setCellValue(rowinfo.getLongitude());
                cell.setCellStyle(style);
                cell = row.createCell((short) 7);
                cell.setCellValue(rowinfo.getLatitude());
                cell.setCellStyle(style);
                cell = row.createCell((short) 8);
                cell.setCellValue(rowinfo.getDevname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 9);
                cell.setCellValue(rowinfo.getIp());
                cell.setCellStyle(style);
                cell = row.createCell((short) 10);
                cell.setCellValue(rowinfo.getManufacturer());
                cell.setCellStyle(style);
                cell = row.createCell((short) 11);
                cell.setCellValue(rowinfo.getDevmodel());
                cell.setCellStyle(style);
                cell = row.createCell((short) 12);
                cell.setCellValue(rowinfo.getDevtype());
                cell.setCellStyle(style);
                cell = row.createCell((short) 13);
                cell.setCellValue(rowinfo.getNodename());
                cell.setCellStyle(style);
                cell = row.createCell((short) 14);
                cell.setCellValue(rowinfo.getPortid());
                cell.setCellStyle(style);
                cell = row.createCell((short) 15);

                if (rowinfo.getSeries() == null || rowinfo.getSeries() == "") {
                    cell.setCellValue("");
                } else {
                    String seriesTmp = ThreeDes.decryptThreeDes(rowinfo.getSeries());
                    cell.setCellValue(seriesTmp);
                }
                cell.setCellStyle(style);
                cell = row.createCell((short) 16);
                if (rowinfo.getKeym() == null || rowinfo.getKeym() == "") {
                    cell.setCellValue("");
                } else {
                    String keyTmp = ThreeDes.decryptThreeDes(rowinfo.getKeym());
                    cell.setCellValue(keyTmp);
                }
                cell.setCellStyle(style);
                cell = row.createCell((short) 17);
                cell.setCellValue(rowinfo.getSubvname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 18);
                cell.setCellValue(rowinfo.getSubvnum());
                cell.setCellStyle(style);
                cell = row.createCell((short) 19);
                cell.setCellValue(rowinfo.getScale());
                cell.setCellStyle(style);
                cell = row.createCell((short) 20);
                cell.setCellValue(rowinfo.getLinename());
                cell.setCellStyle(style);
                cell = row.createCell((short) 21);
                cell.setCellValue(rowinfo.getLinenum());
                cell.setCellStyle(style);
                cell = row.createCell((short) 22);
                cell.setCellValue(rowinfo.getPt());
                cell.setCellStyle(style);
                cell = row.createCell((short) 23);
                cell.setCellValue(rowinfo.getCt());
                cell.setCellStyle(style);
                cell = row.createCell((short) 24);
                cell.setCellValue(rowinfo.getDlrl());
                cell.setCellStyle(style);
                cell = row.createCell((short) 25);
                cell.setCellValue(rowinfo.getSbrl());
                cell.setCellStyle(style);
                cell = row.createCell((short) 26);
                cell.setCellValue(rowinfo.getXyrl());
                cell.setCellStyle(style);
                cell = row.createCell((short) 27);
                cell.setCellValue(rowinfo.getMonitorid());
                cell.setCellStyle(style);
                rowid++;

            }
        }
        map.put(userIndex, wb);
        return 1;
    }

    /**
     * 获取当前用户的所有台账信息
     *
     * @author cdf
     * @date 2021/3/5
     */
    @Override
    public void getExportDevMain(HttpServletResponse response, HttpServletRequest request) {
        String userIndex = TokenManager.getToken().getUserIndex();
        XSSFWorkbook wb = map.get(userIndex);
        exportExcel(response, request, wb);
        map.remove(userIndex);
    }

    private void exportExcel(HttpServletResponse response, HttpServletRequest request, XSSFWorkbook wb) {
        try {
            response.setContentType("application/force-download");
            String str = "台账导出";
            response.addHeader("Content-Disposition",
                    "attachment;fileName=" + new String(str.getBytes("GB2312"), "iso8859-1") + ".xlsx");// 设置文件名
            OutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            wb.close();
            outputStream.close();
            userLog.getLog("导出台账信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (IOException e) {
            userLog.getLog("导出台账信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            logger.error("台账导出发生了异常，异常是" + e.getMessage());
        }
    }

    @Override
    public void runProc(Integer line ,Date be, Date en){
        excelReportMapper.runProc(line,be,en);
    }
}
