package com.kym.miniapp.jobs;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.kym.entity.miniapp.vo.PlatformPolicyInfoVo;
import com.kym.entity.platform.PlatformPolicyInfo;
import com.kym.mapper.admin.EquipmentRelationMapper;
import com.kym.service.admin.StationService;
import com.kym.service.cache.KymCache;
import com.kym.service.miniapp.ChargeService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

/**
 * @author skyline
 * @description 用户优惠权益到期处理
 * @date 2023-11-15 14:00
 */
@Component
@Slf4j
public class StationPolicyInfoJob {

    private final StationService stationService;

    private final EquipmentRelationMapper equipmentRelationMapper;

    private final ChargeService chargeService;

    public StationPolicyInfoJob(
            StationService stationService,
            EquipmentRelationMapper equipmentRelationMapper,
            ChargeService chargeService) {
        this.equipmentRelationMapper = equipmentRelationMapper;
        this.stationService = stationService;
        this.chargeService = chargeService;
    }

    // 每次应用启动或每月第一天00:30运行一次
    @PostConstruct
    @Scheduled(cron = "0 10 0 * * ?")
    public void stationPolicyInfoJob() {
        log.info("站点费率信息定时更新启动...");
        // 手动切换数据源
        DynamicDataSourceContextHolder.push("db-admin");
        // 获取每个站点的第一个connectorId
        var stationConnectorMap = equipmentRelationMapper.selectLatestConnectorByStation();
        DynamicDataSourceContextHolder.poll();
        var maps = new HashMap<String, List<PlatformPolicyInfoVo>>(stationConnectorMap.size());
        stationConnectorMap.forEach(stationConnector -> {
            var policy = chargeService.queryEquipBusinessPolicy(stationConnector.get("connectorId"));
            maps.put(stationConnector.get("stationId"), policy.getPolicyInfos().stream().map(PlatformPolicyInfo::toVo).toList());
        });
        KymCache.INSTANCE.putStationId2PolicyInfo(maps);
        log.info("站点费率信息定时更新结束...");
    }
}
