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

import com.keao.edu.auth.api.entity.SysUser;
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.dao.OrganizationDao;
import com.keao.edu.user.dao.SysUserDao;
import com.keao.edu.user.dao.TenantInfoDao;
import com.keao.edu.user.entity.Organization;
import com.keao.edu.user.entity.TenantInfo;
import com.keao.edu.user.service.TenantInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class TenantInfoServiceImpl extends BaseServiceImpl<Integer, TenantInfo> implements TenantInfoService {
	
	@Autowired
	private TenantInfoDao tenantInfoDao;
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private OrganizationDao organizationDao;
	@Autowired
	private ImFeignService imFeignService;

	@Override
	public BaseDAO<Integer, TenantInfo> getDAO() {
		return tenantInfoDao;
	}

	@Override
	public void addTenant(TenantInfo tenantInfo) {
		if(StringUtils.isBlank(tenantInfo.getContactPhone())){
			throw new BizException("请填写手机号码");
		}
		SysUser userWithPhone = sysUserDao.queryByPhone(tenantInfo.getContactPhone());
		if(Objects.nonNull(userWithPhone)){
			throw new BizException("手机号已被占用");
		}

		tenantInfoDao.insert(tenantInfo);

		SysUser sysUser = new SysUser();
		sysUser.setTenantId(tenantInfo.getId().toString());
		sysUser.setPassword(new BCryptPasswordEncoder().encode("123456"));
		sysUser.setUserType("ORGAN");
		sysUser.setRealName(tenantInfo.getName());
		sysUser.setAvatar(tenantInfo.getLogoUrl());
		sysUser.setPhone(tenantInfo.getContactPhone());
		sysUserDao.insert(sysUser);

		Organization organ=new Organization();
		organ.setTenantId(tenantInfo.getId().toString());
		organ.setParentOrganId(sysUser.getId());
		organ.setLevel(0);
		organ.setParentOrganIdTag(sysUser.getId().toString());
		organ.setId(sysUser.getId());
		organizationDao.insert(organ);

		ImResult imResult = imFeignService.register(new ImUserModel(sysUser.getId().toString(), sysUser.getRealName(),null));
		sysUser.setImToken(imResult.getToken());
		sysUserDao.update(sysUser);
	}
}
