package com.sunyard.chsm.model;

import lombok.Data;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotEmpty;
import java.util.Arrays;
import java.util.List;

/**
 * @author liulu
 * @since 2024/10/29
 */
@Data
public class Subject {

    private static final List<String> keys = Arrays.asList("C", "ST", "L", "O", "OU", "CN");

    private static final String COMMA = ",";

    /**
     * 通用名
     */
    @NotEmpty(message = "通用名不能为空")
    private String commonName;
    /**
     * 国家
     */
    private String country;
    /**
     * 省份
     */
    private String province;
    /**
     * 城市
     */
    private String city;
    /**
     * 组织
     */
    private String org;
    /**
     * 部门
     */
    private String orgUnit;


    public String getDN() {
        Assert.notNull(commonName, "通用名不能为空");
        StringBuilder builder = new StringBuilder();
        if (StringUtils.hasText(commonName)) {
            builder.append("CN=").append(commonName).append(COMMA);
        }
        if (StringUtils.hasText(orgUnit)) {
            builder.append("OU=").append(orgUnit).append(COMMA);
        }
        if (StringUtils.hasText(org)) {
            builder.append("O=").append(org).append(COMMA);
        }
        if (StringUtils.hasText(city)) {
            builder.append("L=").append(city).append(COMMA);
        }
        if (StringUtils.hasText(province)) {
            builder.append("ST=").append(province).append(COMMA);
        }
        if (StringUtils.hasText(country)) {
            builder.append("C=").append(country).append(COMMA);
        }
        builder.deleteCharAt(builder.lastIndexOf(COMMA));
        return builder.toString();
    }

    public static Subject fromDN(String dn) {
        Assert.hasText(dn, "dn不能为空值");
        Subject subject = new Subject();
        String[] splits = dn.trim().split(",");
        for (String split : splits) {
            String trim = split.trim();

            if (trim.startsWith("C=")) {
                subject.setCountry(trim.split("=")[1]);
            }
            if (trim.startsWith("ST=")) {
                subject.setProvince(trim.split("=")[1]);
            }
            if (trim.startsWith("L=")) {
                subject.setCity(trim.split("=")[1]);
            }
            if (trim.startsWith("O=")) {
                subject.setOrg(trim.split("=")[1]);
            }
            if (trim.startsWith("OU=")) {
                subject.setOrgUnit(trim.split("=")[1]);
            }
            if (trim.startsWith("CN=")) {
                subject.setCommonName(trim.split("=")[1]);
            }
        }
        Assert.notNull(subject.commonName, "通用名不能为空");
        return subject;
    }


}
