package com.yonge.cooleshow.auth.service.impl;

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

import com.yonge.cooleshow.auth.dal.dao.SysConfigDao;
import com.yonge.toolset.mybatis.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;

import com.yonge.cooleshow.auth.api.entity.SysUserDevice;
import com.yonge.cooleshow.auth.dal.dao.SysUserDeviceDao;
import com.yonge.cooleshow.auth.service.SysUserDeviceService;
import com.yonge.toolset.mybatis.dal.BaseDAO;

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

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

	@Override
	public List<SysUserDevice> queryByUserId(String clientId, Long userId) {
		return sysUserDeviceDao.queryByUserId(clientId, userId);
	}

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

	@Override
	public boolean bindDevice(String clientId, Long userId, String deviceNum) {
		String paramName;
		if (StringUtils.equalsIgnoreCase(clientId, "STUDENT")) {
			paramName = "student_device_acc_num";
		} else if (StringUtils.equalsIgnoreCase(clientId, "TEACHER")) {
			paramName = "teacher_device_acc_num";
		}else {
			return true;
		}
		String configValue = sysConfigDao.findConfigValue(paramName);
		if(StringUtils.isEmpty(configValue)){
			return true;
		}
		// 检查学生是否绑定了多个设备号
		List<SysUserDevice> studentDeviceList = queryByUserId(clientId, userId);

		if (studentDeviceList == null) {
			studentDeviceList = new ArrayList<SysUserDevice>();
		}

		List<String> deviceList = studentDeviceList.stream().map(t -> t.getDeviceNum()).collect(Collectors.toList());

		if (!deviceList.contains(deviceNum)) {
			if (deviceList.size() >= Integer.parseInt(configValue)) {
				throw new BadCredentialsException("登录失败：该账号已达到设备绑定数量上限");
			}
			SysUserDevice sysUserDevice = new SysUserDevice();
			sysUserDevice.setUserId(userId);
			sysUserDevice.setDeviceNum(deviceNum);
			sysUserDevice.setBindTime(new Date());
			sysUserDevice.setClientId(clientId);
			sysUserDeviceDao.insert(sysUserDevice);
		}
		return true;
	}

	@Override
	public boolean deleteWithLogic(Long id) {
		
		SysUserDevice sysUserDevice = sysUserDeviceDao.get(id);
		if(sysUserDevice != null){
			sysUserDevice.setDelFlag(true);
			
			sysUserDeviceDao.update(sysUserDevice);
		}
		
		return true;
	}
	
}