package com.malk.server.teambition;

import com.malk.utils.UtilMap;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 读取配置文件参考FilePah
 */
@Data
@Component
@ConfigurationProperties(prefix = "teambition")
public class TBConf {

    private String AppID;

    private String AppSecret;

    private String TenantId;

    private String OperatorId;

    private String ApiHost;

    public String getApiHost() {
        if (StringUtils.isNotBlank(ApiHost)) {
            return ApiHost;
        }
        return "https://open.teambition.com/api"; // 公有云环境
    }

    /**
     * 一个分页数量上限 [上限 1000]
     */
    public static final Integer PAGE_SIZE_LIMIT = 1000;

    /**
     * 租户类型: 默认是组织
     */
    public static final String TENANT_TYPE = "organization";

    /**
     * 推送事件验证
     */
    public static final String EVENT_VERIFY_HOOK = "VERIFY_HOOK";

    /// 获取任务字段值
    public static List<Map> getTaskFieldValue(List<Map> customfields, String fieldId) {

        Optional optional = customfields.stream().filter(item -> fieldId.equals(item.get("cfId"))).findAny();
        if (optional.isPresent()) {
            return UtilMap.getList((Map) optional.get(), "value");
        }
        return Arrays.asList();
    }

    /// 获取任务字段集合第一个值
    public static String getTaskFieldValue_First(List<Map> customfields, String fieldId) {

        List<Map> value = getTaskFieldValue(customfields, fieldId);
        if (value.size() > 0) {
            return String.valueOf(value.get(0).get("title"));
        }
        return "";
    }

    /// 更新任务自定义字段值 [ppExt: 富文本不能解析, 知识库可写入]
    public static Map assembleCustomField(String fieldName, String fieldValue, String value, Object meta) {
        Map body = UtilMap.map(fieldName, fieldValue);
        Map data = UtilMap.map("title", (Object) value);
        UtilMap.putNotNull(data, "meta", meta);
        body.put("value", Arrays.asList(data));
        return body;
    }

    public static Map assembleCustomFieldName(String fieldValue, String value) {
        return assembleCustomField("customfieldName", fieldValue, value, null);
    }

    public static Map assembleCustomFieldId(String fieldValue, String value) {
        return assembleCustomField("customfieldId", fieldValue, value, null);
    }
}
