package com.xhpc.evcs.notification.kuaidian;

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.jpa.PlaceholderIOrderTimeRepository;
import com.xhpc.evcs.notification.CoreDispatcher;
import com.xhpc.evcs.utils.JSONUtil;
import com.xhpc.order.domain.XhpcPlaceholderOrder;
import com.xhpc.order.domain.XhpcPlaceholderTimeOrder;
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.ArrayList;
import java.util.List;

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

/**
 * 快电占位费推送
 *
 * @author yuyang
 * @Date 2025-07-09 14:06
 */
@Component
@RestController
@RequestMapping("/overtimeOrderInfoTask")
public class NotificationOvertimeOrderInfoTask extends CoreDispatcher {

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

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

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

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


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

                if(placeholderOrder.getConfirmResult()==-2){
                    PlaceholderOrderInfoKuaiDian placeholderOrderInfo = new PlaceholderOrderInfoKuaiDian();
                    placeholderOrderInfo.setOvertimeBillCode(placeholderOrder.getPlaceholderOrderNumber());
                    placeholderOrderInfo.setStartChargeSeq(placeholderOrder.getInternetSerialNumber());
                    placeholderOrderInfo.setOvertimeBillStatus(1);
                    placeholderOrderInfo.setConnectorId(placeholderOrder.getTerminalNumber());
                    placeholderOrderInfo.setBillEquipment(1);
                    placeholderOrderInfo.setStartTime(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                    placeholderOrderInfo.setEndTime(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                    placeholderOrderInfo.setTotalTimeSpan(0);
                    placeholderOrderInfo.setOvertimePrice(new BigDecimal(0));
                    placeholderOrderInfo.setTotalMoney(new BigDecimal(0.00));

                    List<OvertimeDetail> overtimeDetails =new ArrayList<>();
                    OvertimeDetail overtimeDetail = new OvertimeDetail();
                    overtimeDetail.setDetailStartTime(placeholderOrderInfo.getStartTime());
                    overtimeDetail.setDetailEndTime(placeholderOrderInfo.getStartTime());
                    overtimeDetail.setDetailMoney(new BigDecimal(0.00));
                    overtimeDetail.setOvertimePrice(new BigDecimal(0.00));
                    overtimeDetails.add(overtimeDetail);
                    placeholderOrderInfo.setOvertimeDetails(overtimeDetails);


                    final OvertimeOrderInfo pushResp = notify(placeholderOrderInfo, authSecretTokenOut);
                    if (pushResp != null) {
                        if(pushResp.getSuccStat()==0){
                            placeholderOrder.setConfirmResult(-1);
                        }else{
                            placeholderOrder.setConfirmResult(pushResp.getSuccStat());
                        }
                        //logger.info("==============推送返回值================="+pushResp.toString());
                        placeholderIOrderRepository.save(placeholderOrder);
                    } else {
                        logger.error("快电3dp[{}] order[{}/{}] push fail", "MA005DBW1",placeholderOrder.getSerialNumber(), placeholderOrder.getInternetSerialNumber());
                    }
                }
            }


            final List<XhpcPlaceholderOrder> notYetPushOrderYu =placeholderIOrderRepository.findTop100ByOperatorIdEvcsAndTypeAndConfirmResultOrderByPlaceholderOrderIdAsc("MA005DBW1",1,-1);
            for (XhpcPlaceholderOrder placeholderOrder : notYetPushOrderYu) {
                PlaceholderOrderInfoKuaiDian placeholderOrderInfo = new PlaceholderOrderInfoKuaiDian();
                placeholderOrderInfo.setOvertimeBillCode(placeholderOrder.getPlaceholderOrderNumber());
                placeholderOrderInfo.setStartChargeSeq(placeholderOrder.getInternetSerialNumber());
                placeholderOrderInfo.setOvertimeBillStatus(3);
                placeholderOrderInfo.setConnectorId(placeholderOrder.getTerminalNumber());
                placeholderOrderInfo.setBillEquipment(1);
                placeholderOrderInfo.setStartTime(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                placeholderOrderInfo.setEndTime(DateUtil.format(placeholderOrder.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                placeholderOrderInfo.setTotalTimeSpan(placeholderOrder.getTotalTimeSpan());
                placeholderOrderInfo.setOvertimePrice(placeholderOrder.getOvertimePrice());
                placeholderOrderInfo.setTotalMoney(placeholderOrder.getTotalMoney());


                List<XhpcPlaceholderTimeOrder> list = placeholderIOrderTimeRepository.findByPlaceholderOrderIdAndDelFlag(placeholderOrder.getPlaceholderOrderId(), 0);

                if(placeholderOrder.getTotalMoney().compareTo(new BigDecimal(0.00))==0){
                    List<OvertimeDetail> overtimeDetails =new ArrayList<>();
                    OvertimeDetail overtimeDetail = new OvertimeDetail();
                    overtimeDetail.setDetailStartTime(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                    overtimeDetail.setDetailEndTime(DateUtil.format(placeholderOrder.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                    overtimeDetail.setDetailMoney(placeholderOrder.getTotalMoney());
                    overtimeDetail.setOvertimePrice(new BigDecimal(0.2));
                    overtimeDetails.add(overtimeDetail);

                    placeholderOrderInfo.setOvertimeDetails(overtimeDetails);
                }else{
                    List<OvertimeDetail> overtimeDetails =new ArrayList<>();
                    for (int i = 0; i < list.size(); i++) {
                        XhpcPlaceholderTimeOrder xhpcPlaceholderTimeOrder = list.get(i);
                        OvertimeDetail overtimeDetail = new OvertimeDetail();
                        overtimeDetail.setDetailStartTime(DateUtil.format(xhpcPlaceholderTimeOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                        overtimeDetail.setDetailEndTime(DateUtil.format(xhpcPlaceholderTimeOrder.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                        overtimeDetail.setDetailMoney(xhpcPlaceholderTimeOrder.getTotalmoney());
                        overtimeDetail.setOvertimePrice(xhpcPlaceholderTimeOrder.getPrice());
                        overtimeDetails.add(overtimeDetail);

                    }
                    placeholderOrderInfo.setOvertimeDetails(overtimeDetails);
                }
                final OvertimeOrderInfo pushResp = notify(placeholderOrderInfo, authSecretTokenOut);
                if (pushResp != null) {
                    placeholderOrder.setConfirmResult(pushResp.getSuccStat());
                    placeholderOrder.setStatus(3);
                    //logger.info("==============推送返回值================="+pushResp.toString());
                    placeholderIOrderRepository.save(placeholderOrder);
                } else {
                    logger.error("快电3dp[{}] order[{}/{}] push fail", "MA005DBW1",placeholderOrder.getSerialNumber(), placeholderOrder.getInternetSerialNumber());
                }
            }
        }
    }
    @PostMapping("/v1/getXhpcPlaceholderOrder")
    public void getXhpcPlaceholderOrder(Long placeholderOrderId) throws IOException {

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


        if (authSecretTokenOut != null) {
            final XhpcPlaceholderOrder  placeholderOrder=placeholderIOrderRepository.findByPlaceholderOrderId(placeholderOrderId);
                if(placeholderOrder.getConfirmResult()==-2){
                    PlaceholderOrderInfoKuaiDian placeholderOrderInfo = new PlaceholderOrderInfoKuaiDian();
                    placeholderOrderInfo.setOvertimeBillCode(placeholderOrder.getPlaceholderOrderNumber());
                    placeholderOrderInfo.setStartChargeSeq(placeholderOrder.getInternetSerialNumber());
                    placeholderOrderInfo.setOvertimeBillStatus(1);
                    placeholderOrderInfo.setConnectorId(placeholderOrder.getTerminalNumber());
                    placeholderOrderInfo.setBillEquipment(1);
                    placeholderOrderInfo.setStartTime(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                    placeholderOrderInfo.setEndTime(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                    placeholderOrderInfo.setTotalTimeSpan(0);
                    placeholderOrderInfo.setOvertimePrice(new BigDecimal(0));
                    placeholderOrderInfo.setTotalMoney(new BigDecimal(0.00));

                    List<OvertimeDetail> overtimeDetails =new ArrayList<>();
                    OvertimeDetail overtimeDetail = new OvertimeDetail();
                    overtimeDetail.setDetailStartTime(placeholderOrderInfo.getStartTime());
                    overtimeDetail.setDetailEndTime(placeholderOrderInfo.getStartTime());
                    overtimeDetail.setDetailMoney(new BigDecimal(0.00));
                    overtimeDetail.setOvertimePrice(new BigDecimal(0.00));
                    overtimeDetails.add(overtimeDetail);
                    placeholderOrderInfo.setOvertimeDetails(overtimeDetails);


                    final OvertimeOrderInfo pushResp = notify(placeholderOrderInfo, authSecretTokenOut);
                    if (pushResp != null) {
                        if(pushResp.getSuccStat()==0){
                            placeholderOrder.setConfirmResult(-1);
                        }else{
                            placeholderOrder.setConfirmResult(pushResp.getSuccStat());
                        }
                        //logger.info("==============推送返回值================="+pushResp.toString());
                        placeholderIOrderRepository.save(placeholderOrder);
                    } else {
                        logger.error("新电途3dp[{}] order[{}/{}] push fail", "MA25CNM38",placeholderOrder.getSerialNumber(), placeholderOrder.getInternetSerialNumber());
                    }
                }else if(placeholderOrder.getConfirmResult()==-1){
                    PlaceholderOrderInfoKuaiDian placeholderOrderInfo = new PlaceholderOrderInfoKuaiDian();
                    placeholderOrderInfo.setOvertimeBillCode(placeholderOrder.getPlaceholderOrderNumber());
                    placeholderOrderInfo.setStartChargeSeq(placeholderOrder.getInternetSerialNumber());
                    placeholderOrderInfo.setOvertimeBillStatus(3);
                    placeholderOrderInfo.setConnectorId(placeholderOrder.getTerminalNumber());
                    placeholderOrderInfo.setConnectorId(placeholderOrder.getTerminalNumber());
                    placeholderOrderInfo.setBillEquipment(1);
                    placeholderOrderInfo.setConnectorId(placeholderOrder.getTerminalNumber());
                    placeholderOrderInfo.setStartTime(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                    placeholderOrderInfo.setEndTime(DateUtil.format(placeholderOrder.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                    placeholderOrderInfo.setTotalTimeSpan(placeholderOrder.getTotalTimeSpan());
                    placeholderOrderInfo.setOvertimePrice(placeholderOrder.getOvertimePrice());
                    placeholderOrderInfo.setTotalMoney(placeholderOrder.getTotalMoney());

                    if(placeholderOrder.getTotalMoney().compareTo(new BigDecimal(0.00))==0){
                        List<OvertimeDetail> overtimeDetails =new ArrayList<>();
                        OvertimeDetail overtimeDetail = new OvertimeDetail();
                        overtimeDetail.setDetailStartTime(DateUtil.format(placeholderOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                        overtimeDetail.setDetailEndTime(DateUtil.format(placeholderOrder.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                        overtimeDetail.setDetailMoney(placeholderOrder.getTotalMoney());
                        overtimeDetail.setOvertimePrice(new BigDecimal(0.2));
                        overtimeDetails.add(overtimeDetail);

                        placeholderOrderInfo.setOvertimeDetails(overtimeDetails);
                    }else{
                        List<XhpcPlaceholderTimeOrder> list = placeholderIOrderTimeRepository.findByPlaceholderOrderIdAndDelFlag(placeholderOrder.getPlaceholderOrderId(), 0);
                        List<OvertimeDetail> overtimeDetails =new ArrayList<>();
                        for (int i = 0; i < list.size(); i++) {
                            XhpcPlaceholderTimeOrder xhpcPlaceholderTimeOrder = list.get(i);
                            OvertimeDetail overtimeDetail = new OvertimeDetail();
                            overtimeDetail.setDetailStartTime(DateUtil.format(xhpcPlaceholderTimeOrder.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                            overtimeDetail.setDetailEndTime(DateUtil.format(xhpcPlaceholderTimeOrder.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                            overtimeDetail.setDetailMoney(xhpcPlaceholderTimeOrder.getTotalmoney());
                            overtimeDetail.setOvertimePrice(xhpcPlaceholderTimeOrder.getPrice());
                            overtimeDetails.add(overtimeDetail);

                        }
                        placeholderOrderInfo.setOvertimeDetails(overtimeDetails);
                    }
                    final OvertimeOrderInfo pushResp = notify(placeholderOrderInfo, authSecretTokenOut);
                    if (pushResp != null) {
                        placeholderOrder.setConfirmResult(pushResp.getSuccStat());
                        placeholderOrder.setStatus(3);
                        //logger.info("==============推送返回值================="+pushResp.toString());
                        placeholderIOrderRepository.save(placeholderOrder);
                    } else {
                        logger.error("快电3dp[{}] order[{}/{}] push fail", "MA25CNM38",placeholderOrder.getSerialNumber(), placeholderOrder.getInternetSerialNumber());
                    }
                }
        }
    }


    public OvertimeOrderInfo notify(PlaceholderOrderInfoKuaiDian placeholderOrderInfo, AuthSecretToken authSecretTokenOut) throws JsonProcessingException {

        String data = JSONUtil.toJSONString(placeholderOrderInfo);
        CommonRequest<PlaceholderOrderInfoKuaiDian> commonRequest = new CommonRequest<>();
        commonRequest.setData(data);
        String responseBody = ok(commonRequest, "/notification_overtime_order_info", authSecretTokenOut);

        logger.debug("“==========快电====responseBody=============="+responseBody);
        return DTOJsonHelper.parseResponseData(responseBody,
                OvertimeOrderInfo.class, authSecretTokenOut);
    }


}
