package com.cpp.web.controller.stationDataQuery;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
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.cpp.common.core.domain.R;
import com.cpp.system.service.ISysConfigService;
import com.cpp.web.domain.station.ElectricField;
import com.cpp.web.dto.DqHistoryContrastDto;
import com.cpp.web.dto.TableColumn;
import com.cpp.web.service.station.ElectricFieldService;
import com.cpp.web.service.station.PowerStationStatusDataService;
import com.cpp.web.service.station.impl.PowerStationStatusDataServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.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
@Slf4j
@RequestMapping("/powerstationstatusdata")
@Api(value = "powerstationstatusdata", tags = "idp_power_station_status_data管理")
public class PowerStationStatusDataController {
    @Autowired
    private ISysConfigService configService;

    private final PowerStationStatusDataService powerStationStatusDataService;

    private final ElectricFieldService electricFieldService;
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @ApiOperation(value = "通过条件查询", notes = "通过条件查询")
    @GetMapping("/queryDays")
    public R queryDays() {
        String queryDays = configService.selectConfigByKey("require_dq_day");
        if (StrUtil.isBlankIfStr(queryDays)){
            queryDays = "10";
        }
        return R.ok(queryDays);
    }

    @ApiOperation(value = "通过条件查询", notes = "通过条件查询")
    @GetMapping("/getCompositeData")
    public R getCompositeData(String stationCode,
                                       Long startTime,
                                       Long endTime) {
        return R.ok(powerStationStatusDataService.getCompositeData(stationCode, startTime, endTime));
    }


    @ApiOperation(value = "中心测数据查询", notes = "中心测数据查询")
    @GetMapping("/cloudDataQuery")
    public R cloudDataQuery(Long startTime,
                              Long endTime,
                              Integer forecastHowLongAgo,
                              String stationCode) {
        return R.ok(powerStationStatusDataService.cloudDataQuery(new Date(startTime), new Date(endTime), forecastHowLongAgo, stationCode));
    }

    @GetMapping("/export")
    public void export(Long startTime, Long endTime, Integer forecastHowLongAgo, String stationCode,HttpServletResponse response){

        ElectricField electricField = electricFieldService.findByStationCode(stationCode);

        BufferedOutputStream bos = null;
        Map<String,Object> map = new HashMap();
        try {

            StringBuilder templateContent = new StringBuilder();
            response.setCharacterEncoding("UTF-8");
            map = (Map) cloudDataQuery(startTime, endTime, forecastHowLongAgo,stationCode).getData();
            List<Map<String,Object>> tableList = (List<Map<String,Object>>) map.get("tableData");

            List<TableColumn> tableColumns = (List<TableColumn>) map.get("tableField");

            String header = "";
            StringBuilder content = new StringBuilder();

            for (TableColumn tableColumn : tableColumns) {
                header += "\"" + tableColumn.getTitle() + "\",";
            }
            for (Map<String, Object> tableData : tableList) {
                for (TableColumn tableColumn : tableColumns) {
                    content.append(tableData.get(tableColumn.getField()) + "," );
                }
                content.append("\r\n");
            }


            header += "\r\n";
            templateContent.append(header);

            templateContent.append(content.toString());

            String fileName = "";
            if (sdf.format(startTime).equals(sdf.format(endTime))) {
                fileName = electricField.getName() + sdf.format(startTime) + "中心功率预测" + ".csv";
            } else {
                fileName = electricField.getName() + sdf.format(startTime) + "至" + sdf.format(endTime) + "中心功率预测" + ".csv";
            }

            response.setContentType("application/x-msdownload;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] templateContentBytes = templateContent.toString().getBytes("UTF-8");
            bos = new BufferedOutputStream(response.getOutputStream());
            bos.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            bos.write(templateContentBytes);
            response.flushBuffer();

        } catch (Exception e) {
            log.error("系统错误：" + e.getMessage(), e);
            throw new RuntimeException(e);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    log.error("系统错误：" + e.getMessage(), e);
                }
            }
        }
    }
}
