package com.ruoyi.device.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.device.domain.entity.TsbDevice;
import com.ruoyi.device.domain.entity.TsbUserDevice;
import com.ruoyi.device.domain.model.TsbUserDeviceBind;
import com.ruoyi.device.mapper.TsbDeviceMapper;
import com.ruoyi.device.mapper.TsbUserDeviceMapper;
import com.ruoyi.device.service.ITsbUserDeviceService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 调试宝设备用户绑定 业务层处理
 *
 * @author lwm
 */
@Service
public class TsbUserDeviceServiceImpl implements ITsbUserDeviceService
{
    @Autowired
    private TsbUserDeviceMapper tsbUserDeviceMapper;

    @Autowired
    private TsbDeviceMapper tsbDeviceMapper;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 查询用户与设备绑定列表（联表用户、设备）
     *
     * @param userDeviceBind 查询参数
     * @return 绑定关系集合信息
     */
    @Override
    public TsbUserDeviceBind selectTsbUserDeviceBind(TsbUserDeviceBind userDeviceBind)
    {
        if (userDeviceBind == null) {
            return null;
        }
        if (userDeviceBind.getUserId() == null && StringUtils.isEmpty(userDeviceBind.getUserName()) && StringUtils.isEmpty(userDeviceBind.getNickName())) {
            return null;
        }
        if (userDeviceBind.getDeviceId() == null && StringUtils.isEmpty(userDeviceBind.getImei()) && userDeviceBind.getDeviceSn() == null) {
            return null;
        }
        return tsbUserDeviceMapper.selectTsbUserDeviceBind(userDeviceBind);
    }

    /**
     * 查询指定设备当前绑定
     *
     * @param deviceId 设备ID
     * @return 绑定关系
     */
    @Override
    public TsbUserDeviceBind selectBindByDeviceId(Long deviceId)
    {
        return tsbUserDeviceMapper.selectBindByDeviceId(deviceId);
    }

    /**
     * 未绑定任何调试宝设备的用户列表（用于下拉）
     * 当前用户的可选择用户 再 去掉已经绑定的用户
     *
     * @return 用户列表
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysUser> selectUnbindUsers(TsbUserDevice bind)
    {
        return tsbUserDeviceMapper.selectUnbindUsers(bind);
    }

    /**
     * 用户与设备绑定
     *
     * @param userId   用户ID
     * @param deviceId 设备ID
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUserDevice(Long userId, Long deviceId)
    {
        SysUser user = userMapper.selectUserById(userId);
        if (user == null || UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            throw new ServiceException("用户不存在或已删除");
        }
        TsbDevice device = tsbDeviceMapper.selectTsbDeviceById(deviceId);
        if (device == null)
        {
            throw new ServiceException("设备不存在或已删除");
        }
        if (tsbUserDeviceMapper.selectByUserId(userId) != null)
        {
            throw new ServiceException("该用户已绑定设备，请先解绑");
        }
        if (tsbUserDeviceMapper.selectByDeviceId(deviceId) != null)
        {
            throw new ServiceException("该设备已被其他用户绑定");
        }
        TsbUserDevice row = new TsbUserDevice();
        row.setUserId(userId);
        row.setDeviceId(deviceId);
        row.setBindTime(DateUtils.getNowDate());
        return tsbUserDeviceMapper.insertTsbUserDevice(row);
    }

    /**
     * 用户与设备解绑
     *
     * @param userId   用户ID
     * @param deviceId 设备ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserDevice(Long userId, Long deviceId)
    {
        return tsbUserDeviceMapper.deleteUserDevice(userId, deviceId);
    }

    /**
     * 按用户ID批量删除设备绑定关系（删除用户前清理关联）
     *
     * @param userIds 用户ID数组
     * @return 影响行数
     */
    @Override
    @Transactional
    public int deleteByUserIds(Long[] userIds)
    {
        if (userIds == null || userIds.length == 0)
        {
            return 0;
        }
        return tsbUserDeviceMapper.deleteTsbUserDeviceByUserIds(userIds);
    }
}
