package com.neusoft.smart.pos.org.repository;

import com.neusoft.smart.pos.org.persistent.domain.OrganizationGroup;
import com.neusoft.smart.pos.org.persistent.domain.OrganizationGroupExample;
import com.neusoft.smart.pos.org.persistent.domain.OrganizationGroupRelationExample;
import com.neusoft.smart.pos.org.persistent.mapper.OrganizationGroupMapper;
import com.neusoft.smart.pos.org.persistent.mapper.OrganizationGroupRelationMapper;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
public class OrgGroupRepository {

	@Autowired
	public OrganizationGroupMapper orgGroupMapper;

	@Autowired
	public OrganizationGroupRelationMapper orgGroupRelationMapper;

	public OrganizationGroup queryOrgGroupById(int id) {
		val emp = new OrganizationGroupExample();
		emp.createCriteria().andIdEqualTo(id);
		val orgGroups = orgGroupMapper.selectByExample(emp);
		return orgGroups.size() > 0? orgGroups.get(0):null;
	}

	public OrganizationGroup queryOrgGroupByEntityTable(String entity, int id) {
		val emp = new OrganizationGroupExample();
		emp.createCriteria().andEntityTableIdEqualTo(id).andEntityTableNameLike(entity);
		val orgGroups = orgGroupMapper.selectByExample(emp);
		return orgGroups.size() > 0? orgGroups.get(0):null;
	}

	public List<OrganizationGroup> queryOrgGroupParents(int childOrgGroupId) {
		val emp = new OrganizationGroupRelationExample();
		emp.createCriteria().andChildidEqualTo(childOrgGroupId);
		val relations = orgGroupRelationMapper.selectByExample(emp);
		List<OrganizationGroup> parents = new ArrayList<>();
		relations.forEach(relation -> {
			if(relation != null && relation.getParentid() >= 0) {
				val orgGroup = queryOrgGroupById(relation.getParentid());
				if(orgGroup != null) { //TODO:可能需要检查父组织是否激活？
					parents.add(orgGroup);
				}
			}
		});
		return parents;
	}

	public int insertSelective(OrganizationGroup orgGroup){
		return orgGroupMapper.insertSelective(orgGroup);
	}

	public int updateByPrimaryKeySelective(OrganizationGroup orgGroup){
		return orgGroupMapper.updateByPrimaryKeySelective(orgGroup);
	}


	public int countByCondi(int childId, int parentId){
		val emp = new OrganizationGroupRelationExample();
		emp.createCriteria().andChildidEqualTo(childId);
		if(parentId >= 0) {
			emp.createCriteria().andParentidEqualTo(parentId);
		}
		return orgGroupRelationMapper.countByExample(emp);
	}
}
