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

import com.neusoft.smart.pos.dto.org.response.PostOrgGroupResponse;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.org.constants.OrgShopErrorCode;
import com.neusoft.smart.pos.org.persistent.domain.OrganizationGroup;
import com.neusoft.smart.pos.org.repository.OrgGroupRepository;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrgGroupService {

    @Resource
    public OrgGroupRepository orgGroupRepository;

    public PostOrgGroupResponse selectOrgGroupById(String entity, int id) {
        OrganizationGroup orgGroup;
        if(StringUtils.isEmpty(entity)) {
            orgGroup = orgGroupRepository.queryOrgGroupById(id);
        } else {
            orgGroup = getOrgGroup(entity, id);
        }

        val result = new PostOrgGroupResponse();
        BeanUtils.copyProperties(orgGroup,result);
        return result;
    }

    public int updateOrgGroupStatus(String entity, int id, String status) {
        val orgGroup = getOrgGroup(entity, id);
        orgGroup.setStatus(status);
        return orgGroupRepository.updateByPrimaryKeySelective(orgGroup);
    }

    public int countParentsByCondi(String entity, int id) {
        val orgGroup = getOrgGroup(entity, id);
        return orgGroupRepository.countByCondi(orgGroup.getId(), -1);
    }

    public boolean isChildOfParent(String entity, int id, int parentId) {
        val orgGroup = getOrgGroup(entity, id);
        return orgGroupRepository.countByCondi(orgGroup.getId(), parentId) > 0;
    }

    public List<PostOrgGroupResponse> getOrgGroupParents(String entity, int id) {
        val orgGroup = getOrgGroup(entity, id);
        val parents =  orgGroupRepository.queryOrgGroupParents(orgGroup.getId());
        List<PostOrgGroupResponse> results = new ArrayList<>();
        parents.forEach( parent -> {
            val response = new PostOrgGroupResponse();
            BeanUtils.copyProperties(parent, response);
            results.add(response);
        });
        return results;
    }

    private OrganizationGroup getOrgGroup(String entity, int id) {
        val orgGroup = orgGroupRepository.queryOrgGroupByEntityTable(entity, id);
        if(orgGroup == null) {
            throw new BusinessCommonException(OrgShopErrorCode.INVALID_ORG_ID);
        }
        return orgGroup;
    }
}
