package com.huimv.video.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.huimv.video.domain.*;
import com.huimv.video.repo.*;
import com.huimv.video.result.Result;
import com.huimv.video.service.AllDataService;
import com.spire.xls.*;
import com.spire.xls.charts.ChartSerie;
import com.spire.xls.charts.ChartSeries;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;

/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.video.service.impl
 * @Description : TODO
 * @Author : yuxuexuan
 * @Create : 2021/3/31 0031 14:07
 **/
@Service
public class AllDataServiceImpl implements AllDataService {




    @Autowired
    private SjDlRepo dlRepo;

    @Autowired
    private SjSlRepo slRepo;

    @Autowired
    private SjPhRepo phRepo;

    @Autowired
    private SjSyRepo syRepo;


    @Override
    @DS("thired")
    public Result findByZSID(Integer zsid,String lqid) {
        String JQID ;

        switch (zsid){
            case 367:
                JQID = "00000481";
                break;
            case 378:
                JQID = "00000488";
                break;
            default:
                JQID = "00000489";
                break;
        }
        Date date = DateUtil.date();
        DateTime dateTime = DateUtil.beginOfDay(date);
        Map endMap = new HashMap();



        Map dlMap = initMap();
        List<SjDl> allByJQIDAndSCSJBetween = dlRepo.findAllByJQIDAndSCSJBetween(JQID, dateTime, date);
        for (SjDl o : allByJQIDAndSCSJBetween) {
            Integer x = Integer.parseInt((o.getSCSJ()+"").substring(11,13));
            String str ;
            if (x <10){
                str = "0"+x+":00";
            }else {
                str = x+":00";
            }
            dlMap.put(str,o.getDQDL());
        }
        endMap.put("dl",dlMap);


        Map slMap = initMap();
        List<SjSl> allByJQIDAndSCSJBetween1 = slRepo.findAllByJQIDAndSCSJBetween(JQID, dateTime, date);
        for (SjSl o : allByJQIDAndSCSJBetween1) {
            Integer x = Integer.parseInt((o.getSCSJ()+"").substring(11,13));
            String str ;
            if (x <10){
                str = "0"+x+":00";
            }else {
                str = x+":00";
            }
            slMap.put(str,o.getDQSL());
        }
        endMap.put("sl",slMap);

        Map phMap = initMap();
        List<SjPh> allByJQIDAndSCSJBetween2 = phRepo.findAllByJQIDAndSCSJBetween(JQID, dateTime, date);
        for (SjPh o : allByJQIDAndSCSJBetween2) {
            Integer x = Integer.parseInt((o.getSCSJ()+"").substring(11,13));
            String str ;
            if (x <10){
                str = "0"+x+":00";
            }else {
                str = x+":00";
            }
            phMap.put(str,o.getDQPH());
        }
        endMap.put("ph",phMap);


        Map syMap = initMap();
        List<SjSy> allByJQIDAndSCSJBetween3 = syRepo.findAllByJQIDAndSCSJBetween(JQID, dateTime, date);
        for (SjSy o : allByJQIDAndSCSJBetween3) {
            Integer x = Integer.parseInt((o.getSCSJ()+"").substring(11,13));
            String str ;
            if (x <10){
                str = "0"+x+":00";
            }else {
                str = x+":00";
            }
            syMap.put(str,o.getDQSY());
        }
        endMap.put("sy",syMap);
        endMap.put("zsid",zsid);
        endMap.put("lqid",lqid);


        return new Result(10000,"成功",endMap);
    }

    @Override
    @DS("thired")
    public String findAll(String startTime, String  endTime, HttpServletResponse response) {
        //367  一栋全控   00000481
        //378   二栋      00000488
        //379   三栋      00000489
        Date startDate =  DateUtil.parse(startTime);
        Date endDate =  DateUtil.parse(endTime);

        Double sl1result = 0.0;
        List<SjSl> slList1 = slRepo.findAllByJQIDAndSCSJBetween("00000481", startDate, endDate);
        if (slList1  != null && slList1.size()>0){
            sl1result = slList1.get(slList1.size() - 1).getDQSL().subtract(slList1.get(0).getDQSL()).doubleValue();
        }

        Double dl1result = 0.0;
        List<SjDl> dlList1 = dlRepo.findAllByJQIDAndSCSJBetween("00000481", startDate, endDate);
        if (dlList1  != null &&dlList1.size()>0){
            dl1result = dlList1.get(dlList1.size() - 1).getDQDL().subtract(dlList1.get(0).getDQDL()).doubleValue();
        }



        Double sl2result = 0.0;
        List<SjSl> slList2 = slRepo.findAllByJQIDAndSCSJBetween("00000488", startDate, endDate);
        if (slList2  != null &&slList2.size()>0){
            sl2result = slList2.get(slList2.size() - 1).getDQSL().subtract(slList2.get(0).getDQSL()).doubleValue();
        }

        Double dl2result = 0.0;
        List<SjDl> dlList2 = dlRepo.findAllByJQIDAndSCSJBetween("00000488", startDate, endDate);
        if (dlList2  != null &&dlList2.size() >0 ){
            dl2result = dlList2.get(dlList2.size() - 1).getDQDL().subtract(dlList2.get(0).getDQDL()).doubleValue();
        }


        Double sl3result = 0.0;
        List<SjSl> slList3 = slRepo.findAllByJQIDAndSCSJBetween("00000489", startDate, endDate);
        if (slList3  != null &&slList3.size()>0){
            sl3result= slList3.get(slList3.size() - 1).getDQSL().subtract(slList3.get(0).getDQSL()).doubleValue();
        }

        Double dl3result = 0.0;
        List<SjDl> dlList3 = dlRepo.findAllByJQIDAndSCSJBetween("00000489", startDate, endDate);
        if (dlList3  != null &&dlList3.size()>0){
             dl3result = dlList3.get(dlList3.size() - 1).getDQDL().subtract(dlList3.get(0).getDQDL()).doubleValue();
        }

//        //创建Excel文档
//        Workbook workbook = new Workbook();
//        //获取第一个工作表
//        Worksheet sheet = workbook.getWorksheets().get(0);
//        //设置工作表名称
//        sheet.setName("用水量用电量统计表");
//
//        //向工作表添加数据
//        sheet.getRange().get("A1").setValue("栋舍");
//        sheet.getRange().get("A2").setValue("1栋");
//        sheet.getRange().get("A3").setValue("2栋");
//        sheet.getRange().get("A4").setValue("3栋");
//
//        sheet.getRange().get("B1").setValue("用水量(吨)");
//        sheet.getRange().get("B2").setNumberValue(sl1result);
//        sheet.getRange().get("B3").setNumberValue(sl2result);
//        sheet.getRange().get("B4").setNumberValue(sl3result);
//
//        sheet.getRange().get("C1").setValue("用电量(kw/h)");
//        sheet.getRange().get("C2").setNumberValue(dl1result);
//        sheet.getRange().get("C3").setNumberValue(dl2result);
//        sheet.getRange().get("C4").setNumberValue(dl3result);
//
//        //添加图表到工作表
//        Chart chart = sheet.getCharts().add(ExcelChartType.Column3DClustered);
//        chart.setDataRange(sheet.getRange().get("B1:C4"));
//        chart.setSeriesDataFromRange(false);
//        chart.setTopRow(7);
//        chart.setBottomRow(28);
//        chart.setLeftColumn(3);
//        chart.setRightColumn(11);
//        chart.setChartTitle(startTime.substring(5,10)+ " 到 " + endTime.substring(5,10) + " 水电统计图");
//        chart.getChartTitleArea().isBold(true);
//        chart.getChartTitleArea().setSize(12);
//        ChartSerie cs1 = chart.getSeries().get(0);
//        cs1.setCategoryLabels(sheet.getRange().get("A2:A4"));
//        ChartSeries series = chart.getSeries();
//        for (int i = 0; i < series.size() ; i++) {
//            ChartSerie cs = series.get(i);
//            cs.getDataPoints().getDefaultDataPoint().getDataLabels().hasValue(true);
//        }
//        //添加数据表到图表
//        chart.hasDataTable(true);

        Workbook workbook = new Workbook();

        //获取第一个工作表
        Worksheet sheet = workbook.getWorksheets().get(0);

        //将图表数据写入工作表
        sheet.getCellRange("A1").setValue("栋舍");
        sheet.setColumnWidth(1,8);
        sheet.getCellRange("A2").setValue("1栋");
        sheet.getCellRange("A3").setValue("2栋");
        sheet.getCellRange("A4").setValue("3栋");
        sheet.getCellRange("B1").setValue("用水量(吨)");
        sheet.setColumnWidth(2,13);
        sheet.getCellRange("B2").setNumberValue(sl1result);
        System.out.println(sl1result);
        sheet.getCellRange("B3").setNumberValue(sl2result);
        System.out.println(sl2result);
        sheet.getCellRange("B4").setNumberValue(sl3result);
        System.out.println(sl3result);

        sheet.getCellRange("C1").setValue("用电量(kw/h)");
        sheet.setColumnWidth(3,13);
        sheet.getCellRange("C2").setNumberValue(dl1result);
        System.out.println(dl1result);
        sheet.getCellRange("C3").setNumberValue(dl2result);
        System.out.println(dl2result);
        sheet.getCellRange("C4").setNumberValue(dl3result);
        System.out.println(dl3result);

        //设置单元格样式
        sheet.getCellRange("A1:C4").setRowHeight(18);
        sheet.getCellRange("A1:C1").getCellStyle().setColor(Color.darkGray);
        sheet.getCellRange("A1:C1").getCellStyle().getExcelFont().setColor(Color.white);
        sheet.getCellRange("A1:C4").getCellStyle().setVerticalAlignment(VerticalAlignType.Center);
        sheet.getCellRange("A1:C4").getCellStyle().setHorizontalAlignment(HorizontalAlignType.Center);
//        sheet.autoFitColumn(1);

        //添加柱形图
        Chart chart =sheet.getCharts().add(ExcelChartType.ColumnClustered);

        //设置图表数据区域
        chart.setDataRange(sheet.getCellRange("A1:C4"));
        chart.setSeriesDataFromRange(false);
        //设置图表位置
        chart.setLeftColumn(5);
        chart.setTopRow(1);
        chart.setRightColumn(14);
        chart.setBottomRow(21);

        //设置图表标题
        chart.setChartTitle(startTime.substring(0,10)+ " 到 " + endTime.substring(0,10) + " 水电量统计");
        chart.getChartTitleArea().isBold(true);
        chart.getChartTitleArea().setSize(12);

        //设置x,y轴的名称
        chart.getPrimaryCategoryAxis().setTitle("栋舍");
        chart.getPrimaryCategoryAxis().getFont().isBold(true);
        chart.getPrimaryCategoryAxis().getTitleArea().isBold(true);
        chart.getPrimaryValueAxis().setTitle("数值");
        chart.getPrimaryValueAxis().hasMajorGridLines(false);
        chart.getPrimaryValueAxis().getTitleArea().isBold(true);
        chart.getPrimaryValueAxis().getTitleArea().setTextRotationAngle(90);

        //设置系列颜色、重叠、宽度和数字标签
        ChartSeries series = chart.getSeries();
        series.get(0).getDataPoints().getDefaultDataPoint().getDataLabels().hasValue(true);
        System.out.println(series.size());
        for (int i = 0 ; i < series.size() ; i++) {
            ChartSerie cs = series.get(i);
//            cs.getFormat().getOptions().isVaryColor(true);
            cs.getFormat().getOptions().setOverlap(-50);
            cs.getFormat().getOptions().setGapWidth(350);
            cs.getDataPoints().getDefaultDataPoint().getDataLabels().hasValue(true);
        }

        //设置图例位置
        chart.getLegend().setPosition(LegendPositionType.Top);


        String fileName = System.currentTimeMillis()+".xls";
        response.setContentType("application/vnd.ms-excel");  //"application/vnd.ms-excel;charset=utf-8"  application/force-download
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        ServletOutputStream outputStream = null;
        // try {
        try {
            response.addHeader("Content-Disposition","attachment;fileName=" + new String(fileName.getBytes("UTF-8"),"iso-8859-1"));

             outputStream = response.getOutputStream();

            workbook.saveToStream(outputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }
        return "200";
    }

    private Map initMap (){
        Map map = new TreeMap<String ,Object>(new Comparator<String>() {
            @Override
            public int compare(String s, String t1) {
                return s.compareTo(t1);
            }
        });
        for (int i = 0; i< 24 ;i++){
            String x ;
            if (i <10){
                x = "0"+i;
            }else {
                x =i+"";
            }
            map.put(x+":00",0);
        }
        return map;
    }
}
