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.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 EquipmentRelationMapper equipmentRelationMapper;

    private final ChargeService chargeService;

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

    // 每次应用启动或每月第一天00:30运行一次
    @PostConstruct
    @Scheduled(cron = "0 10 0 * * ?")
    public void stationPolicyInfoJob() {
        log.info("站点费率信息定时更新启动...");
        // 手动切换数据源
        DynamicDataSourceContextHolder.push("db-admin");
        try {
            // 获取每个站点的第一个connectorId
            var stationConnectorMap = equipmentRelationMapper.selectLatestConnectorByStation();
            var maps = new HashMap<String, List<PlatformPolicyInfoVo>>(stationConnectorMap.size());
            stationConnectorMap.forEach(stationConnector -> {
                try {
                    var policy = chargeService.queryEquipBusinessPolicy(stationConnector.get("connectorId"));
                    if (policy.getPolicyInfos() != null) {
                        maps.put(stationConnector.get("stationId"), policy.getPolicyInfos().stream().map(PlatformPolicyInfo::toVo).toList());
                    }
                } catch (Exception e) {
                    // 单个站点费率获取失败不影响其他站点，沿用该站点上次缓存
                    log.error("站点：{}费率信息获取失败", stationConnector.get("stationId"), e);
                }
            });
            KymCache.INSTANCE.putStationId2PolicyInfo(maps);
        } catch (Exception e) {
            // 任务异常不能影响应用启动，费率缓存沿用上次结果
            log.error("站点费率信息定时更新失败", e);
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
        log.info("站点费率信息定时更新结束...");
    }
}
