package com.iailab.module.shasteel.job.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iailab.framework.common.util.http.HttpUtils;
import com.iailab.module.model.api.mcs.McsApi;
import com.iailab.module.model.api.mcs.dto.ElectricityPriceSegmentedDTO;
import com.iailab.module.shasteel.job.vo.RequestAccessTokenVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 同步分段数据定时任务
 * @author Jay
 */
@Component("syncSegmentedDataTask")
public class SyncSegmentedDataTask implements ITask {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private McsApi mcsApi;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final String PUBLIC_KEY_URL = "http://10.88.7.107:8081/api/api/services/Runtime/Authentication/GetLoginRSAPublicKeyAsync";

    private static final String ACCESS_TOKEN_URL = "http://10.88.7.107:8081/EP.Web/account/ajaxLogin";

    private static final String QUERY_SEGMENTED_DATA_URL = "http://10.88.7.107:8081/SG.Web/api/services/nYJK/DiagnosticsSg/QuerySegmentedDataAsync";

    private static final String USERNAME = "Mx001@sgis";

    private static final String PASSWORD = "123456";

    @Override
    public void run(String params) {
        logger.info("syncSegmentedDataTask定时任务正在执行,参数为:{}", params);
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            //获取 公钥
            String publicKeyKey = getPublicKey();
            // 组合密码
            Instant instant = Instant.now(); // 获取当前时间的UTC时间
            ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of("Z"));
            DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
            String isoString = zonedDateTime.format(formatter);
            String password = isoString + "|" + PASSWORD;
            RequestAccessTokenVO requestAccessToken = new RequestAccessTokenVO();
            requestAccessToken.setUserName(USERNAME);
            // 使用公钥和组合后的密码进行密码加密
            String realPassword = encryptWithPublicKey(publicKeyKey, password);
            logger.info("公钥和组合后的密码进行密码加密:" + realPassword);
            requestAccessToken.setPassword(realPassword);
            requestAccessToken.setSource(1);
            //获取 token
            String accessToken = "Bearer " + getAccessToken(requestAccessToken);
            //获取保存后的数据
            List<ElectricityPriceSegmentedDTO> list = getElectricityPriceSegmentedList(accessToken);
            logger.info("开始保存数据:" + JSON.toJSONString(list));
            mcsApi.createElectricityPrice(list);
            logger.info("保存数据完成");
        } catch (Exception ex) {
            logger.error("syncSegmentedDataTask运行异常:" + ex.getMessage());
            ex.printStackTrace();
        }
        logger.info("syncSegmentedDataTask运行完成");
    }

    public String getPublicKey() {
        String publicKeyString = "";
        String resp =  HttpUtils.sendGet(PUBLIC_KEY_URL,null,"");
        logger.info("获取公钥的返回值:" + resp);
        JSONObject jsonObject = JSON.parseObject(resp);
        if (jsonObject.get("status").equals(200)) {
            publicKeyString = jsonObject.getJSONObject("data").getString("pemPublicKey");
        }
        return publicKeyString.replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s", "");
    }

    public String getAccessToken(RequestAccessTokenVO requestAccessToken) {
        String accessToken = "";
        logger.info("请求参数:" + JSON.toJSONString(requestAccessToken));
        String resp = HttpUtils.sendPost(ACCESS_TOKEN_URL, JSON.toJSONString(requestAccessToken));
        logger.info("获取token的返回值:" + resp);
        JSONObject jsonObject = JSON.parseObject(resp);
        if (jsonObject.get("status").equals(200)) {
            String token = jsonObject.getJSONObject("data").getString("token");
            JSONObject tokenObject = JSON.parseObject(token);
            accessToken = tokenObject.getString("accessToken");
            logger.info("获取到accessToken:" + accessToken);
        }
        return accessToken;
    }

    public List<ElectricityPriceSegmentedDTO> getElectricityPriceSegmentedList(String accessToken){
        logger.info("accessToken: " + accessToken);
        Map<String, String> paramsMap = new HashMap<>();
        LocalDate date = LocalDate.now();  // 获取当前日期的LocalDate实例
        String year = String.valueOf(date.getYear());
        paramsMap.put("clock", year);
        logger.info("请求参数:" + JSON.toJSONString(paramsMap));
        String resp = HttpUtils.sendPost(QUERY_SEGMENTED_DATA_URL, JSON.toJSONString(paramsMap), accessToken);
        logger.info("获取分段数据的返回值:" + resp);
        JSONObject jsonObject = JSON.parseObject(resp);
        List<ElectricityPriceSegmentedDTO> list = jsonObject.getJSONArray("data").toJavaList(ElectricityPriceSegmentedDTO.class);
        list.forEach(item -> item.setYear(year));
        return list;
    }

    public static String encryptWithPublicKey(String publicKeyString, String data) throws Exception {
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyString)));
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
    }
}