package com.xhpc.evcs.notification;

import com.xhpc.common.data.redis.CacheOrderData;
import com.xhpc.evcs.domain.AuthSecretToken;
import com.xhpc.evcs.dto.ChargeResultRequest;
import com.xhpc.evcs.dto.ChargeResultResponse;
import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.dto.DTOJsonHelper;
import com.xhpc.evcs.jpa.AuthSecretTokenRepository;
import com.xhpc.evcs.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;

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

@Slf4j
@Component
public class NotificationStopChargeResultTask extends CoreDispatcher {

    @Autowired
    private AuthSecretTokenRepository authSecretTokenRepository;

    //(evcs 放开)
    //都开放
    @Scheduled(cron = "0/30 * * * * ? ")
    public void run() throws Exception {

        notifyService();
    }

    /**
     * 获取充电订单号
     * 获取充电订单状态
     * 获取充电设备接口编码
     * 获取成功标识
     * 获取停止失败原因
     * 推送过去
     * <p>
     * 出现异常逻辑
     * 如果当充电桩因为异常停止充电时，那么谁告诉我订单是个异常订单？
     */
    public void notifyService() throws Exception {

        //获取Redis中的所有订单状态数据
        Collection<String> pushOrders = REDIS.keys("pushOrder:*");

        for (String pushOrderKey : pushOrders) {
            String orderNo = pushOrderKey.substring(10);
            String orderkey = "order:".concat(orderNo);
            CacheOrderData orderData = REDIS.getCacheMapValue(orderkey, "orderData");
            Map<String, Object> pushOrder = REDIS.getCacheMap(pushOrderKey);
            if (orderData != null || (pushOrder != null && pushOrder.get("startChargeSeqStat") != null && (Integer) pushOrder.get("startChargeSeqStat") > 3)) {
                Boolean isStopNotified = (Boolean) pushOrder.get("isStopNotified");
                if (isStopNotified == null || !isStopNotified) {
                    String internetSerialNumber = (String) pushOrder.get("internetSerialNumber");
                    if (internetSerialNumber == null) {
                        continue;
                    }
                    String operatorId3rdpty = internetSerialNumber.substring(0, 9);
                    AuthSecretToken authSecretTokenOut =authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId3rdpty,SECRET_TOKEN_TYPE_OUT).orElse(null);
                    CommonRequest<ChargeResultRequest> commonRequest = new CommonRequest<>();
                    ChargeResultRequest chargeResultRequest = new ChargeResultRequest();
                    chargeResultRequest.setStartChargeSeq(internetSerialNumber);
                    //使用指定包装类封装数据
                    chargeResultRequest.setConnectorID(orderkey.substring(0, 16));
                    chargeResultRequest.setStartChargeSeqStat(4);
                    chargeResultRequest.setSuccStat(0);
                    chargeResultRequest.setFailReason(0);
                    //将其转换为json
                    String jsonData = JSONUtil.toJSONString(chargeResultRequest);
                    commonRequest.setData(jsonData);
                    String result = ok(commonRequest, "/notification_stop_charge_result", authSecretTokenOut);

                    System.out.println("====停止推送结果=======notification_stop_charge_result========="+result+"============orderNo========"+orderNo);
//                    ChargeResultResponse chargeResultResponse = DTOJsonHelper.parseResponseData(result,
//                            ChargeResultResponse.class, authSecretTokenOut);
                    pushOrder.put("isStopNotified", true);
                    REDIS.setCacheMap(pushOrderKey, pushOrder);
                }
            }
        }
    }
}
