package com.ym.mec.biz.service.impl;

import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.EmployeeDao;
import com.ym.mec.biz.dal.dao.OrganizationDao;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.dao.TenantInfoDao;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.entity.Organization;
import com.ym.mec.biz.dal.entity.Teacher;
import com.ym.mec.biz.dal.entity.TenantInfo;
import com.ym.mec.biz.dal.enums.FivePlusGradeEnum;
import com.ym.mec.biz.dal.enums.GradeTypeEnum;
import com.ym.mec.biz.dal.enums.SixPlusGradeEnum;
import com.ym.mec.biz.dal.page.EducationBaseQueryInfo;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.common.tenant.TenantContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.ym.mec.biz.dal.enums.SysUserRoleEnum.EDUCATION;

@Service
public class OrganizationServiceImpl extends BaseServiceImpl<Integer, Organization> implements OrganizationService {

	@Autowired
	private OrganizationDao organizationDao;
	@Autowired
	private TenantInfoService tenantInfoService;
	@Autowired
	private TeacherDao teacherDao;
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysEmployeePositionService employeePositionService;
	@Autowired
    @Lazy
	private ContractService contractService;
	@Autowired
	private TenantInfoDao tenantInfoDao;
	
	@Autowired
	private TenantContractTemplateService tenantContractTemplateService;

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

	@Override
	public List<Organization> queryEmployeeOrgan(){
		SysUser sysUser = sysUserService.getUser();
		String organIds = this.getEmployeeOrgan(sysUser.getId(), "", sysUser.getIsSuperAdmin());
		return organizationDao.queryEmployeeOrgan(organIds);
	}

	@Override
	public List<Organization> queryAllOrganWithNoAuth(Integer tenantId) {
		return organizationDao.findAllOrgans(tenantId);
	}

	@Override
	public List<Organization> queryEmployeeOrganByUser(){
		return this.queryEmployeeOrgan();
	}

	@Override
	public String getOrganName(String organId) {
		return organizationDao.getOrganName(organId);
	}


	@Override
	public Map<Integer, String> getGradeList(Integer id) {
		Organization organization = organizationDao.get(id);
		Map<Integer, String> gradeMap = new HashMap<>();

		if(Objects.isNull(organization)){
			gradeMap.put(GradeTypeEnum.SIX_PLUS.getCode(), GradeTypeEnum.SIX_PLUS.getDesc());
			return gradeMap;
		}

		if(organization.getGradeType().equals(GradeTypeEnum.FIVE_PLUS)){
			FivePlusGradeEnum[] fivePlusGradeEnums = FivePlusGradeEnum.values();
			for (FivePlusGradeEnum fivePlusGradeEnum : fivePlusGradeEnums) {
				gradeMap.put(fivePlusGradeEnum.getCode(),fivePlusGradeEnum.getDesc());
			}
		}
		if(organization.getGradeType().equals(GradeTypeEnum.SIX_PLUS)){
			SixPlusGradeEnum[] sixPlusGradeEnums = SixPlusGradeEnum.values();
			for (SixPlusGradeEnum sixPlusGradeEnum : sixPlusGradeEnums) {
				gradeMap.put(sixPlusGradeEnum.getCode(),sixPlusGradeEnum.getDesc());
			}
		}
		return gradeMap;
	}

	@Override
	public String getEmployeeOrgan(Integer userId, String organIds,Boolean isSuper) {
		if(StringUtils.isEmpty(organIds)){
			Integer tenantId = TenantContextHolder.getTenantId();
			TenantInfo tenantInfo = tenantInfoService.get(tenantId);
			//如果是超管，或者是机构管理员，可以查看当前机构所有分部数据
			if(isSuper || (tenantInfo.getUserId() != null && tenantInfo.getUserId().equals(userId))){
				Map<String,Object> param = new HashMap<>();
				param.put("tenantId",tenantId);
				List<Organization> all = this.findAll(param);
				if(all != null && all.size() > 0){
					organIds = StringUtils.join(all.stream().map(e->e.getId()).collect(Collectors.toSet()),",");
				}
			}
		}
		if(StringUtils.isEmpty(organIds)){
			Employee employee = employeeDao.get(userId);
			organIds = employee.getOrganIdList();
		}
		return organIds;
	}

	@Override
	public String getEmployeeOrgan(Object organIds) {
		SysUser sysUser = sysUserService.getUser();
		return this.getEmployeeOrgan(sysUser.getId(),organIds == null?"":organIds.toString(),sysUser.getIsSuperAdmin());
	}

	@Override
	public String getTeacherOrgan() {
		Teacher teacher = teacherDao.get(sysUserService.getUserId());
		String organIds = teacher.getTeacherOrganId() + "";
		if(StringUtils.isNotBlank(teacher.getFlowOrganRange())){
			organIds = organIds + "," + teacher.getFlowOrganRange();
		}
		return organIds;
	}

	@Override
	public List<Organization> findAllOrgans(Integer tenantId) {
		return organizationDao.findAllOrgans(tenantId);
	}

	@Override
	public List<Organization> findOrgans(List<Integer> organIds,Integer tenantId) {
		return organizationDao.getOrgans(organIds,tenantId);
	}

    @Override
	public List<Organization> queryEmployeeOrgan(String organId) {
		return organizationDao.queryEmployeeOrgan(organId);
	}

	@Override
    public <T extends EducationBaseQueryInfo> T onlyEducation(T queryInfo) {
		SysUser sysUser = sysUserService.getUser();
		queryInfo.setOrganIds(this.getEmployeeOrgan(sysUser.getId(),queryInfo.getOrganIds(),sysUser.getIsSuperAdmin()));
		Boolean onlyForRole = employeePositionService.onlyForRole(EDUCATION, sysUser.getId(), sysUser.getIsSuperAdmin());
		//如果当前用户只有教务老师角色，那么只能看到他所管理的课程组的信息
		if (onlyForRole) {
			queryInfo.setEducationUserId(sysUser.getId());
		}
		return queryInfo;
    }

	@Override
	@Transactional
	public boolean updateBasicInfo(Organization organization) {
		
		Organization orginOrgan = get(organization.getId());
		
		if(orginOrgan == null){
			throw new BizException("分部原始信息查询失败");
		}
		
		update(organization);
		
		//是否修改了机构名称或机构编码
        if (!StringUtils.equals(orginOrgan.getCorporateName(), organization.getCorporateName()) || !StringUtils.equals(orginOrgan.getCorporateCode(), organization.getCorporateCode())) {
        	
        	Integer tenantId = organization.getTenantId();
            //升级机构协议版本号
            tenantContractTemplateService.upgradeContractVersion(tenantId);
            
			if (StringUtils.isNotBlank(organization.getCorporateName()) && StringUtils.isNotBlank(organization.getCorporateCode())) {
				// 添加签章信息
				contractService.addTsign(organization.getId(), organization.getCorporateCode(), organization.getCorporateName(), tenantId);
			}
        }
		
		return true;
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
    public Long add(Organization organization) {
		long insert = organizationDao.insert(organization);
		TenantInfo tenantInfo = tenantInfoDao.selectById(organization.getTenantId());
		Integer userId = sysUserService.getUserId();
		if(!userId.equals(tenantInfo.getUserId())){
			updateOrganId(tenantInfo.getUserId(),organization.getId());
		}
		updateOrganId(userId,organization.getId());
		return insert;
    }

	@Transactional(rollbackFor = Exception.class)
    public void updateOrganId(Integer userId,Integer organId){
		Employee employee = employeeDao.get(userId);
		String organIdList = employee.getOrganIdList();
		if(StringUtils.isNotEmpty(organIdList)){
			employee.setOrganIdList(new StringBuffer(organIdList).append(",").append(organId).toString());
		}else {
			employee.setOrganIdList(organId+"");
		}
		employeeDao.update(employee);
	}

}
