package com.xhpc.evcs.ykc.notification;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
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.notification.xindiantu.NotificationPlaceholderOrderInfoTask;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

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

/**
 * 云快充订单推送
 *
 * @author yuyang
 * @Date 2026-06-09 13:59
 */
@Component
@RestController
@RequestMapping("/yckPlaceholderOrderInfoTask")
public class YCKNotificationPlaceholderOrderInfoTask extends CoreDispatcher {


    @Autowired
    private AuthSecretTokenRepository authSecretTokenRepository;
    @Autowired
    private PlaceholderIOrderRepository placeholderIOrderRepository;
    private final Logger logger = LoggerFactory.getLogger(YCKNotificationPlaceholderOrderInfoTask.class);

    //9009开放定时任务  9099不开放
    @Scheduled(fixedRate = 1000 * 30)
    public void run() throws IOException {

        AuthSecretToken authSecretTokenOut =
                authSecretTokenRepository.findByOperatorId3irdptyAndOperatorIdAndSecretTokenType(
                        "MA1MY0GF9", "MA6DFCTD5", SECRET_TOKEN_TYPE_OUT).orElse(null); //todo
        if (authSecretTokenOut != null) {

            //初始化
            final List<XhpcPlaceholderOrder> notYetPushOrder =placeholderIOrderRepository.findTop100ByOperatorIdEvcsAndConfirmResultOrderByPlaceholderOrderIdAsc("MA1MY0GF9",-2);
            for (XhpcPlaceholderOrder placeholderOrder : notYetPushOrder) {
                if (placeholderOrder.getConfirmResult() == -2) {
                    OccupancyOrderInfo occupancyOrderInfo = new OccupancyOrderInfo();
                    occupancyOrderInfo.setOccupancyFeeCode(placeholderOrder.getPlaceholderOrderNumber());
                    occupancyOrderInfo.setOccupancyStatus(0);
                    occupancyOrderInfo.setStartChargeSeq(placeholderOrder.getInternetSerialNumber());
                    occupancyOrderInfo.setConnectorID(placeholderOrder.getTerminalNumber());
                    occupancyOrderInfo.setStartTime(DateUtil.format(placeholderOrder.getStartTime(), "yyyy-MM-dd HH:mm:ss"));

                    occupancyOrderInfo.setFreeDuration(placeholderOrder.getFreeTime());
                    occupancyOrderInfo.setOccupancyDuration(0);
                    occupancyOrderInfo.setTotalOccupancyFee(new BigDecimal(0));

                    final ChargeOrderInfoResponse pushResp = notify(occupancyOrderInfo, authSecretTokenOut);
                    if (pushResp != null) {

                        Map<String, Object> additionalProperties = pushResp.getAdditionalProperties();

                        if (Integer.valueOf(additionalProperties.get("SuccStat").toString()) == 0) {
                            placeholderOrder.setConfirmResult(-1);
                        } else {
                            placeholderOrder.setConfirmResult(pushResp.getConfirmResult());
                        }
                        logger.debug("云快充3rd part order {} push result: {}", placeholderOrder.getSerialNumber(), pushResp.getConfirmResult());
                        //logger.info("==============推送返回值================="+pushResp.toString());
                        placeholderOrder.setStatus(0);
                        placeholderIOrderRepository.save(placeholderOrder);
                    } else {
                        logger.error("云快充3dp[{}] order[{}/{}] push fail", "MA1MY0GF9", placeholderOrder.getSerialNumber(), placeholderOrder.getInternetSerialNumber());
                    }
                }
            }
          //占位结束
            final List<XhpcPlaceholderOrder> notYetPushOrderYus =placeholderIOrderRepository.findTop100ByOperatorIdEvcsAndTypeAndConfirmResultOrderByPlaceholderOrderIdAsc("MA1MY0GF9",1,-1);
            for (XhpcPlaceholderOrder placeholderOrder : notYetPushOrderYus) {
                OccupancyOrderInfo occupancyOrderInfo = new OccupancyOrderInfo();
                occupancyOrderInfo.setOccupancyFeeCode(placeholderOrder.getPlaceholderOrderNumber());
                occupancyOrderInfo.setOccupancyStatus(3);
                occupancyOrderInfo.setStartChargeSeq(placeholderOrder.getInternetSerialNumber());
                occupancyOrderInfo.setConnectorID(placeholderOrder.getTerminalNumber());
                occupancyOrderInfo.setStartTime(DateUtil.format(placeholderOrder.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                occupancyOrderInfo.setEndTime(DateUtil.format(placeholderOrder.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
                occupancyOrderInfo.setFreeDuration(placeholderOrder.getFreeTime());
                if(placeholderOrder.getTotalTimeSpan()>30){
                    occupancyOrderInfo.setOccupancyFeeStartTime(DateUtil.format(DateUtil.offsetMinute(placeholderOrder.getStartTime(),30), "yyyy-MM-dd HH:mm:ss"));
                    occupancyOrderInfo.setOccupancyDuration(placeholderOrder.getTotalTimeSpan()-30);
                }else{
                    occupancyOrderInfo.setOccupancyDuration(0);
                }
                occupancyOrderInfo.setTotalOccupancyFee(placeholderOrder.getTotalMoney());
                final ChargeOrderInfoResponse pushResp = notify(occupancyOrderInfo, authSecretTokenOut);
                if (pushResp != null) {

                    Map<String, Object> additionalProperties = pushResp.getAdditionalProperties();
                    if (Integer.valueOf(additionalProperties.get("SuccStat").toString()) != 0) {
                        placeholderOrder.setConfirmResult(pushResp.getConfirmResult());
                    } else {
                        placeholderOrder.setConfirmResult(0);
                    }
                    placeholderOrder.setStatus(3);
                    logger.debug("云快充3rd part order {} push result: {}", placeholderOrder.getSerialNumber(), pushResp.getConfirmResult());
                    placeholderIOrderRepository.save(placeholderOrder);
                } else {
                    logger.error("云快充3dp[{}] order[{}/{}] push fail", "MA1MY0GF9", placeholderOrder.getSerialNumber(), placeholderOrder.getInternetSerialNumber());
                }
            }
        }
    }


    @Scheduled(cron = "0 0/15 * * * ? ")
    public void runYu() throws IOException {

        AuthSecretToken authSecretTokenOut =
                authSecretTokenRepository.findByOperatorId3irdptyAndOperatorIdAndSecretTokenType(
                        "MA1MY0GF9", "MA6DFCTD5", SECRET_TOKEN_TYPE_OUT).orElse(null); //todo
        if (authSecretTokenOut != null) {
            final List<XhpcPlaceholderOrder> notYetPushOrder =placeholderIOrderRepository.findTop100ByOperatorIdEvcsAndTypeAndConfirmResultOrderByPlaceholderOrderIdAsc("MA1MY0GF9",0,-1);
            for (XhpcPlaceholderOrder placeholderOrder : notYetPushOrder) {
                if (placeholderOrder.getConfirmResult() == -1) {
                    OccupancyOrderInfo occupancyOrderInfo = new OccupancyOrderInfo();
                    occupancyOrderInfo.setOccupancyFeeCode(placeholderOrder.getPlaceholderOrderNumber());
                    occupancyOrderInfo.setOccupancyStatus(2);
                    occupancyOrderInfo.setStartChargeSeq(placeholderOrder.getInternetSerialNumber());
                    occupancyOrderInfo.setConnectorID(placeholderOrder.getTerminalNumber());
                    occupancyOrderInfo.setStartTime(DateUtil.format(placeholderOrder.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                    occupancyOrderInfo.setFreeDuration(placeholderOrder.getFreeTime());
                    if(placeholderOrder.getTotalTimeSpan() !=null || placeholderOrder.getConfirmResult()==0){
                        if(placeholderOrder.getTotalTimeSpan()>30){
                            occupancyOrderInfo.setOccupancyFeeStartTime(DateUtil.format(DateUtil.offsetMinute(placeholderOrder.getStartTime(),30), "yyyy-MM-dd HH:mm:ss"));
                            occupancyOrderInfo.setOccupancyDuration(placeholderOrder.getTotalTimeSpan()-30);
                            occupancyOrderInfo.setTotalOccupancyFee(new BigDecimal(0.2).multiply(new BigDecimal(placeholderOrder.getTotalTimeSpan()-30)).setScale(2,BigDecimal.ROUND_CEILING));
                        }else{
                            occupancyOrderInfo.setOccupancyDuration(0);
                            occupancyOrderInfo.setTotalOccupancyFee(new BigDecimal(0));
                        }
                    }else{
                        DateTime parse = cn.hutool.core.date.DateUtil.parse(DateUtil.format(placeholderOrder.getStartTime(), "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss");
                        DateTime parse1 = new DateTime();
                        long betweenDay = cn.hutool.core.date.DateUtil.between(parse,parse1, DateUnit.MINUTE);
                        if(betweenDay>30){
                            int num = (int) (betweenDay - 30);
                            occupancyOrderInfo.setOccupancyFeeStartTime(DateUtil.format(DateUtil.offsetMinute(placeholderOrder.getStartTime(),30), "yyyy-MM-dd HH:mm:ss"));
                            occupancyOrderInfo.setOccupancyDuration(num);
                            occupancyOrderInfo.setTotalOccupancyFee(new BigDecimal(0.2).multiply(new BigDecimal(num)).setScale(2,BigDecimal.ROUND_HALF_UP));
                        }else{
                            occupancyOrderInfo.setOccupancyDuration(0);
                            occupancyOrderInfo.setTotalOccupancyFee(new BigDecimal(0));
                        }
                    }

                    final ChargeOrderInfoResponse pushResp = notify(occupancyOrderInfo, authSecretTokenOut);
                    if (pushResp != null) {
                        Map<String, Object> additionalProperties = pushResp.getAdditionalProperties();

                        if (Integer.valueOf(additionalProperties.get("SuccStat").toString()) == 0) {
                            placeholderOrder.setConfirmResult(-1);
                        } else {
                            placeholderOrder.setConfirmResult(Integer.valueOf(additionalProperties.get("SuccStat").toString()));
                        }
                        logger.debug("云快充3rd part order {} push result: {}", placeholderOrder.getSerialNumber(), pushResp.getConfirmResult());
                        placeholderOrder.setStatus(2);
                        placeholderIOrderRepository.save(placeholderOrder);
                    } else {
                        logger.error("云快充3dp[{}] order[{}/{}] push fail", "MA1MY0GF9", placeholderOrder.getSerialNumber(), placeholderOrder.getInternetSerialNumber());
                    }
                }
            }
        }
    }

    public ChargeOrderInfoResponse notify(OccupancyOrderInfo occupancyOrderInfo, AuthSecretToken authSecretTokenOut) throws JsonProcessingException {

        String data = JSONUtil.toJSONString(occupancyOrderInfo);
        CommonRequest<PlaceholderOrderInfo> commonRequest = new CommonRequest<>();
        commonRequest.setData(data);
        System.out.println("========云快充推送记录=============="+data);
        String responseBody = ok(commonRequest, "/notification_occupancy_order_info", authSecretTokenOut);
        return DTOJsonHelper.parseResponseData(responseBody,
                ChargeOrderInfoResponse.class, authSecretTokenOut);
    }

}
