package com.xhpc.evcs.notification.xindiantu;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xhpc.evcs.domain.AuthSecretToken;
import com.xhpc.evcs.dto.*;
import com.xhpc.evcs.jpa.AuthSecretTokenRepository;
import com.xhpc.evcs.jpa.PlaceholderIOrderRepository;
import com.xhpc.evcs.notification.CoreDispatcher;
import com.xhpc.evcs.utils.JSONUtil;
import com.xhpc.order.domain.XhpcPlaceholderOrder;
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 org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

import static com.xhpc.evcs.domain.AuthSecretToken.SECRET_TOKEN_TYPE_OUT;

/**
 * 新电途占位费订单信息推送
 *
 * @author yuyang
 * @Date 2025-07-08 14:31
 */
@Component
@RestController
@RequestMapping("/placeholderOrderInfoTask")
public class NotificationPlaceholderOrderInfoTask extends CoreDispatcher {


    @Autowired
    private AuthSecretTokenRepository authSecretTokenRepository;
    @Autowired
    private PlaceholderIOrderRepository placeholderIOrderRepository;

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

    //(占位费还没有合作)
    //9009开放定时任务  9099不开放
    @Scheduled(fixedRate = 1000 * 30)
    public void run() throws IOException {

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

        if (authSecretTokenOut != null) {
            final List<XhpcPlaceholderOrder> notYetPushOrder =placeholderIOrderRepository.findTop100ByOperatorIdEvcsAndConfirmResultOrderByPlaceholderOrderIdAsc("MA25CNM38",-2);
            for (XhpcPlaceholderOrder placeholderOrder : notYetPushOrder) {

                if(placeholderOrder.getConfirmResult()==-2){
                    PlaceholderOrderInfo placeholderOrderInfo = new PlaceholderOrderInfo();
                    placeholderOrderInfo.setPlaceholderOrderID(placeholderOrder.getPlaceholderOrderNumber());
                    placeholderOrderInfo.setStarChargeSeq(placeholderOrder.getInternetSerialNumber());
                    placeholderOrderInfo.setTimeStart(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                    placeholderOrderInfo.setTimeEnd(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                    placeholderOrderInfo.setHoldTime(0);
                    placeholderOrderInfo.setActuallyPay(0.0);
                    placeholderOrderInfo.setBillEquipment(1);
                    placeholderOrderInfo.setStatus(1);

                    final ChargeOrderInfoResponse pushResp = notify(placeholderOrderInfo, authSecretTokenOut);
                    if (pushResp != null) {
                        if(pushResp.getConfirmResult()==0){
                            placeholderOrder.setConfirmResult(-1);
                        }else{
                            placeholderOrder.setConfirmResult(pushResp.getConfirmResult());
                        }
                        logger.debug("新电途3rd part order {} push result: {}", placeholderOrder.getSerialNumber(),pushResp.getConfirmResult());
                        //logger.info("==============推送返回值================="+pushResp.toString());
                        placeholderIOrderRepository.save(placeholderOrder);
                    } else {
                        logger.error("新电途3dp[{}] order[{}/{}] push fail", "MA25CNM38",placeholderOrder.getSerialNumber(), placeholderOrder.getInternetSerialNumber());
                    }

                }
            }


            final List<XhpcPlaceholderOrder> notYetPushOrderYu =placeholderIOrderRepository.findTop100ByOperatorIdEvcsAndTypeAndConfirmResultOrderByPlaceholderOrderIdAsc("MA25CNM38",1,-1);
            for (XhpcPlaceholderOrder placeholderOrder : notYetPushOrderYu) {
                PlaceholderOrderInfo placeholderOrderInfo = new PlaceholderOrderInfo();
                placeholderOrderInfo.setPlaceholderOrderID(placeholderOrder.getPlaceholderOrderNumber());
                placeholderOrderInfo.setStarChargeSeq(placeholderOrder.getInternetSerialNumber());
                placeholderOrderInfo.setTimeStart(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                placeholderOrderInfo.setTimeEnd(DateUtil.format(placeholderOrder.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                placeholderOrderInfo.setHoldTime(placeholderOrder.getTotalTimeSpan());
                placeholderOrderInfo.setOvertimePrice(new BigDecimal(0.2).doubleValue());
                placeholderOrderInfo.setActuallyPay(placeholderOrder.getTotalMoney().doubleValue());
                placeholderOrderInfo.setBillEquipment(1);
                placeholderOrderInfo.setStatus(9);

                final ChargeOrderInfoResponse pushResp = notify(placeholderOrderInfo, authSecretTokenOut);
                if (pushResp != null) {
                    placeholderOrder.setStatus(9);
                    placeholderOrder.setConfirmResult(pushResp.getConfirmResult());
                    logger.debug("新电途3rd part order {} push result: {}", placeholderOrder.getSerialNumber(),pushResp.getConfirmResult());
                    //logger.info("==============推送返回值================="+pushResp.toString());
                    placeholderIOrderRepository.save(placeholderOrder);
                } else {
                    logger.error("新电途3dp[{}] order[{}/{}] push fail", "MA25CNM38",placeholderOrder.getSerialNumber(), placeholderOrder.getInternetSerialNumber());
                }
            }
        }
    }

    @PostMapping("/v1/getNotificationPlaceholderOrderInfo")
    public void getNotificationPlaceholderOrderInfo(Long placeholderOrderId) throws IOException {

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

        logger.info("===========placeholderOrderId=========="+placeholderOrderId);
        if (authSecretTokenOut != null) {
            final XhpcPlaceholderOrder placeholderOrder=placeholderIOrderRepository.findByPlaceholderOrderId(placeholderOrderId);
                if(placeholderOrder.getConfirmResult()==-2){
                    PlaceholderOrderInfo placeholderOrderInfo = new PlaceholderOrderInfo();
                    placeholderOrderInfo.setPlaceholderOrderID(placeholderOrder.getPlaceholderOrderNumber());
                    placeholderOrderInfo.setStarChargeSeq(placeholderOrder.getInternetSerialNumber());
                    placeholderOrderInfo.setTimeStart(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                    placeholderOrderInfo.setTimeEnd(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                    placeholderOrderInfo.setHoldTime(0);
                    placeholderOrderInfo.setActuallyPay(0.0);
                    placeholderOrderInfo.setBillEquipment(1);
                    placeholderOrderInfo.setStatus(1);

                    final ChargeOrderInfoResponse pushResp = notify(placeholderOrderInfo, authSecretTokenOut);
                    if (pushResp != null) {
                        if(pushResp.getConfirmResult()==0){
                            placeholderOrder.setConfirmResult(-1);
                        }else{
                            placeholderOrder.setConfirmResult(pushResp.getConfirmResult());
                        }
                        logger.debug("新电途3rd part order {} push result: {}", placeholderOrder.getSerialNumber(),pushResp.getConfirmResult());
                        //logger.info("==============推送返回值================="+pushResp.toString());
                        placeholderIOrderRepository.save(placeholderOrder);
                    } else {
                        logger.error("新电途3dp[{}] order[{}/{}] push fail", "MA25CNM38",placeholderOrder.getSerialNumber(), placeholderOrder.getInternetSerialNumber());
                    }

                }else if(placeholderOrder.getConfirmResult()==-1){
                    PlaceholderOrderInfo placeholderOrderInfo = new PlaceholderOrderInfo();
                    placeholderOrderInfo.setPlaceholderOrderID(placeholderOrder.getPlaceholderOrderNumber());
                    placeholderOrderInfo.setStarChargeSeq(placeholderOrder.getInternetSerialNumber());
                    placeholderOrderInfo.setTimeStart(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                    placeholderOrderInfo.setTimeEnd(DateUtil.format(placeholderOrder.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                    placeholderOrderInfo.setHoldTime(placeholderOrder.getTotalTimeSpan());
                    placeholderOrderInfo.setActuallyPay(placeholderOrder.getTotalMoney().doubleValue());
                    placeholderOrderInfo.setBillEquipment(1);
                    placeholderOrderInfo.setStatus(9);

                    final ChargeOrderInfoResponse pushResp = notify(placeholderOrderInfo, authSecretTokenOut);
                    if (pushResp != null) {
                        placeholderOrder.setConfirmResult(pushResp.getConfirmResult());
                        logger.debug("新电途3rd part order {} push result: {}", placeholderOrder.getSerialNumber(),pushResp.getConfirmResult());
                        //logger.info("==============推送返回值================="+pushResp.toString());
                        placeholderIOrderRepository.save(placeholderOrder);
                    } else {
                        logger.error("新电途3dp[{}] order[{}/{}] push fail", "MA25CNM38",placeholderOrder.getSerialNumber(), placeholderOrder.getInternetSerialNumber());
                    }
                }

        }
    }


    public ChargeOrderInfoResponse notify(PlaceholderOrderInfo placeholderOrderInfo, AuthSecretToken authSecretTokenOut) throws JsonProcessingException {

        String data = JSONUtil.toJSONString(placeholderOrderInfo);
        CommonRequest<PlaceholderOrderInfo> commonRequest = new CommonRequest<>();
        commonRequest.setData(data);
        System.out.println("========新电途推送记录=============="+data);
        String responseBody = ok(commonRequest, "/notification_placeholder_order_info", authSecretTokenOut);
        return DTOJsonHelper.parseResponseData(responseBody,
                ChargeOrderInfoResponse.class, authSecretTokenOut);
    }
}
