package com.gic.haoban.manage.api.enums.contact;

import cn.hutool.core.date.DateUtil;
import com.gic.haoban.manage.api.dto.contact.ContactLogDTO;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

public enum ContactBizTypeEnum {

    // 业务类型 1潜客（0001）2机会人群（0010）

    POTENTIAL_CUSTOMER("10",1,"潜客"),
    OPPORTUNITY_CUSTOMER("20",2,"机会人群");

    private final String codePre;
    private final int type;
    private final String description;

    public String getCodePre() {
        return codePre;
    }

    public int getType() {
        return type;
    }

    public String getDescription() {
        return description;
    }

    public Long getEsClerkContactTime(Long contactTime) {
        if (Objects.equals(contactTime, -1L)) {
            return null;
        }
        return Long.parseLong(this.getCodePre() + contactTime);
    }

    public static List<Long> getEsClerkContactTimeList(List<ContactLogDTO> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        list = list.stream().sorted(Comparator.comparing(ContactLogDTO::getBizType))
                .collect(Collectors.toList());
        List<Long> clerkContactTimeList = Lists.newArrayList();
        Long maxContactTime = null;
        for (ContactLogDTO contactLogDTO : list) {
            Date contactTime = contactLogDTO.getContactTime();
            ContactBizTypeEnum bizTypeEnum = ContactBizTypeEnum.fromType(contactLogDTO.getBizType());
            Long orginalContactTimeLong = Long.parseLong(DateUtil.format(contactTime, "yyyyMMddHHmmss"));
            Long contactTimeLong = bizTypeEnum.getEsClerkContactTime(orginalContactTimeLong);
            clerkContactTimeList.add(contactTimeLong);
            if (maxContactTime == null || orginalContactTimeLong > maxContactTime) {
                maxContactTime = orginalContactTimeLong;
            }
        }
        if (maxContactTime != null) {
            clerkContactTimeList.add(maxContactTime);
        }
        return clerkContactTimeList;
    }

    ContactBizTypeEnum(String codePre, int type, String description) {
        this.codePre = codePre;
        this.type = type;
        this.description = description;
    }

    public static ContactBizTypeEnum fromCode(String code) {
        for (ContactBizTypeEnum type : values()) {
            if (Objects.equals(type.codePre,code)) {
                return type;
            }
        }
        return ContactBizTypeEnum.POTENTIAL_CUSTOMER;
    }

    public static ContactBizTypeEnum fromType(int type) {
        for (ContactBizTypeEnum bizTypeEnum : values()) {
            if (bizTypeEnum.type == type) {
                return bizTypeEnum;
            }
        }
        return ContactBizTypeEnum.POTENTIAL_CUSTOMER;
    }
}