package com.cusc.nirvana.user.rnr.fp.service.impl;

import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.eiam.client.OrganizationClient;
import com.cusc.nirvana.user.eiam.dto.OrganizationDTO;
import com.cusc.nirvana.user.rnr.fp.constants.OrganBizzTypeEnum;
import com.cusc.nirvana.user.rnr.fp.service.IOrganService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * Description:组织操作service实现类
 * <br />
 * CreateDate 2022-07-06 19:33:31
 *
 * @author yuyi
 **/
@Service
@Slf4j
public class OrganServiceImpl implements IOrganService {

    @Resource
    private OrganizationClient organizationClient;

    @Override
    public Response<OrganizationDTO> getCarSubOrganByOrgId(OrganizationDTO bean) {
        //根据组织id查询组织信息
        OrganizationDTO organ = new OrganizationDTO();
        organ.setUuid(bean.getUuid());
        organ.setTenantNo(bean.getTenantNo());
        Response<OrganizationDTO> organResp = organizationClient.getByUuid(organ);
        if (!organResp.isSuccess()) {
            return Response.createError(organResp.getMsg(), organResp.getCode());
        }
        organ = organResp.getData();
        return getCarSubOrganByQueryCodePrivate(organ);
    }

    @Override
    public Response<OrganizationDTO> getCarSubOrganByQueryCodePrivate(OrganizationDTO bean) {
        //根据当前组织的查询编码查询组织信息
        List<String> uuidList = Arrays.asList(bean.getQueryCode().split("-"));
        OrganizationDTO organSub = new OrganizationDTO();
        organSub.setTenantNo(bean.getTenantNo());
        organSub.setUuidList(uuidList);
        Response<List<OrganizationDTO>> orgListResp = organizationClient.queryByList(organSub);
        if (!orgListResp.isSuccess()) {
            return Response.createError(orgListResp.getMsg(), orgListResp.getCode());
        }
        if (CollectionUtils.isEmpty(orgListResp.getData())) {
            return Response.createSuccess();
        }

        for (OrganizationDTO tmp : orgListResp.getData()) {
            if (OrganBizzTypeEnum.CAR_FACTORY.getCode() == tmp.getBizType().intValue()
                    || OrganBizzTypeEnum.CAR_SUB_ORGAN.getCode() == tmp.getBizType().intValue()) {
                return Response.createSuccess(tmp);
            }
        }
        return Response.createSuccess();
    }
}
