package com.jiayue.insu.incloud.pushdata;

import cn.hutool.core.date.DateUtil;
import com.jiayue.insu.incloud.constants.CompanyConstant;
import com.jiayue.insu.incloud.constants.enums.StatusEnum;
import com.jiayue.insu.incloud.entity.IntegrationCompany;
import com.jiayue.insu.incloud.entity.Record;
import com.jiayue.insu.incloud.entity.Station;
import com.jiayue.insu.incloud.service.IntegrationCompanyService;
import com.jiayue.insu.incloud.service.RecordService;
import com.jiayue.insu.incloud.utils.FileUtils;
import com.jiayue.insu.incloud.utils.SFTPUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.VelocityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 将数据推送至sftp
 *
 * @author changchenglong
 * @version 1.0
 * @since 2025/5/27 14:29
 */
@Component
@Slf4j
public class PushDataToSftp implements IPushInitForecastData {
    @Autowired
    private RecordService recordService;
    @Autowired
    private PushCommon pushCommon;
    @Autowired
    private IntegrationCompanyService integrationCompanyService;
    @Autowired
    private FileUtils fileUtils;
    @Autowired
    private SFTPUtil sftpUtil;
    @Value("${localFilePath.drFilePath}")
    String drFilePath;

    /**
     * 推送原始预测数据
     *
     * @param station 场站信息
     * @return 是否成功
     */
    @Override
    public Boolean pushDQAndNWPData(Station station) {
        Boolean dqResult = this.pushDQData(station);
        Boolean nwpResult = this.pushNWPData(station);
        return (dqResult && nwpResult)? true:false ;
    }

    /**
     * 将下载好的原始短期文件通过sftp推送
     *
     * @param station
     * @return
     */
    @Override
    public Boolean pushDQData(Station station) {
        Boolean result = false;
        String stationCode = station.getStationCode();
        String signCode = station.getSignCode();
        String newFilePath = drFilePath + stationCode + File.separatorChar;
        String todayStr = DateUtil.format(DateUtil.date(), "yyyyMMdd");
        String newFileName = "modeloutput-" + signCode + "J001-" + todayStr + "AM.txt";
        String templateName = File.separatorChar + "vms" + File.separatorChar + "DR_DQ.vm";
        result = pushCommon.pushDQData(station, station.getInCode(), newFilePath, newFileName, templateName);
        return result;
    }

    @Override
    public Boolean pushNWPData(Station station) {
        Boolean result = false;
        String stationCode = station.getStationCode();
        String signCode = station.getSignCode();
        String newFilePath = drFilePath + stationCode + File.separatorChar;
        String todayStr = DateUtil.format(DateUtil.date(), "yyyyMMdd");
        String newFileName = "modeloutput-" + signCode + "J001-" + todayStr + "NWP.txt";
        String templateName = File.separatorChar + "vms" + File.separatorChar + "DR_NWP.vm";
        result = pushCommon.pushNWPData(station, station.getInCode(), newFilePath, newFileName, templateName);
        return result;
    }

    /**
     * @param record
     * @param vList
     * @param newFilePath
     * @param newFileName
     * @param templateName
     * @param station
     * @param dateAndFileType
     * @param todayStr
     * @return
     */
    public boolean pushFileToSftp(Record record, List<Map<String, Object>> vList, String newFilePath, String newFileName, String templateName, Station station, String dateAndFileType, String todayStr, String fileDateStr) {

        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("vList", vList);
        velocityContext.put("createTime", DateUtil.format(new Date(), "yyyyMMdd_HH:mm:ss"));
        velocityContext.put("date", fileDateStr);
        velocityContext.put("stationCode", station.getStationCode());
        velocityContext.put("stationName", station.getName());

        File newFile;
        // 生成新文件
        try {
            newFile = fileUtils.createFileByVelocityTemplate(newFilePath, newFileName, templateName, velocityContext);
            if(newFile!=null){
                log.info("生成文件路径：{}",newFile.getAbsolutePath());
            }

        } catch (Exception e) {
            e.printStackTrace();
            record.setState(StatusEnum.CREATE_FILE_FAIL.getSign());
            record.setStateContent(StatusEnum.CREATE_FILE_FAIL.getMsg());
            recordService.save(record);
            return false;
        }
        // 获取公司信息
        IntegrationCompany integrationCompany = integrationCompanyService.findByCode(CompanyConstant.COMPANY_BJZYYJY);
        String sftpInfo = integrationCompany.getPushUrl();
        String[] sftpInfoArr = sftpInfo.split(":");
        // 如果sftp的url配置不对，正确为   用户名:米面:ip:端口号:路径
        if (sftpInfoArr.length < 5) {
            record.setState(StatusEnum.PUSH_URL_ERROR.getSign());
            record.setStateContent(StatusEnum.PUSH_URL_ERROR.getMsg());
            recordService.save(record);
            return false;
        }
        String userName = sftpInfoArr[0];
        String passWord = sftpInfoArr[1];
        String sftpUrl = sftpInfoArr[2];
        // 如果端口为空
        if (sftpInfoArr[3] == null || "".equals(sftpInfoArr[3])) {
            record.setState(StatusEnum.PUSH_URL_ERROR.getSign());
            record.setStateContent(StatusEnum.PUSH_URL_ERROR.getMsg());
            recordService.save(record);
            return false;
        }
        int sftpPort = Integer.valueOf(sftpInfoArr[3]);
        String sftpFilePath = sftpInfoArr[4];
        sftpFilePath = sftpFilePath + File.separatorChar + dateAndFileType;

        log.info("getUsername:" + userName);
        log.info("getPassword:" + passWord);
        log.info("sftpUrl:" + sftpUrl);
        log.info("sftpPort:" + sftpPort);
        log.info("sftpFilePath:" + sftpFilePath);
        log.info("newFileName:" + newFile.getName());
        // 多级目录创建并上传
        sftpUtil.uploadByFileAndPath(userName, passWord, sftpUrl, sftpPort, newFile, sftpFilePath, newFile.getName());
        // 保存日志
        recordService.save(record);
        return true;
    }


}
