package com.kym.service.impl;

import com.kym.common.utils.CommUtil;
import com.kym.entity.AdminUser;
import com.kym.entity.AdminUserStation;
import com.kym.mapper.AdminUserStationMapper;
import com.kym.service.AdminUserService;
import com.kym.service.AdminUserStationService;
import com.kym.service.cache.KymCache;
import com.kym.service.mybatisplus.MyBaseServiceImpl;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 操作员站点关联表 服务实现类
 * </p>
 *
 * @author skyline
 * @since 2023-09-18
 */
@Service
public class AdminUserStationServiceImpl extends MyBaseServiceImpl<AdminUserStationMapper, AdminUserStation> implements AdminUserStationService {

    private final AdminUserService adminUserService;

    public AdminUserStationServiceImpl(AdminUserService adminUserService) {
        this.adminUserService = adminUserService;
    }

    @PostConstruct
    private void init() {
        var adminUser2Stations = list().stream().collect(Collectors.toMap(AdminUserStation::getAdminUserId,
                adminUserStation -> {
                    List<String> stationIds = new ArrayList<>();
                    stationIds.add(adminUserStation.getStationId());
                    return stationIds;
                },
                (v1, v2) -> {
                    v1.addAll(v2);
                    return v1;
                }
        ));

        KymCache.INSTANCE.putAdminUser2Stations(adminUser2Stations);

        // 筛选出角色为投资者的用户，缓存站点-投资者对应关系
        var investorAdminUserIds = adminUserService.getInvestorAdminUsers().stream().map(AdminUser::getId).toList();

        var investorAdminUser2Stations = adminUser2Stations.entrySet().stream()
                .filter(entry -> investorAdminUserIds.contains(entry.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        investorAdminUser2Stations.forEach((adminUserId, stationIds) -> {
            if (CommUtil.isNotEmptyAndNull(stationIds) && stationIds.size() == 1) {
                KymCache.INSTANCE.putStationId2InvestorAdminUserId(Map.of(stationIds.get(0), String.valueOf(adminUserId)));
            }
        });

    }


}
