package com.artfess.device.base.manager.impl;

import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.device.base.dao.DeviceGroupInfoDao;
import com.artfess.device.base.dao.DeviceRelationGroupDao;
import com.artfess.device.base.manager.DeviceGroupInfoManager;
import com.artfess.device.base.model.DeviceGroupInfo;
import com.artfess.device.base.model.DeviceInfo;
import com.artfess.device.base.model.DeviceRelationGroup;
import com.artfess.device.base.vo.DeviceGroupVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

/**
 * 设备分组信息 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author min.wu
 * @since 2022-07-15
 */
@Service
public class DeviceGroupInfoManagerImpl extends BaseManagerImpl<DeviceGroupInfoDao, DeviceGroupInfo> implements DeviceGroupInfoManager {

    @Resource
    private DeviceRelationGroupDao deviceRelationGroupDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindDevice(DeviceGroupVo t) {
        Assert.hasText(t.getGroupId(), "请选择要绑定的设备分组");
        QueryWrapper<DeviceRelationGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id_", t.getGroupId());
        this.deviceRelationGroupDao.delete(queryWrapper);

        t.getDeviceIds().forEach(deviceId -> {
            DeviceRelationGroup deviceRelationGroup = new DeviceRelationGroup();
            deviceRelationGroup.setDeviceId(deviceId);
            deviceRelationGroup.setGroupId(t.getGroupId());
            deviceRelationGroupDao.insert(deviceRelationGroup);
        });
    }

    @Override
    public DeviceGroupVo getDeviceList(DeviceGroupVo t) {
        List<DeviceInfo> list = this.deviceRelationGroupDao.getDeviceList(t.getGroupId());
        t.setDeviceList(list);
        return t;
    }
}
