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

import com.yeejoin.amos.boot.module.common.api.entity.EsBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.common.api.entity.EsUserInfo;
import org.thymeleaf.util.ListUtils;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class RefreshCmService {

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

    public static 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)) {
            long jydwCount = 0L;
            long jcdwCount = 0L;
            if (!ListUtils.isEmpty(unitLicences)) {
                jydwCount = unitLicences.stream().filter(e -> jyjgCode.equals(e.getCertTypeCode()) || jyjg.equals(e.getCertType())).count();
                jcdwCount = unitLicences.stream().filter(e -> jcjgCode.equals(e.getCertTypeCode()) || jcjg.equals(e.getCertType())).count();
            }
            // 如果资质中不包含检测机构但历史的单位类型中包含检验检测机构，将此单位类型修改为检测机构
            if (jcdwCount == 0 && oldUnitType.contains(jyjcjg)) {
                jydwCount += 1;
            }
            // 如果资质中不含有检验和检测资质，则不更新单位类型
            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;
        }
    }

    public static LocalDate getMinDateFromLicensesEp(List<EsBaseEnterpriseInfo.License> licenses) {
        if (licenses == null || licenses.isEmpty()) {
            return null;
        }
        return licenses.stream().map(EsBaseEnterpriseInfo.License::getExpiryDate).filter(Objects::nonNull).min(LocalDate::compareTo).orElse(null);
    }

    public static LocalDate getMinDateFromLicensesUser(List<EsUserInfo.License> licenses) {
        if (licenses == null || licenses.isEmpty()) {
            return null;
        }
        return licenses.stream().map(EsUserInfo.License::getExpiryDate).filter(Objects::nonNull).min(LocalDate::compareTo).orElse(null);
    }
}
