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.page.PageInfo;
import com.keao.edu.common.page.QueryInfo;
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.EmployeeDao;
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.dto.TenantInfoDto;
import com.keao.edu.user.entity.Employee;
import com.keao.edu.user.entity.Organization;
import com.keao.edu.user.entity.TenantInfo;
import com.keao.edu.user.service.TenantInfoService;
import com.keao.edu.util.collection.MapUtil;
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 org.springframework.transaction.annotation.Transactional;

import java.util.*;

@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;
	@Autowired
	private EmployeeDao employeeDao;

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

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addTenant(TenantInfoDto 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("SYSTEM");
		sysUser.setRealName(tenantInfo.getContactName());
		sysUser.setAvatar(tenantInfo.getLogoUrl());
		sysUser.setPhone(tenantInfo.getContactPhone());
		sysUserDao.insert(sysUser);
		if(tenantInfo.getRoleIds() != null){
//			Set<Integer> roleIds = Arrays.stream(tenantInfo.getRoleIds().split(",")).map(e -> Integer.valueOf(e)).collect(Collectors.toSet());
			sysUserDao.batchAddEmployeeRole(sysUser.getId(), tenantInfo.getRoleIds());
		}

		Organization organ=new Organization();
		organ.setUserId(sysUser.getId());
		organ.setTenantId(tenantInfo.getId().toString());
		organ.setParentOrganId(sysUser.getId());
		organ.setLevel(0);
		organ.setParentOrganIdTag(sysUser.getId().toString());
		organ.setId(sysUser.getId());
		organ.setName(tenantInfo.getName());
		organ.setContactName(tenantInfo.getContactName());
		organ.setContactPhone(tenantInfo.getContactPhone());
		organizationDao.insert(organ);

		Employee employee = new Employee();
		employee.setOrganId(organ.getId());
		employee.setUserId(sysUser.getId());
		employee.setTenantId(tenantInfo.getId().toString());
		employee.setEmployeeType("ORGAN");
		employeeDao.insert(employee);

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

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateTenant(TenantInfoDto newTenantInfo) {
		TenantInfo existTenantInfo = tenantInfoDao.get(newTenantInfo.getId());
		if(Objects.isNull(existTenantInfo)){
			throw new BizException("机构不存在");
		}
		SysUser sysUser = sysUserDao.queryByPhone(existTenantInfo.getContactPhone());
		if(sysUser == null){
			throw new BizException("用户信息异常");
		}
		if(!newTenantInfo.getContactPhone().equals(sysUser.getPhone())){
			if (sysUserDao.queryByPhone(newTenantInfo.getContactPhone()) != null) {
				throw new BizException("手机号已被占用");
			}
		}
		Organization organization = organizationDao.findByUserId(sysUser.getId());
		if(newTenantInfo.getRoleIds() != null){
			//删除当前用户角色
			sysUserDao.delEmployeeRole(sysUser.getId());
			//新增用户角色
			sysUserDao.batchAddEmployeeRole(sysUser.getId(),newTenantInfo.getRoleIds());
		}
		if(StringUtils.isNotBlank(newTenantInfo.getContactName())){
			sysUser.setRealName(newTenantInfo.getContactName());
			organization.setContactName(newTenantInfo.getContactName());
			organization.setName(newTenantInfo.getName());
		}
		if(StringUtils.isNotBlank(newTenantInfo.getContactPhone())){
			sysUser.setPhone(newTenantInfo.getContactPhone());
			organization.setContactPhone(newTenantInfo.getContactPhone());
		}
		organizationDao.update(organization);
		sysUserDao.update(sysUser);
		imFeignService.update(new ImUserModel(sysUser.getId().toString(),sysUser.getRealName(),sysUser.getAvatar()));
		tenantInfoDao.update(newTenantInfo);
	}

	@Override
	public PageInfo<TenantInfoDto> queryTenants(QueryInfo queryInfo) {
		PageInfo<TenantInfoDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<String, Object>();
		MapUtil.populateMap(params, queryInfo);

		List<TenantInfoDto> dataList = new ArrayList<>();
		int count = tenantInfoDao.countTenants(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = tenantInfoDao.queryTenants(params);
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}
}
