package com.xhpc.evcs.notification.xindiantu;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.xhpc.evcs.domain.*;
import com.xhpc.evcs.dto.*;
import com.xhpc.evcs.jpa.*;
import com.xhpc.evcs.notification.CoreDispatcher;
import com.xhpc.evcs.utils.JSONUtil;
import com.xhpc.order.domain.XhpcHistoryOrder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

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

/**
 * 新电途推送订单
 */
@Component
@Slf4j
public class NotificationChargeOrderInfoXinDianTuTask extends CoreDispatcher {

    @Autowired
    private XhpcHistoryOrderRepository xhpcHistoryOrderRepository;
    @Autowired
    private AuthSecretTokenRepository authSecretTokenRepository;

    private final Logger logger = LoggerFactory.getLogger(NotificationChargeOrderInfoXinDianTuTask.class);
    /**
     * 推送充电新电途订单信息(暂时不开放)
     * * @throws IOException
     */
    //9099开放定时任务  9009不开放
    //@Scheduled(fixedDelay = 1000 * 23)
    //@Scheduled(cron = "0/15 * * * * ? ")
    public void run() throws IOException {
        logger.info("==============开始推送新电途订单=================");
        AuthSecretToken authSecretTokenOut =
                authSecretTokenRepository.findByOperatorId3irdptyAndOperatorIdAndSecretTokenType(
                        "MA25CNM38", "MA6DFCTD5", SECRET_TOKEN_TYPE_OUT).orElse(null); //todo
        // maybe对接第三方
        if (authSecretTokenOut != null) {
            final List<XhpcHistoryOrder> notYetPushOrder =
                    xhpcHistoryOrderRepository.findTop100ByHistoryOrderIdGreaterThanEqualAndConfirmResultAndUserIdOrderByHistoryOrderIdAsc(authSecretTokenOut.getLastPushOrder(),-1, 3L);
            for (XhpcHistoryOrder horder : notYetPushOrder) {

                String operatorId3rdptyEvcs = horder.getOperatorId3rdptyEvcs();
                logger.info("==============开始推送新电途订单================="+horder.getInternetSerialNumber());
                if (operatorId3rdptyEvcs == null) {
                    if (horder.getInternetSerialNumber() != null) {
                        operatorId3rdptyEvcs = horder.getInternetSerialNumber().substring(0, 9);
                        horder.setOperatorId3rdptyEvcs(operatorId3rdptyEvcs);
                        xhpcHistoryOrderRepository.save(horder); // mending
                    }
                }

                ChargeOrderInfo chargeOrderInfo = new ChargeOrderInfo(horder);
                final ChargeOrderInfoResponse pushResp = notify(chargeOrderInfo, authSecretTokenOut);
                if (pushResp != null) {
                    horder.setConfirmResult(pushResp.getConfirmResult());
                    logger.debug("新电途3rd part order {} push result: {}", horder.getSerialNumber(),
                            pushResp.getConfirmResult());
                    //logger.info("==============推送返回值================="+pushResp.toString());
                    xhpcHistoryOrderRepository.save(horder);
                    REDIS.setCacheMapValue("pushOrder:".concat(horder.getSerialNumber()), "horderpushed", true);

                    authSecretTokenOut.setLastPushOrder(horder.getHistoryOrderId());
                    authSecretTokenRepository.save(authSecretTokenOut);
                } else {
                    logger.error("新电途3dp[{}] order[{}/{}] push fail", operatorId3rdptyEvcs,
                            horder.getSerialNumber(), horder.getInternetSerialNumber());
                }
            }

        }
    }


    public ChargeOrderInfoResponse notify(ChargeOrderInfo chargeOrderInfo, AuthSecretToken authSecretTokenOut) throws JsonProcessingException {

        String data = JSONUtil.toJSONString(chargeOrderInfo);
        CommonRequest<ChargeOrderInfo> commonRequest = new CommonRequest<>();
        commonRequest.setData(data);
        String responseBody = ok(commonRequest, "/notification_charge_order_info", authSecretTokenOut);
        return DTOJsonHelper.parseResponseData(responseBody,
                ChargeOrderInfoResponse.class, authSecretTokenOut);
    }
}
