package com.jiayue.ipp.idp.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipp.common.data.entity.PowerStationStatusData;
import com.jiayue.ipp.idp.service.PowerStationStatusDataService;
import com.jiayue.ipp.idp.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * idp_power_station_status_data
 *
 * @author whc
 * @date 2022-03-18 15:49:20
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/powerstationstatusdata")
@Api(value = "powerstationstatusdata", tags = "idp_power_station_status_data管理")
public class PowerStationStatusDataController {

    private final PowerStationStatusDataService powerStationStatusDataService;

    /**
     * 分页查询
     *
     * @param page                   分页对象
     * @param powerStationStatusData idp_power_station_status_data
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    //@PreAuthorize("@pms.hasPermission('idp_forecastpowerdata_get')")
    public R getPowerStationStatusDataPage(Page page, PowerStationStatusData powerStationStatusData) {
        return R.ok(powerStationStatusDataService.page(page, Wrappers.query(powerStationStatusData)));
    }

    /**
     * 通过id查询idp_power_station_status_data
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    //@PreAuthorize("@pms.hasPermission('idp_forecastpowerdata_get')")
    public R getById(@PathVariable("id") String id) {
        return R.ok(powerStationStatusDataService.getById(id));
    }

    @ApiOperation(value = "通过条件查询", notes = "通过条件查询")
    @PostMapping("/getPowerStationStatusData")
    //@PreAuthorize("@pms.hasPermission('idp_forecastpowerdata_get')")
    public R getPowerStationStatusData(String stationCode,
                                       Long startTime,
                                       Long endTime) {
        return R.ok(powerStationStatusDataService.findByStationCodeAndStartTimeAndEndTime(stationCode, new Date(startTime), new Date(endTime)));
    }

    @ApiOperation(value = "通过时间查询时间轴", notes = "通过时间查询时间轴")
    @PostMapping("/getTimeStamp")
    //@PreAuthorize("@pms.hasPermission('idp_forecastpowerdata_get')")
    public R getTimeStamp(
            Long startTime,
            Long endTime) throws ParseException {
        return R.ok(powerStationStatusDataService.timeStamp(new Date(startTime), new Date(endTime)));
    }

    @ApiOperation(value = "通过时间范围查询短期超短期实际功率", notes = "通过时间范围查询短期超短期实际功率")
    @PostMapping("/getCompositeData")
    //@PreAuthorize("@pms.hasPermission('idp_forecastpowerdata_get')")
    public R getCompositeData(
            String stationCode,
            Long startTime,
            Long endTime,
            String forecastManufactor,
            Integer cdqPoint,
            Integer dqPoint) {
        return R.ok(powerStationStatusDataService.getCompositeData(stationCode, new Date(startTime), new Date(endTime), forecastManufactor, cdqPoint,dqPoint));
    }
    @PostMapping("/getCenterData")
    public R getCenterData(
            Long startTime,
            Long endTime) {
        return R.ok(powerStationStatusDataService.getCenterData(new Date(startTime), new Date(endTime)));
    }
    @GetMapping(value = {"/exportDataEvent/{stationCode}/{startTime}/{endTime}/{cdqPoint}/{dqPoint}/{forecastManufactor}","/exportDataEvent/{stationCode}/{startTime}/{endTime}/{cdqPoint}/{dqPoint}" })
    public R exportDataEvent(
            @PathVariable("stationCode") String stationCode,
            @PathVariable("startTime") Long startTime,
            @PathVariable("endTime") Long endTime,
            @PathVariable("cdqPoint") Integer cdqPoint,
            @PathVariable("dqPoint") Integer dqPoint,
            @PathVariable(value = "forecastManufactor",required = false) String forecastManufactor,
            HttpServletResponse response) {


        try {
            Map<String, List> map = powerStationStatusDataService.getCompositeData(stationCode, new Date(startTime), new Date(endTime), forecastManufactor, cdqPoint,dqPoint);

            ExcelWriter writer = ExcelUtil.getWriter(true);
            writer.renameSheet(0, "数据查询对比");
            List<String> header = new ArrayList();
            List<String> headFieldName = new ArrayList();

            List<Map> headerList = map.get("fromHead");
            for (Map headMap:headerList){
                header.add(headMap.get("label").toString());
                headFieldName.add(headMap.get("field").toString());
            }
            List<List<String>> rowHeather = CollUtil.newArrayList();
            rowHeather.add(header);

            List<Map<String,Object>> contentList = map.get("tableList");

            List<List<String>> rowsContent = CollUtil.newArrayList();

            for (Map<String,Object> contentMap : contentList) {
                List<String> rowList = new ArrayList();
                for (String fieldStr:headFieldName){
                    if (contentMap.get(fieldStr)==null){
                        rowList.add("");
                    }
                    else{
                        rowList.add(contentMap.get(fieldStr).toString());
                    }
                }
                rowHeather.add(rowList);
            }

            writer.write(rowHeather, true);
//
//            ExcelWriter monthSheet = writer.setSheet("月");
//
//            List<List<String>> rowsMonth = CollUtil.newArrayList();
//            rowsMonth.add(rowHeather);
//            for (Map<String, BigDecimal> monthList : monthLists) {
//                List<String> rowContent = CollUtil.newArrayList();
//                rowContent.add(monthList.get("time") + "");
//                rowContent.add(monthList.get("capacity") + "");
//                rowContent.add(monthList.get("hourDA") + "");
//                rowContent.add(monthList.get("ultraShortTermAccuracy") + "");
//                rowContent.add(monthList.get("theoreticalPowerGeneration") + "");
//                rowContent.add(monthList.get("actualPowerGeneration") + "");
//                rowContent.add(monthList.get("prValue") + "");
//                rowsMonth.add(rowContent);
//            }
//
//            monthSheet.write(rowsMonth, true);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

            String fileName = "数据对比查询" + simpleDateFormat.format(startTime) + "至" + simpleDateFormat.format(endTime) + ".xlsx";
            response.setContentType("application/x-msdownload;charset=utf-8");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream out = null;
            out = response.getOutputStream();
            writer.flush(out, true);
            // 关闭writer，释放内存
            writer.close();
            //此处记得关闭输出Servlet流
            IoUtil.close(out);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.ok();

    }
}
