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

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ym.mec.auth.api.dto.SysUserInfo;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.auth.api.enums.YesOrNoEnum;
import com.ym.mec.auth.dal.dao.SysUserDao;
import com.ym.mec.auth.service.SysRoleMenuService;
import com.ym.mec.auth.service.SysUserRoleService;
import com.ym.mec.auth.service.SysUserService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.entity.ImResult;
import com.ym.mec.common.entity.ImUserModel;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.IdGeneratorService;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.im.ImFeignService;
import com.ym.mec.im.WebFeignService;

@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 WebFeignService userFeignService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private IdGeneratorService smsCodeService;

	@Value("${auth.sysconfig.tenantId}")
	private Integer lesseeOrganId;

	@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) {
		return getSysUserInfo(queryByPhone(phone));
	}

	@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(YesOrNoEnum.YES);

		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 SysUserInfo initUser(String phone, String clientId) {
		if(StringUtils.equalsIgnoreCase(clientId,"TEACHER")){
			SysUser sysUser = new SysUser();
			sysUser.setPhone(phone);
			sysUser.setUserType("TEACHER");
			sysUserDao.insert(sysUser);
			//添加用户现金账户
			imFeignService.register(new ImUserModel(sysUser.getId().toString(),phone,null));
			userFeignService.createCashAccount(sysUser.getId());
			//sysTenantAccount
			sysUserDao.insertSysTenantAccount(sysUser.getId());
			//创建teacher表
			sysUserDao.insertTeacher(sysUser.getId(),lesseeOrganId);
			return queryUserInfoByPhone(phone);
		}else if(StringUtils.equalsIgnoreCase(clientId,"STUDENT")){
			SysUser sysUser = new SysUser();
			sysUser.setPhone(phone);
			sysUser.setUserType("STUDENT");
			sysUser.setOrganId(lesseeOrganId);
			sysUserDao.insert(sysUser);
			sysUserService.saveStudent(sysUser.getId());
			//添加用户现金账户
			imFeignService.register(new ImUserModel(sysUser.getId().toString(),phone,null));
			userFeignService.createCashAccount(sysUser.getId());
			return queryUserInfoByPhone(phone);
		}
		return null;
	}

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

	@Override
	public void saveStudent(Integer userId) {
		sysUserDao.saveStudent(userId);
	}

	@Override
	public void saveTeacher(Integer userId) {
		sysUserDao.insertTeacher(userId, lesseeOrganId);
	}

	@Override
	public Integer getLesseeOrganId() {
		return lesseeOrganId;
	}

}
