package com.ym.mec.auth.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ym.mec.auth.api.entity.SysUserDevice;
import com.ym.mec.auth.dal.dao.SysUserDeviceDao;
import com.ym.mec.auth.service.SysUserDeviceService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.service.impl.BaseServiceImpl;

@Service
public class SysUserDeviceServiceImpl extends BaseServiceImpl<Integer, SysUserDevice>  implements SysUserDeviceService {
	
	@Autowired
	private SysUserDeviceDao sysUserDeviceDao;

	@Override
	public BaseDAO<Integer, SysUserDevice> getDAO() {
		return sysUserDeviceDao;
	}

	@Override
	public List<SysUserDevice> queryByUserId(Integer userId) {
		return sysUserDeviceDao.queryByUserId(userId);
	}

	@Override
	public List<SysUserDevice> queryByDeviceNum(String deviceNum) {
		return sysUserDeviceDao.queryByDeviceNum(deviceNum);
	}

	@Override
	public boolean bindDevice(Integer userId, String deviceNum) throws Exception {
		//查询设备号是否已存在
		List<SysUserDevice> sysUserDeviceList = sysUserDeviceDao.queryByDeviceNum(deviceNum);
		
		if (sysUserDeviceList != null && sysUserDeviceList.size() > 0) {
			if (sysUserDeviceList.stream().filter(sud -> sud.getUserId().equals(userId)).count() > 0) {
				return true;
			} else {
				throw new Exception("当前设备已绑定账号，请更换设备");
			}
		}
		
		SysUserDevice sysUserDevice = new SysUserDevice();
		sysUserDevice.setUserId(userId);
		sysUserDevice.setDeviceNum(deviceNum);
		sysUserDevice.setBindTime(new Date());
		sysUserDeviceDao.insert(sysUserDevice);
		
		return true;
	}
	
}