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


import com.keao.edu.auth.api.client.SysUserFeignService;
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.EmployeeDao;
import com.keao.edu.user.dao.OrganizationDao;
import com.keao.edu.user.dao.SysUserDao;
import com.keao.edu.user.entity.Employee;
import com.keao.edu.user.entity.Organization;
import com.keao.edu.user.service.EmployeeService;
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.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Integer, Employee> implements EmployeeService {
	
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private OrganizationDao organizationDao;
	@Autowired
	private ImFeignService imFeignService;
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysUserFeignService sysUserFeignService;

	@Override
	public BaseDAO<Integer, Employee> getDAO() {
		return employeeDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(Employee employee) {
		SysUser queryUserInfo = sysUserFeignService.queryUserInfo();
		Integer organId = employeeDao.get(queryUserInfo.getId()).getOrganId();
//		String tenantId = queryUserInfo.getTenantId();
		employee.setOrganId(organId);
		SysUser sysUser = employee.getSysUser();
//		employee.setTenantId(tenantId);
		SysUser user = sysUserDao.queryByPhone(sysUser.getPhone());
		if(user != null && user.getId() != null){
//			if(!user.getTenantId().equals(tenantId)){
//				throw new BizException("手机号已被占用");
//			}
			if(StringUtils.isNotEmpty(user.getUserType()) && user.getUserType().contains("SYSTEM")){
				throw new BizException("手机号已被占用");
			}
			Employee employee1 = employeeDao.get(user.getId());
			if(employee1 == null){
				if(StringUtils.isEmpty(user.getPassword())){
					sysUser.setPassword(new BCryptPasswordEncoder().encode("123456"));
				}
				employee.setUserId(user.getId());
				employee.setEmployeeType("EMPLOYEE");
				employeeDao.insert(employee);
				//新增用户角色
				sysUserDao.batchAddEmployeeRole(user.getId(),sysUser.getRoles());
				if(!user.getUserType().contains("SYSTEM")){
					user.setUserType(user.getUserType() + ",SYSTEM");
				}
				sysUserDao.update(user);
			}else if(employee1.getDelFlag()){
				SysUser sysUser1 = employee1.getSysUser();
				if(StringUtils.isEmpty(sysUser1.getUserType())){
					sysUser.setUserType("SYSTEM");
				}else {
					sysUser.setUserType(sysUser1.getUserType() + ",SYSTEM");
				}
				if(sysUser.getRoles() != null){
					sysUserDao.batchAddEmployeeRole(sysUser1.getId(),sysUser.getRoles());
				}
				sysUser.setId(sysUser1.getId());
				sysUserDao.update(sysUser);
				employee.setUserId(sysUser1.getId());
				employee.setDelFlag(false);
				employee.setEmployeeType("EMPLOYEE");
				employeeDao.update(employee);
			}else{
				throw new BizException("用户已存在");
			}
			return;
		}
//		sysUser.setTenantId(tenantId);
		sysUser.setPassword(new BCryptPasswordEncoder().encode("123456"));
		sysUser.setUserType("SYSTEM");
		sysUserDao.insert(sysUser);

		employee.setUserId(sysUser.getId());
		employee.setEmployeeType("EMPLOYEE");
		employeeDao.insert(employee);
		//新增用户角色
		sysUserDao.batchAddEmployeeRole(sysUser.getId(),sysUser.getRoles());
		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 updateEmployee(Employee employee) {
		SysUser sysUser = employee.getSysUser();
		sysUser.setId(employee.getUserId());
		if(null == employeeDao.get(sysUser.getId())){
			throw new BizException("员工信息不存在");
		}
		employee.setUserId(sysUser.getId());
		if(StringUtils.isNotEmpty(sysUser.getPhone())){
			SysUser queryByPhone = sysUserDao.queryByPhone(sysUser.getPhone());
			if(queryByPhone != null && !sysUser.getId().equals(queryByPhone.getId())){
				throw new BizException("手机号已存在");
			}
		}
		employee.setEmployeeType("EMPLOYEE");
		employeeDao.update(employee);

		Organization organization = organizationDao.findByUserId(employee.getUserId());
		if(organization != null){
			List<Organization> childOrgans = organizationDao.getChildOrgans(organization.getParentOrganIdTag());
			Set<Integer> userIds = childOrgans.stream().map(e -> e.getUserId()).collect(Collectors.toSet());
			userIds.add(sysUser.getId());

			sysUserDao.batchDelEmployeeRole(userIds);
			if(sysUser.getRoles() != null){
				sysUserDao.batchAddEmployeeRoles(userIds,sysUser.getRoles());
			}
		}else {
			sysUserDao.delEmployeeRole(sysUser.getId());
			sysUserDao.batchAddEmployeeRole(sysUser.getId(),sysUser.getRoles());
		}
		sysUserDao.update(sysUser);
		imFeignService.update(new ImUserModel(sysUser.getId().toString(),sysUser.getRealName(),sysUser.getAvatar()));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void del(Integer id) {
		SysUser queryUserInfo = sysUserFeignService.queryUserInfo();
		Employee employee = employeeDao.get(id);
		if(queryUserInfo.getId().equals(employee.getUserId())){
			throw new BizException("删除失败：不支持此操作");
		}

		SysUser sysUser = employee.getSysUser();
		String userType = sysUser.getUserType();
		if(userType.contains(",SYSTEM")){
			userType = userType.replace(",SYSTEM","");
		}else if(userType.contains("SYSTEM,")){
			userType = userType.replace("SYSTEM,","");
		}else {
			userType = "";
		}
		sysUserDao.updateUserType(sysUser.getId(),userType);
		sysUserDao.delEmployeeRole(employee.getUserId());
		employeeDao.delete(id);
	}

	@Override
	public Employee getEmployee(Integer id) {
		Employee employee = employeeDao.get(id);
		SysUser sysUser = employee.getSysUser();
        Integer roleIds = sysUserDao.queryRoleIds(sysUser.getId());
		sysUser.setRoles(roleIds);
		return employee;
	}
}