package com.kym.service.admin.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.kym.common.utils.CommUtil;
import com.kym.entity.admin.EquipmentInfo;
import com.kym.entity.admin.queryParams.EquipmentQueryParam;
import com.kym.entity.common.PageBean;
import com.kym.mapper.admin.EquipmentInfoMapper;
import com.kym.service.admin.EquipmentInfoService;
import com.kym.service.utils.KymCache;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Map;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;

/**
 * <p>
 * 充电桩桩体设备 服务实现类
 * </p>
 *
 * @author skyline
 * @since 2023-08-05
 */
@Service
@DS("db-admin")
public class EquipmentInfoServiceImpl extends ServiceImpl<EquipmentInfoMapper, EquipmentInfo> implements EquipmentInfoService {

    private final KymCache kymCache;

    public EquipmentInfoServiceImpl(@Lazy KymCache kymCache) {
        this.kymCache = kymCache;
    }

    @Override
    public PageBean<EquipmentInfo> listEquipment(EquipmentQueryParam params) {
        // 判断数据权限
        var adminStationId = kymCache.getAdminUserStationId(StpUtil.getLoginIdAsLong());
        if (adminStationId != null) {
            params.setStationId(adminStationId);
        }
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        var equipmentInfos = lambdaQuery()
                .eq(isNotNull(params.getEquipmentId()), EquipmentInfo::getEquipmentId, params.getEquipmentId())
                .eq(isNotNull(params.getStationId()), EquipmentInfo::getStationId, params.getStationId())
                .eq(isNotNull(params.getStatus()), EquipmentInfo::getNetStatus, params.getStatus())
                .list();
        var page = new PageBean<>(equipmentInfos);
        // TODO: 2023-09-02  parallelStream 这里可能有坑，注意检查
        var res = equipmentInfos.parallelStream().map(item ->
                        item.setShortId(kymCache.getShortId(item.getEquipmentId())).setStationName(kymCache.getStationName(item.getStationId()))
                )
                .toList().stream().sorted(Comparator.comparing(EquipmentInfo::getShortId)).toList();
        page.setList(res);
        return page;
    }

    @Override
    public Map<Integer, Long> statEquipmentStatus(String stationId) {
        if (CommUtil.null2Long(stationId) <= 0) {
            // 判断数据权限
            stationId = kymCache.getAdminUserStationId(StpUtil.getLoginIdAsLong());
        }
        // 获取指定站点下的充电桩
        var equipmentInfos = lambdaQuery().eq(isNotNull(stationId), EquipmentInfo::getStationId, stationId).list();
        // 根据状态进行分组
        return equipmentInfos.stream().collect(Collectors.groupingBy(EquipmentInfo::getServiceStatus, Collectors.counting()));
    }
}
