package com.xhpc.evcs.notification.xindiantu;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xhpc.common.api.dto.ChargingStationDto;
import com.xhpc.evcs.domain.AuthSecretToken;
import com.xhpc.evcs.domain.PriceInfo;
import com.xhpc.evcs.domain.XhpcStationInternetBlacklist;
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.XhpcPlaceholderITime;
import com.xhpc.order.domain.XhpcPlacreholder;
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 javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

/**
 * 占位费规则
 * @author yuyang
 * @Date 2025-08-06 15:30
 */
@Component
@RestController
@RequestMapping("/notificationPlaceholderRulesTask")
public class NotificationPlaceholderRulesTask extends CoreDispatcher {

    @Resource
    private AuthSecretTokenRepository authSecretTokenRepository;
    @Autowired
    private PlaceholderIRepository placeholderIRepository;
    @Resource
    private PlaceholderITimeRepository placeholderITimeRepository;
    @Resource
    private XhpcStationInternetBlacklistRepository xhpcStationInternetBlacklistRepo;
    private final Logger logger = LoggerFactory.getLogger(NotificationPlaceholderRulesTask.class);

    //9009开放定时任务  9099不开放
    @Scheduled(cron = "0 0 0/6 * * ? ")
   // @Scheduled(cron = "0 0/1 * * * ? ")
    public void run() throws IOException {
        AuthSecretToken authSecretTokenOut =
                authSecretTokenRepository.findByOperatorId3irdptyAndOperatorIdAndSecretTokenType("MA25CNM38", "MA6DFCTD5", SECRET_TOKEN_TYPE_OUT).orElse(null); //todo

        List<XhpcStationInternetBlacklist> xhpcStationInternetBlacklist = xhpcStationInternetBlacklistRepo.findByInternetUserId(3L);
        List<String> stationKeys = new ArrayList<>(REDIS.keys("station:*"));

        List<String> validStationKeys = new ArrayList<>();
        for (String stationKey : stationKeys) {
            boolean isValid = true;
            //查询不合作的电桩
            for (XhpcStationInternetBlacklist xhpcStationInternetBlack : xhpcStationInternetBlacklist) {
                if (stationKey.substring(8).equals(xhpcStationInternetBlack.getChargingStationId().toString())) {
                    isValid = false;
                }
            }
            ChargingStationDto chargingStationDto = REDIS.getCacheObject(stationKey);
            if (chargingStationDto.getPiles() != null) {
                if (isValid) {
                    validStationKeys.add(stationKey);
                }
            }
        }
        for (String stationKey : validStationKeys) {

                    if (authSecretTokenOut != null) {
                        String stationId = stationKey.substring(8);
                        XhpcPlacreholder xhpcPlacreholder = placeholderIRepository.findByChargingStationIdAndDelFlag(Long.valueOf(stationId), 0);

                        PlaceholderRulesXinDianTu placeholderRulesXinDianTu = new PlaceholderRulesXinDianTu();

                        placeholderRulesXinDianTu.setStationID(stationId);
                        String startTime = DateUtil.format(xhpcPlacreholder.getStartTime(), "yyyy.MM.dd HH:mm:ss");
                        String endTime = DateUtil.format(xhpcPlacreholder.getEndTime(), "yyyy.MM.dd HH:mm:ss");
                        placeholderRulesXinDianTu.setEffectStartTime(startTime);
                        placeholderRulesXinDianTu.setEffectEndTime(endTime);
                        placeholderRulesXinDianTu.setStatus(xhpcPlacreholder.getType());
                        placeholderRulesXinDianTu.setFreeTime(xhpcPlacreholder.getFreeTime());
                        placeholderRulesXinDianTu.setMaxFee(xhpcPlacreholder.getMaxFee().doubleValue());

                        List<PriceInfo> priceInfos =new ArrayList<>();
                        List<XhpcPlaceholderITime> xhpcPlaceholderITimeList = placeholderITimeRepository.findByPlaceholderIdAndDelFlagAndChargingStationId(xhpcPlacreholder.getPlaceholderId(), 0,Long.valueOf(stationId));
                        if(xhpcPlaceholderITimeList !=null && xhpcPlaceholderITimeList.size()>0){
                            for (int j = 0; j < xhpcPlaceholderITimeList.size(); j++) {
                                XhpcPlaceholderITime xhpcPlaceholderTimeOrder = xhpcPlaceholderITimeList.get(j);
                                PriceInfo placeHolderPrice = new PriceInfo();
                                placeHolderPrice.setStartTime(DateUtil.format(xhpcPlaceholderTimeOrder.getStartTime(),"HH:mm:ss"));
                                placeHolderPrice.setPrice(xhpcPlaceholderTimeOrder.getPrice().doubleValue());
                                priceInfos.add(placeHolderPrice);
                            }
                        }
                        placeholderRulesXinDianTu.setPriceInfos(priceInfos);

                        notify(placeholderRulesXinDianTu,authSecretTokenOut);
                    }
        }
    }


    public void notify(PlaceholderRulesXinDianTu placeholderRulesXinDianTu, AuthSecretToken authSecretTokenOut) throws JsonProcessingException {

        String data = JSONUtil.toJSONString(placeholderRulesXinDianTu);
        logger.error("新电途========placeholderRulesXinDianTu================"+data);
        CommonRequest<PlaceholderRulesXinDianTu> commonRequest = new CommonRequest<>();
        commonRequest.setData(data);
        String responseBody = ok(commonRequest, "/notification_placeholder_rules", authSecretTokenOut);
        logger.error("新电途========responseBody================"+responseBody);

    }
}
