package com.keao.edu.auth.service.impl;

import com.keao.edu.auth.api.dto.SysUserInfo;
import com.keao.edu.auth.api.entity.LoginEntity;
import com.keao.edu.auth.api.entity.SysUser;
import com.keao.edu.auth.dal.dao.SysUserDao;
import com.keao.edu.auth.service.SysRoleMenuService;
import com.keao.edu.auth.service.SysUserRoleService;
import com.keao.edu.auth.service.SysUserService;
import com.keao.edu.common.dal.BaseDAO;
import com.keao.edu.common.exception.BizException;
import com.keao.edu.common.service.impl.BaseServiceImpl;
import com.keao.edu.im.api.client.ImFeignService;
import com.keao.edu.im.api.entity.ImResult;
import com.keao.edu.im.api.entity.ImUserModel;
import com.keao.edu.user.api.client.EduUserFeignService;
import com.keao.edu.user.api.entity.Student;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class SysUserServiceImpl extends BaseServiceImpl<Integer, SysUser> implements SysUserService {

	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleMenuService sysRoleMenuService;
	@Autowired
	private ImFeignService imFeignService;
	@Autowired
	private EduUserFeignService eduUserFeignService;

	@Override
	public BaseDAO<Integer, SysUser> getDAO() {
		return sysUserDao;
	}

	@Override
	public SysUser queryByUsername(String username) {
		return sysUserDao.queryByUsername(username);
	}

	@Override
	public SysUser queryByPhone(String phone) {
		return sysUserDao.queryByPhone(phone);
	}

	@Override
	public SysUser queryByPhoneAndClient(String phone,String client) {
		return sysUserDao.queryByPhoneAndClient(phone,client);
	}

	@Override
	public SysUserInfo queryUserInfoByUsername(String username) {
		return getSysUserInfo(queryByUsername(username));
	}

	@Override
	public SysUserInfo queryUserInfoByPhone(String phone,String clientId) {
		return getSysUserInfo(queryByPhoneAndClient(phone,clientId));
	}

	@Override
	public SysUserInfo queryUserInfoByPhoneAndClient(String phone,String client) {
		return getSysUserInfo(queryByPhoneAndClient(phone,client));
	}

	private SysUserInfo getSysUserInfo(SysUser sysUser) {
		if (sysUser == null) {
			return null;
		}
		SysUserInfo userInfo = new SysUserInfo();
		userInfo.setSysUser(sysUser);

		List<String> roleCodeList = sysUserRoleService.queryRoleCodeListByUserId(sysUser.getId());
		userInfo.setRoles(roleCodeList.toArray(new String[roleCodeList.size()]));

		List<Integer> roleIdList = sysUserRoleService.queryRoleIdListByUserId(sysUser.getId());
		List<String> permissionList = sysRoleMenuService.queryPermissionsByRoleIdList(roleIdList);

		userInfo.setPermissions(permissionList.toArray(new String[permissionList.size()]));

		return userInfo;
	}

	@Override
	public boolean deleteById(Integer id) {
		SysUser user = get(id);
		if (user == null) {
			throw new BizException("账户不存在");
		}
		user.setUpdateTime(new Date());
		user.setDelFlag(1);

		update(user);

		return true;
	}

	@Override
	public void updatePassword(String mobile, String password) {
		sysUserDao.updatePassword(mobile,password);
	}

	@Override
	public Integer add(SysUser sysUser) {
		sysUserDao.insert(sysUser);
		ImResult imResult = imFeignService.register(new ImUserModel(sysUser.getId().toString(), sysUser.getUsername(), sysUser.getAvatar()));
		sysUser.setImToken(imResult.getToken());
		sysUserDao.update(sysUser);
		return sysUser.getId();
	}

	@Override
	public ImUserModel getBasic(Integer userId) {
		return sysUserDao.getBasic(userId);
	}

	@Override
	public void updateBaseInfo(SysUser sysUser) {
		sysUserDao.update(sysUser);
		imFeignService.update(new ImUserModel(sysUser.getId().toString(),sysUser.getRealName()==null?sysUser.getUsername():sysUser.getRealName(),sysUser.getAvatar()));
	}

	@Override
	public SysUser queryUserInfo(Integer userId) {
		return sysUserDao.get(userId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void refreshImToken(SysUser sysUser) {
		sysUserDao.refreshImToken(sysUser.getId(),sysUser.getImToken());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public SysUserInfo initUser(LoginEntity loginEntity) {
		if(StringUtils.equalsIgnoreCase(loginEntity.getClientId(),"STUDENT")){
			eduUserFeignService.studentApply(loginEntity.getOrganId(),loginEntity.getPhone());
			return queryUserInfoByPhone(loginEntity.getPhone(),loginEntity.getClientId());
		}else {
			throw new UsernameNotFoundException("404.9");
		}
	}

	@Override
	public Integer queryUserTenantId(String clientId, Integer userId) {
		if(StringUtils.equalsIgnoreCase(clientId,"SYSTEM")){
			return sysUserDao.getEmployeeTenantId(userId);
		}else if(StringUtils.equalsIgnoreCase(clientId,"TEACHER")){
			return sysUserDao.getTeacherTenantId(userId);
		}
		return null;
	}

	@Override
	public Integer queryUserOrganId(String clientId, Integer userId) {
		if(StringUtils.equalsIgnoreCase(clientId,"SYSTEM")){
			return sysUserDao.getEmployeeOrganId(userId);
		}else if(StringUtils.equalsIgnoreCase(clientId,"TEACHER")){
			return sysUserDao.getTeacherOrganId(userId);
		}
		return null;
	}

}
