package com.zhongshu.card.server.core.service.devices.permiss;

import com.google.common.collect.Lists;
import com.zhongshu.card.client.type.DataState;
import com.zhongshu.card.server.core.dao.devices.DeviceInfoDao;
import com.zhongshu.card.server.core.dao.devices.DevicePermissDao;
import com.zhongshu.card.server.core.domain.devices.DeviceInfo;
import com.zhongshu.card.server.core.domain.devices.permiss.DevicePermiss;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 *
 * @author TRX
 * @date 2025/3/25
 */
@Slf4j
@Service
public class UserCanUseDeviceService {

    @Autowired
    private DevicePermissService devicePermissService;

    @Autowired
    private DeviceInfoDao deviceInfoDao;

    @Autowired
    private DevicePermissDao devicePermissDao;

    public List<String> getUserDeviceIds(String projectOid, String userId) {
        if (StringUtils.isNotEmpty(projectOid) && StringUtils.isNotEmpty(userId)) {
            return getUserDeviceIds(projectOid, List.of(userId));
        }
        return Lists.newArrayList();
    }

    /**
     * 得到用户在项目中可以使用的设备列表
     * @param  projectOid
     * @param  userIds
     * @return deviceIds
     */
    public List<String> getUserDeviceIds(String projectOid, List<String> userIds) {
        List<String> deviceIds = new ArrayList<String>();
        if (StringUtils.isNotEmpty(projectOid) && ObjectUtils.isNotEmpty(userIds)) {
            //step1: 在 “设备权限” 里直接配置的数据
            List<String> deviceIds1 = devicePermissService.getUserAllDeviceIds(projectOid, userIds);
            if (ObjectUtils.isNotEmpty(deviceIds1)) {
                deviceIds.addAll(deviceIds1);
            }

            //todo step2: 在设备权限规则里，动态的数据（不好找，时间段在变化）
        }
        return deviceIds;
    }

    /**
     * 得到设备关联的 所有用户userIds （全量）
     * @param  deviceId
     * @return userIds
     */
    public List<String> getDeviceUserIds(String deviceId) {
        if (StringUtils.isEmpty(deviceId)) {
            return Lists.newArrayList();
        }
        DeviceInfo deviceInfo = deviceInfoDao.findTopByDeviceId(deviceId);
        if (ObjectUtils.isEmpty(deviceInfo)) {
            return Lists.newArrayList();
        }
        List<String> userIds = new ArrayList<>();

        String projectOid = deviceInfo.getProjectOid();
        //step1: 在 “设备权限” 里直接配置的数据
        List<DevicePermiss> permisses = devicePermissDao.findByDeviceIdInAndDataState(List.of(deviceId), DataState.Enable);
        if (ObjectUtils.isNotEmpty(permisses)) {
            List<String> _userIds = permisses.stream().map(DevicePermiss::getUserId).collect(Collectors.toList());
            userIds.addAll(_userIds);
        }

        //todo 其他权限 （如：设备规则）

        return userIds;
    }

}
