package com.xhpc.evcs.notification;

import com.xhpc.evcs.domain.AuthSecretToken;
import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.dto.DTOJsonHelper;
import com.xhpc.evcs.dto.NotificationStartChargeResultRequestData;
import com.xhpc.evcs.dto.NotificationStartStopChargeResultResponse;
import com.xhpc.evcs.encryption.Aes128Cbc;
import com.xhpc.evcs.jpa.AuthSecretTokenRepository;
import com.xhpc.evcs.utils.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.evcs.domain.AuthSecretToken.SECRET_TOKEN_TYPE_OUT;


@Component
public class NotificationStartChargeResultTask extends CoreDispatcher {

    @Autowired
    private AuthSecretTokenRepository authSecretTokenRepository;

    private final Logger logger = LoggerFactory.getLogger(NotificationStartChargeResultTask.class);

    /**
     * Judging the 3rd whether it has got the start charging task.
     */
    //(evcs 放开 30 秒， 测试平台开放 15秒)
    //都开放
    @Scheduled(cron = "0/30 * * * * ? ")
    public void run() throws IOException {

        //Getting the charge orders which from 3rd.
        Collection<String> pushOrderKeys = REDIS.keys("pushOrder:*");
        for (String pushOrderKey : pushOrderKeys) {
            Map<String, Object> pushOrder = REDIS.getCacheMap(pushOrderKey);
            if (pushOrder.get("startChargeSeqStat") != null && (Integer) pushOrder.get("startChargeSeqStat") > 1) {
                if(pushOrder.get("operatorId3rdptyName") !=null && "CYC".equals((String)pushOrder.get("operatorId3rdptyName"))){
                    continue;
                }
                Integer startChargeNotificationStat = (Integer) pushOrder.get("startChargeNotificationStat");
                if (null != startChargeNotificationStat && 1 != startChargeNotificationStat && startChargeNotificationStat <= 20) {
                    if(pushOrder.get("internetSerialNumber")==null || "".equals((String) pushOrder.get("internetSerialNumber"))){
                        continue;
                    }
                    String startChargeSeq = (String) pushOrder.get("internetSerialNumber");
                    String operatorId = startChargeSeq.substring(0, 9);
                    Optional<AuthSecretToken> authSecretToken =authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId,SECRET_TOKEN_TYPE_OUT);
                    if (authSecretToken.isPresent()) {
                        NotificationStartChargeResultRequestData notificationStartChargeResultRequestData =
                                new NotificationStartChargeResultRequestData();
                        notificationStartChargeResultRequestData.setStartTime((String) pushOrder.get("startTime"));
                        notificationStartChargeResultRequestData.setStartChargeSeq(startChargeSeq);
                        notificationStartChargeResultRequestData.setConnectorId((String) pushOrder.get("connectorID"));
                        if("765367656".equals(operatorId)){
                            Integer startChargeSeqStat = (Integer) pushOrder.get("startChargeSeqStat");
                            if(startChargeSeqStat !=1){
                                notificationStartChargeResultRequestData.setFailReasonMsg("平台停止");
                            }
                        }
                        notificationStartChargeResultRequestData.setStartChargeSeqStat((Integer) pushOrder.get(
                                "startChargeSeqStat"));
                        notify(notificationStartChargeResultRequestData, authSecretToken.get(), pushOrderKey.substring(10),startChargeSeq);
                    }
                }
            }
        }
    }

    //Notifying others platform.
    public void notify(NotificationStartChargeResultRequestData notificationStartChargeResultRequestData,
                       AuthSecretToken authSecretTokenOut, String orderNo,String startChargeSeq) throws IOException {

        String operatorIdEvcs = "MA6DFCTD5";
        String data = JSONUtil.toJSONString(notificationStartChargeResultRequestData);

        CommonRequest<NotificationStartChargeResultRequestData> commonRequest = new CommonRequest<>();
        commonRequest.setData(data);
        String responseBody = ok(commonRequest, "/notification_start_charge_result", authSecretTokenOut);
        NotificationStartStopChargeResultResponse notificationStartStopChargeResultResponse =DTOJsonHelper.parseResponseData(responseBody,NotificationStartStopChargeResultResponse.class, authSecretTokenOut);

        if (null != notificationStartStopChargeResultResponse) {
            //Ensuring that only when startChargeNotificationStat equals 1 won't be notified.
            if(!"".equals(startChargeSeq)&& startChargeSeq !=null && "MA7D6FPW6".equals(startChargeSeq.substring(0, 9))){
                REDIS.setCacheMapValue("pushOrder:".concat(orderNo), "startChargeNotificationStat", 1);
            }else{
                if (notificationStartStopChargeResultResponse.getSuccStat() == 0) {
                    REDIS.setCacheMapValue("pushOrder:".concat(orderNo), "startChargeNotificationStat", 1);
                } else {
                    Integer startChargeNotificationStat = REDIS.getCacheMapValue("pushOrder:".concat(orderNo),
                            "startChargeNotificationStat");
                    if (startChargeNotificationStat == 0) {
                        startChargeNotificationStat = 2;
                    } else {
                        ++startChargeNotificationStat;
                    }
                    REDIS.setCacheMapValue("pushOrder:".concat(orderNo), "startChargeNotificationStat",startChargeNotificationStat);
                    throw new RuntimeException(String.format("push CD start charge order status [%s] failed: %s",notificationStartChargeResultRequestData.getStartChargeSeq(), responseBody));
                }
            }


        }
    }


    public static void main(String[] args) {
        try{
            String data ="tHZ+rscY6M5g77k0+NtJD+IG5Wkt30jd+IshU7P4y0DIe6m3rwmTibfudkSYF05Dco39z0eRnf6oRQwcC4Uh+oNljQF/cZz2owzPFmaMrKY=";

            String s = Aes128Cbc.decryptString(data, "4d593ae4f74f2798", "0802395fab41d38c");

        }catch (Exception e){

        }

    }
}
