package com.hz.pm.api.organization.helper.impl;

import com.hz.pm.api.organization.helper.GovBusinessStripHelper;
import com.hz.pm.api.organization.model.entity.DingOrganization;
import com.hz.pm.api.organization.service.IDingOrganizationService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author liuxinxin
 * @date 2023/3/8 下午3:34
 */

@Component
@RequiredArgsConstructor
public class GovBusinessStripHelperImpl implements GovBusinessStripHelper {

    private final IDingOrganizationService organizationService;

    @Override
    public List<DingOrganization> getSupGovBusinessStrip(String organizationCode) {
        List<DingOrganization> supGovBusinessStripList = new ArrayList<>();

        DingOrganization dingOrganization = organizationService.getByOrgCode(organizationCode);
        if (Objects.isNull(dingOrganization)) {
            return Collections.emptyList();
        }
        String businessStripCodes = dingOrganization.getBusinessStripCodes();
        if (StringUtils.isNotBlank(businessStripCodes)) {
            String[] businessStripCodeList = businessStripCodes.split("\\|");
            for (String businessStripCode : businessStripCodeList) {
                DingOrganization supGovBusinessStrip = getSupGovBusinessStrip(dingOrganization.getOrganizationCode(), businessStripCode);
                if (Objects.nonNull(supGovBusinessStrip)) {
                    supGovBusinessStripList.add(supGovBusinessStrip);
                }
            }
        }
        return supGovBusinessStripList;
    }

    private DingOrganization getSupGovBusinessStrip(String organizationCode, String businessStripCode) {
        String tempParentOrgCode = organizationCode;

        HashSet<String> tempParentOrgCodeSet = new HashSet<>();
        while (true) {
            if (StringUtils.isBlank(tempParentOrgCode)) {
                return null;
            }
            // 防止脏数据导致死循环
            if (!tempParentOrgCodeSet.add(tempParentOrgCode)) {
                return null;
            }
            DingOrganization parentOrganization = organizationService.getParentOrganization(tempParentOrgCode);
            if (Objects.isNull(parentOrganization)) {
                return null;
            }
            String businessStripCodes = parentOrganization.getBusinessStripCodes();
            if (StringUtils.isNotBlank(businessStripCode) && businessStripCodes.contains(businessStripCode)) {
                return parentOrganization;
            }
            tempParentOrgCode = parentOrganization.getParentCode();
        }
    }

    @Override
    public DingOrganization getSupMainManageOrganization(String organizationCode) {
        return null;
    }
}
