package com.xhpc.evcs.notification.henda;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.xhpc.evcs.domain.AuthSecretToken;
import com.xhpc.evcs.dto.ChargeOrderInfo;
import com.xhpc.evcs.dto.ChargeOrderInfoResponse;
import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.dto.DTOJsonHelper;
import com.xhpc.evcs.jpa.AuthSecretTokenRepository;
import com.xhpc.evcs.jpa.XhpcHistoryOrderRepository;
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 NotificationChargeOrderInfoHenDaTask extends CoreDispatcher {

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

    private final Logger logger = LoggerFactory.getLogger(NotificationChargeOrderInfoHenDaTask.class);
    /**
     * 推送充电恒大订单信息(不推送，有整体推送)
     * * @throws IOException
     */
    public void run() throws IOException {

        AuthSecretToken authSecretTokenOut =
                authSecretTokenRepository.findByOperatorId3irdptyAndOperatorIdAndSecretTokenType(
                        "MA5FF58R7", "MA6DFCTD5", SECRET_TOKEN_TYPE_OUT).orElse(null); //todo

        // maybe对接第三方
        if (authSecretTokenOut != null) {
            final List<XhpcHistoryOrder> notYetPushOrder =
                    xhpcHistoryOrderRepository.findTop100ByHistoryOrderIdGreaterThanEqualAndConfirmResultAndUserIdOrderByHistoryOrderIdAsc(authSecretTokenOut.getLastPushOrder(), -1,2L);
            for (XhpcHistoryOrder horder : notYetPushOrder) {

                String operatorId3rdptyEvcs = horder.getOperatorId3rdptyEvcs();
                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);
    }
}
