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.ExamOrganizationRelationDao;
import com.keao.edu.user.dao.OrganizationDao;
import com.keao.edu.user.dao.SysUserDao;
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 java.util.Collections;
import java.util.List;
import java.util.Objects;

@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 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.get(queryUserInfo.getId());
		//获取父级的organ
		if(organ.getIsAllowArrangeExam() == YesOrNoEnum.YES){
			if(currentOrganization.getIsAllowArrangeExam() == YesOrNoEnum.NO){
				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(queryUserInfo.getId());
		organ.setLevel(currentOrganization.getLevel() + 1);

		if(user != null && user.getId() != null){
			Organization organization = organDao.get(user.getId());
			if(organization == null){
				organ.setParentOrganIdTag(currentOrganization.getParentOrganIdTag() + "," + user.getId());
				if(StringUtils.isEmpty(user.getPassword())){
					sysUser.setPassword(new BCryptPasswordEncoder().encode("123456"));
				}
				organ.setUserId(user.getId());
				organDao.insert(organ);
				//新增用户角色
				if(sysUser.getRoles() != null && sysUser.getRoles().size() > 0){
					sysUserDao.batchAddEmployeeRole(user.getId(),sysUser.getRoles());
				}
				user.setUserType(user.getUserType() + ",ORGAN");
				user.setRealName(organ.getName());
				user.setPhone(organ.getContactPhone());
				sysUserDao.update(user);
			}else if(organization.getDelFlag() == YesOrNoEnum.YES){
				organization.setDelFlag(YesOrNoEnum.NO);
				organDao.update(organization);
			}else{
				throw new BizException("用户已存在");
			}
			return;
		}
		sysUser.setPassword(new BCryptPasswordEncoder().encode("123456"));
		sysUser.setUserType("ORGAN");
		sysUser.setRealName(organ.getName());
		sysUser.setPhone(organ.getContactPhone());
		sysUserDao.insert(sysUser);

		organ.setParentOrganIdTag(currentOrganization.getParentOrganIdTag() + "," + sysUser.getId());
		organ.setUserId(sysUser.getId());
		organDao.insert(organ);
		//新增用户角色
		sysUserDao.delEmployeeRole(sysUser.getId());
		if(sysUser.getRoles() != null && sysUser.getRoles().size() > 0){
			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 updateOrganization(Organization organization) {
		SysUser sysUser = organization.getSysUser();
		sysUser.setId(organization.getUserId());
		if(null == organDao.get(sysUser.getId())){
			throw new BizException("合作商信息不存在");
		}
//		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.getName());
		sysUser.setPhone(organization.getContactPhone());
		organDao.update(organization);
		//删除当前用户角色
		sysUserDao.delEmployeeRole(sysUser.getId());
		//新增用户角色
		if(sysUser.getRoles() != null && sysUser.getRoles().size() > 0){
			sysUserDao.batchAddEmployeeRole(sysUser.getId(),sysUser.getRoles());
		}
		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());
		}
		return selfAndChildOrganIds;
	}

	@Override
	public List<Organization> getChildOrgans(Integer organId) {
		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;
		}
		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());
		}
		return selfAndChildOrganIds;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void del(Integer id) {
		Integer count = examOrganizationRelationDao.findByOrganId(id);
		if(count == null || count == 0){
			organDao.delete(id);
		}else {
			throw new BizException("删除失败：存在考试项目,无法删除");
		}
	}
}
