package com.njcn.cssystem.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.cssystem.mapper.AppMsgSetMapper;
import com.njcn.cssystem.pojo.po.AppMsgSet;
import com.njcn.cssystem.service.IAppMsgSetService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 设备发送短信配置表 服务实现类
 * </p>
 *
 * @author xy
 * @since 2026-04-21
 */
@Service
public class AppMsgSetServiceImpl extends ServiceImpl<AppMsgSetMapper, AppMsgSet> implements IAppMsgSetService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUserDevices(String userId, List<String> deviceIds) {
        // 先删除该用户的所有设备关联
        deleteByUserId(userId);
        // 如果设备列表为空，直接返回
        if (CollectionUtils.isEmpty(deviceIds)) {
            return;
        }

        // 批量插入新的设备关联
        List<AppMsgSet> relationList = new ArrayList<>();
        for (String deviceId : deviceIds) {
            AppMsgSet relation = new AppMsgSet();
            relation.setId(IdUtil.fastSimpleUUID());
            relation.setUserId(userId);
            relation.setDeviceId(deviceId);
            relationList.add(relation);
        }
        this.saveBatch(relationList);
    }

    @Override
    public void deleteByUserId(String userId) {
        LambdaQueryWrapper<AppMsgSet> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppMsgSet::getUserId, userId);
        this.remove(wrapper);
    }

    @Override
    public List<String> queryDeviceIdsByUserId(String userId) {
        LambdaQueryWrapper<AppMsgSet> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppMsgSet::getUserId, userId);
        wrapper.select(AppMsgSet::getDeviceId);

        List<AppMsgSet> relationList = this.list(wrapper);
        List<String> deviceIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(relationList)) {
            for (AppMsgSet relation : relationList) {
                deviceIds.add(relation.getDeviceId());
            }
        }
        return deviceIds;
    }


    @Override
    public List<String> queryUserIdsByDeviceId(String deviceId) {
        LambdaQueryWrapper<AppMsgSet> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppMsgSet::getDeviceId, deviceId);
        wrapper.select(AppMsgSet::getUserId);

        List<AppMsgSet> relationList = this.list(wrapper);
        List<String> userIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(relationList)) {
            for (AppMsgSet relation : relationList) {
                userIds.add(relation.getUserId());
            }
        }
        return userIds;
    }


}
