package com.jiayue.ipp.idp.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.jiayue.ipp.common.data.entity.ElectricField;
import com.jiayue.ipp.common.data.entity.PowerStationStatusData;
import com.jiayue.ipp.idp.util.DateTimeUtil;
import com.jiayue.ipp.idp.util.GzipUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 生成回传数据
 *
 * @Author: tl
 * @Date: 2023/6/29 9:47
 */
@Service
@Slf4j
public class GenerateBackPassDataService {

    @Autowired
    private PowerStationStatusDataService powerStationStatusDataService;


    @Autowired
    private SysParameterService sysParameterService;

    @Autowired
    private ElectricFieldService electricFieldService;


    /**
     * 生成实际功率json文件
     */
    @Scheduled(cron = "0 48 1 * * ?")
    public void genRealPowerDataJsonFile()  {

        long time = System.currentTimeMillis() - 86400000l;

        Date startTime = DateTimeUtil.getDayStartTime(time);

        Date endTime = DateTimeUtil.getDayLastTime(time);


        for (ElectricField electricField : electricFieldService.list()) {

            String zxglPath = sysParameterService.getSysParameterAndStationCode("zxgl_config", "", electricField.getStationCode());

            if (!zxglPath.equals("")) {
                FileOutputStream fileOutputStream = null;
                try {
                    log.info("开始生成【{}】实际功率json文件",electricField.getStationCode());
                    List<PowerStationStatusData> list = powerStationStatusDataService.findByStationCodeAndStartTimeAndEndTime(electricField.getStationCode(), startTime, endTime);
                    String content = electricField.getStationCode() + "|" + startTime.getTime() + "|rp|";
                    //为了确保无数据缺失，遍历时间
                    long sTimeL = startTime.getTime();
                    long eTimeL = endTime.getTime();
                    for (long i = sTimeL; i < eTimeL; i += 900000l) {

                        long finalI = i;
                        List<PowerStationStatusData> filterList = list.stream().filter(p -> Timestamp.valueOf(p.getTime()).getTime() == finalI).collect(Collectors.toList());

                        if (filterList != null && filterList.size() > 0) {
                            content = content + filterList.get(0).getRealValue().setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "|";
                        } else {
                            content = content + "-0.99|";
                        }

                    }


                    for (int i = 0; i < 96; i++) {
                        content = content + "-0.99|";
                    }
                    String zipContent = GzipUtil.zip(content).replace("\r\n", "");

                    String taskNo = getTaskNo(electricField);

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.putOnce("taskNo", taskNo);
                    jsonObject.putOnce("taskType", "stationData-rp");
                    jsonObject.putOnce("partNo", 1);
                    jsonObject.putOnce("partTotal", 1);
                    jsonObject.putOnce("data", zipContent);

                    String qrCodeContent = jsonObject.toString();

                    String fileName = electricField.getStationCode() + "-" + DateFormatUtils.format(new Date(), "yyyyMMddHHmm") + "-realpower.json";

                    File file = new File(zxglPath + File.separator + fileName);

                    fileOutputStream = new FileOutputStream(file);
                    fileOutputStream.write(qrCodeContent.getBytes(Charset.forName("utf-8")));
                    fileOutputStream.flush();
                    fileOutputStream.close();

                    log.info("实际功率json文件【{}】生成成功",fileName);
                }catch (IOException e){
                 e.printStackTrace();
                }

            }
        }


    }

//    public void realPowerForQr(String zxglPath) {
//
//        File file = new File(zxglPath);
//
//        if (file.exists()) {
//
//            for (String s : file.list()) {
//
//                List<String> list;
//                try {
//                    list = FileUtil.getFileContent(new File(zxglPath + File.separator + s));
//                    TaskResultRequestVO taskResultRequestVO = new TaskResultRequestVO();
//
//                    taskResultRequestVO.setTaskResult(list.get(0));
//                    String url = "https://api.jiayuepowertech.com:8080/task/result";
//                    // 构造请求对象
//                    HttpRequest request = HttpRequest.put(url).body(JsonBeanUtil.beanToJson(taskResultRequestVO));
//
//                    // 发送请求并获取响应对象
//                    HttpResponse response = request.execute();
//
//                    log.info("回传实际功率状态=》", response.body());
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }

    /**
     * 获取taskNo编号
     *
     * @param electricField 场站对象
     * @return 编号
     */
    private String getTaskNo(ElectricField electricField) {
        Date date = DateUtil.date();
        return electricField.getStationCode() + DateUtil.format(date, "yyMMddHHmmss");
    }


//    @Data
//    class TaskResultRequestVO {
//        private static final long serialVersionUID = 1L;
//        private String taskResult;
//    }
}
