package com.yeejoin.amos.boot.module.common.biz.refresh.cm;

import com.yeejoin.amos.boot.module.common.api.entity.EsBaseEnterpriseInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.ListUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
@RequiredArgsConstructor
public class BaseEnterpriseUpdate {

    public final String jyjcjg = "检验检测机构";
    public final String jyjg = "检验机构";
    public final String jcjg = "检测机构";
    public final String jyjgCode = "1233-1";
    public final String jcjgCode = "1233-2";

    public String updateJyjcUnitType(String oldUnitType, List<EsBaseEnterpriseInfo.License> unitLicences) {
         if(oldUnitType == null || oldUnitType.isEmpty()) {
             return oldUnitType;
         }
        // 如果单位类型中包含检验检测机构、检测单位、检验单位，且有资质信息，则更新单位类型
        if ((oldUnitType.contains(jyjcjg) || oldUnitType.contains(jyjg) || oldUnitType.contains(jcjg)) && !ListUtils.isEmpty(unitLicences)) {
            long jydwCount = unitLicences.stream().filter(e -> jyjgCode.equals(e.getCertTypeCode()) || jyjg.equals(e.getCertType())).count();
            long jcdwCount = unitLicences.stream().filter(e -> jcjgCode.equals(e.getCertTypeCode())  || jcjg.equals(e.getCertType())).count();
            // 如果资质中不含有检验和检测资质，则不更新单位类型
            if (jydwCount == 0 && jcdwCount == 0) {
                return oldUnitType;
            }
            // 处理旧的单位类型
            Set<String> units = Arrays.stream(oldUnitType.split("#")).collect(Collectors.toSet());
            units.remove(jyjcjg);
            units.remove(jyjg);
            units.remove(jcjg);
            if (jydwCount > 0) {
                units.add(jyjg);
            }
            if (jcdwCount > 0) {
                units.add(jcjg);
            }
            return String.join("#", units);
        } else {
            return oldUnitType;
        }
    }
}
