package com.sundot.airport.system.service.portrait;


import com.sundot.airport.common.domain.portrait.BaseModuleIndicatorResult;
import com.sundot.airport.common.domain.portrait.IndicatorCalculateParams;
import com.sundot.airport.common.service.portrait.Indicator;
import com.sundot.airport.system.domain.portrait.IndicatorResult;
import com.sundot.airport.common.enums.portrait.IndicatorType;
import com.sundot.airport.common.enums.portrait.UserType;
import com.sundot.airport.system.domain.portrait.PositionCompetencyStats;
import com.sundot.airport.system.domain.portrait.PositionInfo;
import com.sundot.airport.system.mapper.portrait.AvailablePositionsIndicatorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 可上岗岗位指标实现类
 */
@Component
public class AvailablePositionsIndicator implements Indicator<Object> {

    @Autowired
    private AvailablePositionsIndicatorMapper availablePositionsIndicatorMapper;

    private Object value;

    @Override
    public String getName() {
        return IndicatorType.AVAILABLE_POSITIONS.getCode();
    }

    @Override
    public Object getValue() {
        return value;
    }

    @Override
    public void calculate(IndicatorCalculateParams params) {
        Long userId = params.getUserId();
        UserType userType = params.getUserType();
        List<Long> userIds = params.getUserIds();
        if (UserType.PERSONAL.equals(userType)) {
            // 个人可上岗岗位列表
            this.value = availablePositionsIndicatorMapper.queryPersonalAvailablePositions(userId);
        } else {
            // 组织岗位胜任统计
            calculateOrgPositionCompetencyStats(userIds);
        }
    }

    /**
     * 在服务层计算组织岗位胜任统计，避免复杂SQL
     *
     * @param userIds 用户ID列表
     */
    private void calculateOrgPositionCompetencyStats(List<Long> userIds) {
        // 获取所有用户的岗位信息
        List<PositionInfo> positionInfos = new ArrayList<>();
        for (Long userId : userIds) {
            positionInfos.addAll(availablePositionsIndicatorMapper.queryPersonalAvailablePositions(userId));
        }

        // 统计各岗位的胜任人数
        Map<String, Integer> positionCountMap = new HashMap<>();
        for (PositionInfo positionInfo : positionInfos) {
            String postName = positionInfo.getPostName();
            positionCountMap.put(postName, positionCountMap.getOrDefault(postName, 0) + 1);
        }

        // 构造岗位胜任统计列表
        List<PositionCompetencyStats> stats = new ArrayList<>();
        int totalUserCount = userIds.size();

        for (Map.Entry<String, Integer> entry : positionCountMap.entrySet()) {
            PositionCompetencyStats stat = new PositionCompetencyStats();
            stat.setPostName(entry.getKey());
            stat.setCompetentCount(entry.getValue());
            stat.setTotalCount(totalUserCount);

            // 计算胜任比例
            double percentage = (double) entry.getValue() / totalUserCount;
            stat.setPercentage(Math.round(percentage * 100.0) / 100.0); // 保留两位小数

            stats.add(stat);
        }

        this.value = stats;
    }

    @Override
    public void setResult(BaseModuleIndicatorResult result) {
        if (result instanceof IndicatorResult) {
            IndicatorResult indicatorResult = (IndicatorResult) result;
            if (value instanceof List) {
                List listValue = (List) value;
                if (!listValue.isEmpty()) {
                    Object firstElement = listValue.get(0);
                    if (firstElement instanceof PositionInfo) {
                        indicatorResult.setAvailablePositions(listValue);
                    } else if (firstElement instanceof PositionCompetencyStats) {
                        indicatorResult.setPositionCompetencyStats(listValue);
                    }
                }
            }
        }
    }
}