package com.jiayue.ipp.idp.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiayue.ipfcst.common.core.util.DateMomentUtil;
import com.jiayue.ipp.common.data.entity.DqIntervene;
import com.jiayue.ipp.common.data.entity.ForecastPowerShortTerm;
import com.jiayue.ipp.common.data.entity.an.ParsingChannel;
import com.jiayue.ipp.common.data.entity.an.ParsingUrl;
import com.jiayue.ipp.idp.dto.DqInterveneDto;
import com.jiayue.ipp.idp.dto.DqTempDto;
import com.jiayue.ipp.idp.dto.ForecastData;
import com.jiayue.ipp.idp.service.DqInterveneService;
import com.jiayue.ipp.idp.service.an.ParsingChannelService;
import com.jiayue.ipp.idp.service.an.ParsingUrlService;
import com.jiayue.ipp.idp.util.FileUtil;
import com.jiayue.ipp.idp.util.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 短期干预
 */
@RestController
@RequestMapping("/dqInterveneController")
@Slf4j
public class DqInterveneController {
    @Autowired
    DqInterveneService dqInterveneService;
    @Autowired
    ParsingChannelService parsingChannelService;
    @Autowired
    VelocityEngine velocityEngine;
    @Autowired
    ParsingUrlService parsingUrlService;

    /**
     * 获取短期干预
     */
    @GetMapping(value = "/getShort")
    public R getPresetsShort(Long startTime, Long endTime,String stationCode) {
        List<DqInterveneDto> presetsShortDtoList = dqInterveneService.getShort(startTime, endTime,stationCode);
        return R.ok(presetsShortDtoList);

    }

    /**
     * 获取短期干预
     */
    @PostMapping(value = "/saveIntervene")
    public R savePresets(@RequestBody DqTempDto dqTempDto) {
        String stationCode = dqTempDto.getStationCode();
        List<DqInterveneDto> list = dqTempDto.getList();
        // 先删除干预表的数据记录
        list.sort(Comparator.comparing(DqInterveneDto::getForecastTime));
        // 干预日期
        String gyrq = DateFormatUtils.format(list.get(0).getForecastTime(), "yyyyMMdd");
        Date startTime = list.get(0).getForecastTime();
        Date endTime = list.get(list.size() - 1).getForecastTime();
        dqInterveneService.deleteShort(startTime, endTime,stationCode);
        // 封装干预实体，保存数据
        List<DqIntervene> presetsShortList = new ArrayList<>();
        for (DqInterveneDto dqInterveneDto : list) {
            if (dqInterveneDto.getPresetsPower() != null) {
                DqIntervene dqIntervene = new DqIntervene();
                dqIntervene.setForecastTime(dqInterveneDto.getForecastTime());
                dqIntervene.setActivePower(dqInterveneDto.getPresetsPower());
                dqIntervene.setStationCode(stationCode);
                presetsShortList.add(dqIntervene);
            }
        }
        dqInterveneService.saveBatch(presetsShortList);
        // 下发短期干预
        log.info(stationCode+"下发嘉越DQ数据开始："+gyrq);

        LambdaQueryWrapper<ParsingUrl> urlWrapper = new LambdaQueryWrapper<>();
        urlWrapper.eq(ParsingUrl::getUrlStatus, "1");
        urlWrapper.eq(ParsingUrl::getStationCode, stationCode);
        List<ParsingUrl> parsingUrlList = parsingUrlService.list(urlWrapper);
        if (parsingUrlList.size()>0){
            // 获取ftp通道
            LambdaQueryWrapper<ParsingChannel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ParsingChannel::getAnChannelType, "E1");
            lambdaQueryWrapper.eq(ParsingChannel::getUseStatus, "E1");
            lambdaQueryWrapper.eq(ParsingChannel::getId, parsingUrlList.get(0).getCId());
            ParsingChannel parsingChannel = parsingChannelService.getOne(lambdaQueryWrapper);

            String distPath = "/home"+ File.separator+parsingChannel.getUsername()+File.separator+"download";
            File dirFile = new File(distPath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            VelocityContext velocityContext = new VelocityContext();
            List<ForecastData> vList = new ArrayList<>();

            for (DqIntervene d1:presetsShortList) {
                ForecastData forecastData = new ForecastData();
                forecastData.setTime(DateFormatUtils.format(d1.getForecastTime(), "yyyy-MM-dd HH:mm:ss"));
                forecastData.setPower(d1.getActivePower().toString());
                vList.add(forecastData);
            }

            velocityContext.put("vList", vList);
            // 系统当前日期
            velocityContext.put("currentTime", DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            StringWriter writer = new StringWriter();
            org.apache.velocity.Template template = this.velocityEngine.getTemplate(FileUtil.getResourceBasePath() + "/templates/send_dq.vm");
            template.merge(velocityContext, writer);

            String vmFileName = "send_"+stationCode+"_dq_"+gyrq+".WPD";
            createSendDqFile(writer,new File(distPath + File.separator+vmFileName));
            log.info(stationCode+"下发嘉越DQ数据成功："+gyrq);
        }
        return R.ok();

    }
    /**
     * 生成上报文件
     *
     * @param writer
     * @param file
     */
    protected void createSendDqFile(StringWriter writer, File file) {
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            // 采用UTF-8字符集
            os.write(writer.toString().getBytes("UTF-8"));
            os.flush();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    log.error("文件生成关闭流失败", e);
                }
            }
        }
    }
}
