package com.gic.haoban.manage.service.service.content.adaptor;

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.enterprise.api.constant.EnterpriseServiceEnum;
import com.gic.enterprise.api.dto.EnterpriseUsingPermissionDto;
import com.gic.enterprise.api.dto.enterprise.EnterpriseUsingStatusDTO;
import com.gic.enterprise.api.service.EnterpriseUseForbidService;
import com.gic.haoban.manage.api.enums.contact.ContactBizTypeEnum;
import com.gic.redis.data.util.RedisUtil;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * @Author MUSI
 * @Date 2023/4/2 10:05 PM
 * @Description
 * @Version
 **/
@Slf4j
@Component
public class EnterpriseAdaptor {

    @Getter
    @AllArgsConstructor
    public enum MaterialLevel {
        LOW(1, "低版本"),
        HIGH(2, "高版本");
        private Integer code;
        private String desc;
    }

    private static final Long cache_hour_sec = 5 * 60L;

    /**
     * 销售线索处理微盟订单的服务
     */
    public static final List<String> rightCodeList = Lists.newArrayList(
            EnterpriseServiceEnum.POTENTIAL.getRightMenuCode(),
            EnterpriseServiceEnum.CONTENT.getRightMenuCode(),
            EnterpriseServiceEnum.GOODS_ANALYSIS.getRightMenuCode()
    );

    public static final List<String> newRightCodeList = Lists.newArrayList(
            EnterpriseServiceEnum.POTENTIAL.getRightMenuCode(),
            EnterpriseServiceEnum.CONTENT.getRightMenuCode()
    );

    @Autowired
    EnterpriseUseForbidService enterpriseUseForbidService;

    /**
     * @see MaterialLevel
     * @param highLevel 1 低版本; 2高版本
     * @return
     */
    public List<String> queryHasRightEnterpriseIds(Integer highLevel) {

        ServiceResponse<List<EnterpriseUsingStatusDTO>> serviceResponse = enterpriseUseForbidService.getUseEnterpriseByCode(EnterpriseServiceEnum.CONTENT.getRightMenuCode(), null);
        if (!serviceResponse.isSuccess()) {
            log.info("查询企业信息异常 {}", JSON.toJSONString(serviceResponse));
            return Collections.emptyList();
        }
        log.info("有权限的企业 {}", JSON.toJSONString(serviceResponse));
        return serviceResponse.getResult()
                .stream()
                .filter(item -> item.getVersion() != null && item.getVersion() >= highLevel)
                .filter(item -> Boolean.TRUE.equals(item.getVaild()))
                .map(EnterpriseUsingStatusDTO::getEnterpriseId)
                .collect(Collectors.toList());
    }

    public Map<String, List<String>> getWeekMonthEid() {
        ServiceResponse<List<EnterpriseUsingStatusDTO>> serviceResponse1 =
                enterpriseUseForbidService.getUseEnterpriseByCode(EnterpriseServiceEnum.CONTENT.getRightMenuCode(), null);
        ServiceResponse<List<EnterpriseUsingStatusDTO>> serviceResponse2 =
                enterpriseUseForbidService.getUseEnterpriseByCode(EnterpriseServiceEnum.POTENTIAL.getRightMenuCode(), null);

        if (!serviceResponse1.isSuccess() || !serviceResponse2.isSuccess()) {
            return Collections.emptyMap();
        }

        Map<String, List<String>> map = new HashMap<>();

        // 处理内容相关企业ID
        Optional.ofNullable(serviceResponse1.getResult()).orElse(Collections.emptyList())
                .stream()
                .filter(item -> item.getVersion() != null && item.getVersion() >= EnterpriseAdaptor.MaterialLevel.LOW.getCode())
                .filter(item -> Boolean.TRUE.equals(item.getVaild()))
                .map(EnterpriseUsingStatusDTO::getEnterpriseId)
                .forEach(eid -> map.computeIfAbsent(eid, k -> new ArrayList<>())
                        .add(EnterpriseServiceEnum.CONTENT.getRightMenuCode()));

        // 处理潜客相关企业ID
        Optional.ofNullable(serviceResponse2.getResult()).orElse(Collections.emptyList())
                .stream()
                .filter(item -> Boolean.TRUE.equals(item.getVaild()))
                .map(EnterpriseUsingStatusDTO::getEnterpriseId)
                .forEach(eid -> map.computeIfAbsent(eid, k -> new ArrayList<>())
                        .add(EnterpriseServiceEnum.POTENTIAL.getRightMenuCode()));

        return map;
    }

    /**
     * 校验企业是否有内容权限
     * @param enterpriseId
     * @return
     */
    public boolean checkEnterpriseHasContentRight(String enterpriseId) {
        String key = "haoban_enterprise_content:" + enterpriseId;
        String cache = RedisUtil.getCache(key, String.class);
        if (StringUtils.isBlank(cache)) {
            cache = "0";
            ServiceResponse<List<EnterpriseUsingStatusDTO>> tempServiceResponse = enterpriseUseForbidService.getUseEnterpriseByCode(EnterpriseServiceEnum.CONTENT.getRightMenuCode(), enterpriseId);
            if (!tempServiceResponse.isSuccess() || CollectionUtils.isEmpty(tempServiceResponse.getResult())) {
                log.info("企业 {} 没有内容权限 {}", enterpriseId, JSON.toJSONString(tempServiceResponse));
                RedisUtil.setCache(key, cache, cache_hour_sec, TimeUnit.SECONDS);
                return false;
            }
            EnterpriseUsingStatusDTO enterpriseUsingStatusDTO = tempServiceResponse.getResult().get(0);
            if (!Boolean.TRUE.equals(enterpriseUsingStatusDTO.getVaild())) {
                log.info("企业 {} 内容权限已失效 {}", enterpriseId, JSON.toJSONString(tempServiceResponse));
                RedisUtil.setCache(key, cache, cache_hour_sec, TimeUnit.SECONDS);
                return false;
            }
            cache = "1";
            RedisUtil.setCache(key, cache, cache_hour_sec, TimeUnit.SECONDS);
        }
        return StringUtils.equals(cache, "1");
    }

    public boolean checkEnterpriseHasRightByContactBizType(String enterpriseId,Integer contactBizType) {
        if (Objects.equals(contactBizType, ContactBizTypeEnum.POTENTIAL_CUSTOMER.getType())) {
            return checkEnterpriseHasRights(enterpriseId,Lists.newArrayList(EnterpriseServiceEnum.POTENTIAL.getRightMenuCode()));
        } else if (Objects.equals(contactBizType, ContactBizTypeEnum.OPPORTUNITY_CUSTOMER.getType())) {
            return checkEnterpriseHasRights(enterpriseId,Lists.newArrayList(EnterpriseServiceEnum.OBJECTIVES.getRightMenuCode()));
        } else {
            return checkEnterpriseHasRights(enterpriseId, Lists.newArrayList(EnterpriseServiceEnum.POTENTIAL.getRightMenuCode()))
                    || checkEnterpriseHasRights(enterpriseId, Lists.newArrayList(EnterpriseServiceEnum.OBJECTIVES.getRightMenuCode()));
        }
    }

    public boolean checkEnterpriseHasRight(String enterpriseId,String rightMenuCode) {
        return checkEnterpriseHasRights(enterpriseId,Lists.newArrayList(rightMenuCode));
    }

    public boolean checkEnterpriseHasRights(String enterpriseId,List<String> rightMenuCodes) {
        String key = "haoban_enterprise_menuCode:" + enterpriseId + ":" + String.join(":", rightMenuCodes);
        String cache = RedisUtil.getCache(key, String.class);
        if (StringUtils.isBlank(cache)) {
            List<EnterpriseUsingPermissionDto> list = enterpriseUseForbidService.selectUsingEnterprisePermissionByEnterpriseId(enterpriseId);
            if (CollectionUtils.isEmpty(list)) {
                return false;
            }
            List<String> hasList = list.stream().map(EnterpriseUsingPermissionDto::getRightMenuCode).collect(Collectors.toList());
            hasList = hasList.stream().filter(rightMenuCodes::contains).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(hasList)) {
                cache = "0";
            }else {
                cache = "1";
            }
            RedisUtil.setCache(key, cache, cache_hour_sec, TimeUnit.SECONDS);
        }
        return StringUtils.equals(cache, "1");
    }
}
