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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.hologres.client.HoloClient;
import com.alibaba.hologres.client.Put;
import com.alibaba.hologres.client.model.TableSchema;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.dto.ClerkListDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.enterprise.api.constant.EnterpriseServiceEnum;
import com.gic.enterprise.api.dto.enterprise.EnterpriseUsingStatusDTO;
import com.gic.enterprise.api.service.EnterpriseUseForbidService;
import com.gic.haoban.app.customer.dto.ChildDTO;
import com.gic.haoban.app.customer.dto.CustomerDTO;
import com.gic.haoban.app.customer.dto.FilterListDTO;
import com.gic.haoban.app.customer.dto.MemberInfoListParamsDTO;
import com.gic.haoban.app.customer.dto.contact.ContactParamDTO;
import com.gic.haoban.app.customer.dto.contact.ContactSumDTO;
import com.gic.haoban.app.customer.service.api.service.CustomerApiService;
import com.gic.haoban.common.utils.DateUtil;
import com.gic.haoban.manage.api.enums.contact.ContactBizTypeEnum;
import com.gic.haoban.manage.service.dao.mapper.content.holo.HoloDataSource;
import com.gic.haoban.manage.service.pojo.bo.contact.ContactDataBO;
import com.gic.store.goods.dto.potential.PlatformPotentialCustomerOutDTO;
import com.gic.store.goods.service.potential.PlatformPotentialCustomerApiService;
import com.google.common.collect.Lists;
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.stream.Collectors;

/**
 * Created by wangzubo on 2025/4/14.
 */
@Slf4j
@Component
public class ContactAdaptor {

    @Autowired
    private EnterpriseUseForbidService enterpriseUseForbidService;
    @Autowired
    private ClerkService clerkService ;
    @Autowired
    private PlatformPotentialCustomerApiService platformPotentialCustomerApiService;
    @Autowired
    private CustomerApiService customerService;
    @Autowired
    private HoloDataSource holoDataSource;

    /**
     * 潜客商户定时刷新
     */
    public void contactDataTimer() {
        // 处理潜客相关企业ID
        ServiceResponse<List<EnterpriseUsingStatusDTO>> serviceResponse =
                enterpriseUseForbidService.getUseEnterpriseByCode(EnterpriseServiceEnum.POTENTIAL.getRightMenuCode(), null);
        List<ContactDataBO> list = new ArrayList<>();
        List<String> eidList = Optional.ofNullable(serviceResponse.getResult()).orElse(Collections.emptyList())
                .stream()
                .filter(item -> Boolean.TRUE.equals(item.getVaild()))
                .map(EnterpriseUsingStatusDTO::getEnterpriseId).collect(Collectors.toList());
        ContactDataBO contactDataBO = null;
        for (String eid : eidList) {
            log.info("开始处理潜客数据eid:{}", eid);
            Set<String> storeIdSet = new HashSet<>();
            List<ClerkListDTO> enterpriseClerk = clerkService.getEnterpriseClerk(eid);
            if (CollectionUtils.isEmpty(enterpriseClerk)) {
                continue;
            }
            log.info("潜客数据导购数:{}", enterpriseClerk.size());
            for (int i = 0; i < enterpriseClerk.size(); i++) {
                ClerkListDTO clerk = enterpriseClerk.get(i);
                // 无归属导购数据
                if (storeIdSet.add(clerk.getStoreId())) {
                    contactDataBO = new ContactDataBO();
                    contactDataBO.setEnterpriseId(clerk.getEnterpriseId());
                    contactDataBO.setClerkId("-1");
                    contactDataBO.setStoreId(clerk.getStoreId());
                    list.add(contactDataBO);
                }
                contactDataBO = new ContactDataBO();
                contactDataBO.setEnterpriseId(clerk.getEnterpriseId());
                contactDataBO.setClerkId(clerk.getClerkId());
                contactDataBO.setStoreId(clerk.getStoreId());
                list.add(contactDataBO);
                if (list.size() >= 100 || i == enterpriseClerk.size() - 1) {
                    try {
                        String jsonString = JSON.toJSONString(list);
                        GICMQClientUtil.getClientInstance().sendMessage("contactDataRefreshMQ", jsonString);
                        jsonString = null;
                    } catch (Exception e) {
                        log.error("发送MQ异常:",e);
                    }
                    list.clear();
                }
            }
        }
    }

    /**
     * 定时刷新未建联数到holo
     * @param param
     */
    public void contactDataRefresh(String param) {
        List<ContactDataBO> list = JSONObject.parseArray(param, ContactDataBO.class);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        ContactDataBO contactDataBO = list.get(0);
        String enterpriseId = contactDataBO.getEnterpriseId();
        ServiceResponse<PlatformPotentialCustomerOutDTO> potentialResponse = platformPotentialCustomerApiService.getPotentialCustomerOutRule(enterpriseId);
        if (!potentialResponse.isSuccess() || potentialResponse.getResult() == null) {
            return;
        }
        List<String> clerkIdList = list.stream().map(ContactDataBO::getClerkId).collect(Collectors.toList());
        List<ClerkDTO> clerkDTOS = clerkService.getClerkByClerkIds(new HashSet<>(clerkIdList));
        Map<String, ClerkDTO> clerkMap = Optional.ofNullable(clerkDTOS).orElse(new ArrayList<>()).stream().collect(Collectors.toMap(ClerkDTO::getClerkId, clerkDTO -> clerkDTO));
        for (ContactDataBO dataBO : list) {
            boolean unassigned = Objects.equals(dataBO.getClerkId(), "-1");
            ClerkDTO clerkDTO = clerkMap.get(dataBO.getClerkId());
            Integer noConnPotCusNum = getNoConnPotCusNum(potentialResponse.getResult(), dataBO.getEnterpriseId(), dataBO.getStoreId(), clerkDTO, unassigned);
            log.info("clerkId:{},noConnPotCusNum:{}", dataBO.getClerkId(), noConnPotCusNum);
            dataBO.setNoConnPotCusNum(noConnPotCusNum);
        }
        try {
            HoloClient client = holoDataSource.getClient();
            if (client == null) {
                log.error("数仓数据源链接异常, 请检查！！！！{}", param);
                return;
            }
            TableSchema tableSchema = client.getTableSchema("ads_gic_mbr_no_conn_mbr_1d");

            SerializeConfig serializeConfig = new SerializeConfig();
            serializeConfig.setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCase);
            List<Put> puts = list
                    .stream()
                    .map(item -> {
                        Put temp = new Put(tableSchema);
                        temp.setObject("ent_id", item.getEnterpriseId());
                        temp.setObject("store_id", item.getStoreId());
                        temp.setObject("clerk_id", item.getClerkId());
                        temp.setObject("no_conn_pot_cus_num", item.getNoConnPotCusNum());
                        // 时间戳格式不行
                        temp.setObject("create_time", DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
                        return temp;
                    })
                    .collect(Collectors.toList());
            client.put(puts);
            log.info("写数据组完成");
        } catch (Exception ex) {
            log.info("数据组写入异常 {}", param, ex);
        }
    }

    public Integer getNoConnPotCusNum(PlatformPotentialCustomerOutDTO result, String enterpriseId, String storeId, ClerkDTO clerkDTO, boolean unassigned) {
        if (StringUtils.isBlank(storeId) && clerkDTO == null) {
            return 0;
        }
        String clerkTypeStr = "1";
        CustomerDTO params = new CustomerDTO();
        String clerkId = null;
        if (clerkDTO != null) {
            clerkTypeStr = "0";
            clerkId = clerkDTO.getClerkId();
            Integer clerkType = clerkDTO.getClerkType();
            if (clerkType == 0 || clerkType == 1) {
                storeId = clerkDTO.getStoreId();
            }
        }
        ContactParamDTO contact = new ContactParamDTO();
        contact.setRuleJSON(JSON.toJSONString(result));
        contact.setContactType(0);
        contact.setBizType(ContactBizTypeEnum.POTENTIAL_CUSTOMER.getType());
        params.setStoreId(storeId);
        params.setClerkId(clerkId);
        params.setClerkType(clerkTypeStr);
        params.setEnterpriseId(enterpriseId);
        params.setContactParamDTO(contact);
        MemberInfoListParamsDTO memberInfoListParamsDTO = new MemberInfoListParamsDTO();
        // 查询无归属数据
        if (unassigned) {
            FilterListDTO filterListDTO = new FilterListDTO();
            filterListDTO.setFilterType("1");
            ChildDTO child = new ChildDTO();
            child.setId("-1");
            filterListDTO.setChild(child);
            memberInfoListParamsDTO.setFilterList(Lists.newArrayList(filterListDTO));
        }
        ServiceResponse<ContactSumDTO> noContactResponse = customerService.contactMemberSum(new com.gic.haoban.base.api.common.BasePageInfo(), params, memberInfoListParamsDTO);
        return noContactResponse.getResult() != null ? noContactResponse.getResult().getTotalCount() : 0;
    }
}
