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.common.tenant.OrganContextHolder;
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.ExamOrganizationRelationDao;
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.enums.YesOrNoEnum;
import com.keao.edu.user.service.OrganizationService;
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 org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class OrganizationServiceImpl extends BaseServiceImpl<Integer, Organization> implements OrganizationService {
	
	@Autowired
	private OrganizationDao organDao;
	@Autowired
	private ImFeignService imFeignService;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private ExamOrganizationRelationDao examOrganizationRelationDao;

	@Override
	public BaseDAO<Integer, Organization> getDAO() {
		return organDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(Organization organ) {
		//获取当前用的organ
		SysUser queryUserInfo = sysUserFeignService.queryUserInfo();
		Organization currentOrganization = organDao.findByUserId(queryUserInfo.getId());
		if(currentOrganization == null){
			Integer organId = OrganContextHolder.getOrganId();
			currentOrganization = organDao.get(organId);
		}
		if(currentOrganization.getLevel() == 3){
			throw new BizException("无权限创建合作单位");
		}
		SysUser sysUser = organ.getSysUser();
//		String tenantId = queryUserInfo.getTenantId();
//		organ.setTenantId(tenantId);
//		sysUser.setTenantId(tenantId);
		SysUser user = sysUserDao.queryByPhone(sysUser.getPhone());
		organ.setParentOrganId(currentOrganization.getId());
		organ.setLevel(currentOrganization.getLevel() + 1);

		if(user != null && user.getId() != null){
//			if(!user.getTenantId().equals(tenantId)){
//				throw new BizException("手机号已被占用");
//			}
			if(StringUtils.isNotEmpty(user.getUserType())){
				throw new BizException("手机号已被占用");
			}
			Organization organization = organDao.findByUserId(user.getId());
			if(organization == null){
				if(StringUtils.isEmpty(user.getPassword())){
					sysUser.setPassword(new BCryptPasswordEncoder().encode("123456"));
				}
				organ.setUserId(user.getId());
				organDao.insert(organ);
				organ.setParentOrganIdTag(currentOrganization.getParentOrganIdTag() + "," + organ.getId());
				organDao.update(organ);
				//新增用户角色
				if(sysUser.getRoles() != null){
					sysUserDao.batchAddEmployeeRole(user.getId(),sysUser.getRoles());
				}else {
					Integer roleIds = sysUserDao.queryRoleIds(queryUserInfo.getId());
					sysUserDao.batchAddEmployeeRole(user.getId(),roleIds);
				}
				if(StringUtils.isNotEmpty(user.getUserType())){
					if(!user.getUserType().contains("SYSTEM")){
						user.setUserType(user.getUserType() + ",SYSTEM");
					}
				}else {
					user.setUserType("SYSTEM");
				}
				user.setRealName(organ.getContactName());
				user.setPhone(organ.getContactPhone());
				sysUserDao.update(user);
				Employee employee = employeeDao.get(user.getId());
				if(employee == null){
					employee = new Employee();
					employee.setOrganId(organ.getId());
					employee.setUserId(user.getId());
					employee.setTenantId(organ.getTenantId());
					employee.setEmployeeType("ORGAN");
					employeeDao.insert(employee);
				}else {
					employee.setDelFlag(false);
					employee.setOrganId(organ.getId());
					employee.setUserId(user.getId());
					employee.setTenantId(organ.getTenantId());
					employee.setEmployeeType("ORGAN");
					employeeDao.update(employee);
				}
			}else if(organization.getDelFlag() == YesOrNoEnum.YES){
				SysUser sysUser1 = organization.getSysUser();
				if(StringUtils.isEmpty(sysUser1.getUserType())){
					sysUser.setUserType("SYSTEM");
				}else {
					sysUser.setUserType(sysUser1.getUserType() + ",SYSTEM");
				}
				sysUser.setRealName(organ.getContactName());
				sysUser.setPhone(organ.getContactPhone());
				sysUser.setId(sysUser1.getId());
				sysUserDao.update(sysUser);
				if(sysUser.getRoles() != null){
					sysUserDao.batchAddEmployeeRole(sysUser.getId(),sysUser.getRoles());
				}else {
					Integer roleIds = sysUserDao.queryRoleIds(queryUserInfo.getId());
					sysUserDao.batchAddEmployeeRole(sysUser.getId(),roleIds);
				}
				Employee employee = employeeDao.get(sysUser.getId());
				employee.setDelFlag(false);
				employee.setTenantId(organ.getTenantId());
				employee.setEmployeeType("ORGAN");
				employee.setOrganId(organization.getId());
				employeeDao.update(employee);
				organ.setParentOrganIdTag(currentOrganization.getParentOrganIdTag() + "," + organization.getId());
				organ.setDelFlag(YesOrNoEnum.NO);
				organ.setId(organization.getId());
				organDao.update(organ);
			}else{
				throw new BizException("用户已存在");
			}
			return;
		}
		sysUser.setPassword(new BCryptPasswordEncoder().encode("123456"));
		sysUser.setUserType("SYSTEM");
		sysUser.setRealName(organ.getContactName());
		sysUser.setPhone(organ.getContactPhone());
		sysUserDao.insert(sysUser);

		organ.setUserId(sysUser.getId());
		organDao.insert(organ);
		organ.setParentOrganIdTag(currentOrganization.getParentOrganIdTag() + "," + organ.getId());
		organDao.update(organ);
		//新增用户角色
		sysUserDao.delEmployeeRole(sysUser.getId());
		if(sysUser.getRoles() != null){
			sysUserDao.batchAddEmployeeRole(sysUser.getId(),sysUser.getRoles());
		}else {
			Integer roleIds = sysUserDao.queryRoleIds(queryUserInfo.getId());
			sysUserDao.batchAddEmployeeRole(sysUser.getId(),roleIds);
		}
		Employee employee = new Employee();
		employee.setOrganId(organ.getId());
		employee.setUserId(sysUser.getId());
		employee.setTenantId(organ.getTenantId());
		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 updateOrganization(Organization organization) {
		SysUser sysUser = organization.getSysUser();
		Organization organization1 = organDao.get(organization.getId());
		if(null == organization1){
			throw new BizException("合作商信息不存在");
		}
		sysUser.setId(organization1.getUserId());
//		organization.setId(sysUser.getId());
		if(StringUtils.isNotEmpty(sysUser.getPhone())){
			SysUser queryByPhone = sysUserDao.queryByPhone(sysUser.getPhone());
			if(queryByPhone != null && !sysUser.getId().equals(queryByPhone.getId())){
				throw new BizException("手机号已存在");
			}
		}
		sysUser.setRealName(organization.getContactName());
		sysUser.setPhone(organization.getContactPhone());
		organization.setUserId(organization1.getUserId());
		organDao.update(organization);

		List<Organization> childOrgans = organDao.getChildOrgans(organization1.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 {
			SysUser queryUserInfo = sysUserFeignService.queryUserInfo();
			Integer roleIds = sysUserDao.queryRoleIds(queryUserInfo.getId());
			sysUserDao.batchAddEmployeeRole(sysUser.getId(),roleIds);
		}

		sysUserDao.update(sysUser);
		imFeignService.update(new ImUserModel(sysUser.getId().toString(),sysUser.getRealName(),sysUser.getAvatar()));
	}

	@Override
	public List<Integer> getChildOrganIds(Integer organId, boolean includeSelf) {
		if(Objects.isNull(organId)){
			return null;
		}
		Organization organization = organDao.get(organId);
		if(Objects.isNull(organization)){
			throw new BizException("当前声部不存在");
		}
		List<Integer> selfAndChildOrganIds = organDao.getChildOrganIds(organization.getParentOrganIdTag());
		if(null == selfAndChildOrganIds){
			selfAndChildOrganIds= Collections.EMPTY_LIST;
		}
		if(!includeSelf){
			selfAndChildOrganIds.remove(organization.getId());
		}
		if(CollectionUtils.isEmpty(selfAndChildOrganIds)){
			selfAndChildOrganIds.add(0);
		}
		return selfAndChildOrganIds;
	}

	@Override
	public List<Organization> getChildOrgans(Integer organId, boolean includeSelf) {
		Organization organization = organDao.get(organId);
		if(Objects.isNull(organization)){
			throw new BizException("合作单位不存在");
		}
		List<Organization> selfAndChildOrgans = organDao.getChildOrgans(organization.getParentOrganIdTag());
		if(null == selfAndChildOrgans){
			selfAndChildOrgans= Collections.EMPTY_LIST;
		}
		if(includeSelf){
			selfAndChildOrgans.add(organization);
		}
		return selfAndChildOrgans;
	}

	@Override
	public List<Integer> getNextLevelOrganIds(Integer organId, boolean includeSelf) {
		if(Objects.isNull(organId)){
			return null;
		}
		Organization organization = organDao.get(organId);
		if(Objects.isNull(organization)){
			throw new BizException("当前声部不存在");
		}
		List<Integer> selfAndChildOrganIds = organDao.getNextLevelOrganIds(organization.getId());
		if(null == selfAndChildOrganIds){
			selfAndChildOrganIds= Collections.EMPTY_LIST;
		}
		if(includeSelf){
			selfAndChildOrganIds.add(organization.getId());
		}
		if(CollectionUtils.isEmpty(selfAndChildOrganIds)){
			selfAndChildOrganIds.add(0);
		}
		return selfAndChildOrganIds;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void del(Integer id) {
		Organization organization = organDao.get(id);
		SysUser queryUserInfo = sysUserFeignService.queryUserInfo();
		if(queryUserInfo.getId().equals(organization.getUserId())){
			throw new BizException("删除失败：不支持此操作");
		}
		Integer count = examOrganizationRelationDao.findByOrganId(id);
		if(count == null || count == 0){
			SysUser sysUser = organization.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(organization.getUserId());
			employeeDao.delete(sysUser.getId());
			organDao.delete(id);
		}else {
			throw new BizException("删除失败：存在考试项目,无法删除");
		}
	}

	@Override
	public Organization getOrganization(Integer id) {
		Organization organization = organDao.get(id);
		SysUser sysUser = organization.getSysUser();
		Integer roleIds = sysUserDao.queryRoleIds(organization.getUserId());
		sysUser.setRoles(roleIds);
		return organization;
	}

	@Override
	public Organization findByUserId(Integer userId) {
		return organDao.findByUserId(userId);
	}
}
