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

import com.alibaba.fastjson.JSON;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.enums.NoticeMessageTypeEnum;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.util.notify.NoticeMessageUtil;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.entity.TabHaobanClerkMainStoreRelated;
import com.gic.haoban.manage.service.pojo.bo.NoticeMessageBO;
import com.gic.haoban.manage.service.pojo.bo.content.PotentialCustomerStaticsBO;
import com.gic.haoban.manage.service.pojo.bo.content.context.PotentialCustomerNotifyContext;
import com.gic.haoban.manage.service.service.ClerkMainStoreRelatedService;
import com.gic.haoban.manage.service.service.StaffClerkRelationService;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.haoban.manage.service.service.notify.NoticeMessageService;
import com.gic.wechat.api.dto.qywx.ItemDTO;
import com.gic.wechat.api.dto.qywx.QywxXcxSendMessageDTO;
import com.gic.wechat.api.service.qywx.QywxSuiteApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author MUSI
 * @Date 2023/3/30 10:58 AM
 * @Description
 * @Version
 **/
@Slf4j
@Component
public class PotentialCustomerNotifyBuilder {

    @Autowired
    StaffClerkRelationService staffClerkRelationService;
    @Autowired
    private ClerkMainStoreRelatedService clerkMainStoreRelatedService;
    @Autowired
    private NoticeMessageService noticeMessageService;
    @Autowired
    private QywxSuiteApiService qywxSuiteApiService;
    @Autowired
    private WxEnterpriseService wxEnterpriseService;
    @Autowired
    private Config config;
    @Autowired
    private StaffApiService staffApiService;

    /**
     * 获取企业下所有导购id
     *
     * @param context
     */
    public void buildEnterpriseClerkIds(PotentialCustomerNotifyContext context) {
        if (StringUtils.isBlank(context.getEnterpriseId())) {
            return;
        }
        List<String> clerkIds =
                staffClerkRelationService.listAllClerkIdsByEnterpriseId(context.getEnterpriseId());
        if (CollectionUtils.isEmpty(clerkIds)) {
            return;
        }
        context.setClerkIds(clerkIds);
    }

    /**
     * 获取导购的绑定关系
     *
     * @param context
     */
    public void buildClerkRelations(PotentialCustomerNotifyContext context) {
        List<String> clerkIds = context.getCustomerStaticsBos()
                .stream()
                .map(PotentialCustomerStaticsBO::getClerkId)
                .distinct()
                .collect(Collectors.toList());
        context.setClerkIds(clerkIds);
        List<StaffClerkRelationDTO> staffClerkRelations = staffClerkRelationService.listByClerkIds(context.getClerkIds());
        context.setStaffClerkRelations(staffClerkRelations);
    }

    /**
     * 过滤区经
     *
     * @param context
     */
    public void filterAreaManage(PotentialCustomerNotifyContext context) {

        List<StaffClerkRelationDTO> clerkRelations = context.getStaffClerkRelations()
                .stream()
                .filter(item -> !Objects.equals(2, item.getClerkType()))
                .collect(Collectors.toList());
        context.setStaffClerkRelations(clerkRelations);
    }

    /**
     * 发送好办小程序消息
     *
     * @param context
     */
    public void sendHaoBanNotifyMessage(PotentialCustomerNotifyContext context) {
        List<NoticeMessageBO> noticeMessageBos = context.buildHaoBanNoticeMessage();
        if (CollectionUtils.isEmpty(noticeMessageBos)) {
            log.info("好办消息为空");
            return;
        }
        noticeMessageService.addNoticeMessageBatch(noticeMessageBos);
    }

    /**
     * 发送应用消息
     * 批次中存在导购主门店数据的话 推送主门店数据
     * 不存在主门店数据的话 随机推送一个有数据的门店
     *
     * @param context
     */
    public void sendApplicationMessage(PotentialCustomerNotifyContext context) {
        if (CollectionUtils.isEmpty(context.getCustomerStaticsBos())) {
            log.info("发送应用消息不存在导购纬度的统计");
            return;
        }
        if (CollectionUtils.isEmpty(context.getStaffClerkRelations())) {
            log.info("发送应用消息 不存在导购绑定关系 clerkIds: {}", JSON.toJSONString(context.getClerkIds()));
            return;
        }
        Map<String, WxEnterpriseQwDTO> clerkEnterpriseCacheMap = new HashMap<>();

        Map<String, PotentialCustomerStaticsBO> customerStaticsBOMap = context.getCustomerStaticsBos()
                .stream()
                .collect(Collectors.toMap(PotentialCustomerStaticsBO::getClerkId, Function.identity(), (v1, v2) -> v1));

        // 按staffId 聚合
        Map<String, List<StaffClerkRelationDTO>> staffRelationMap = context.getStaffClerkRelations()
                .stream()
                .filter(item -> {
                    PotentialCustomerStaticsBO staticsBO = customerStaticsBOMap.get(item.getClerkId());
                    return staticsBO != null && staticsBO.getNum() != null && staticsBO.getNum() > 0;
                })
                .collect(Collectors.groupingBy(StaffClerkRelationDTO::getStaffId));
        if (MapUtils.isEmpty(staffRelationMap)) {
            log.info("企业下的销售线索统计为空 {}", context.getEnterpriseId());
            return;
        }
        // 按成员分组
        for (Map.Entry<String, List<StaffClerkRelationDTO>> entry : staffRelationMap.entrySet()) {
            if (CollectionUtils.isEmpty(entry.getValue())) {
                log.info("成员不存在有数值的绑定关系 staffIf:{}", entry.getKey());
                continue;
            }
            String staffId = entry.getKey();
            String wxEnterpriseId = entry.getValue().get(0).getWxEnterpriseId();
            TabHaobanClerkMainStoreRelated tabHaobanClerkMainStoreRelated = clerkMainStoreRelatedService.selectByWxEnterpriseIdAndStoreId(staffId, wxEnterpriseId);
            if (tabHaobanClerkMainStoreRelated == null) {
                log.info("成员无主门店信息,不做处理 {}", staffId);
                continue;
            }
            Optional<StaffClerkRelationDTO> mainStoreClerkRelation = entry.getValue()
                    .stream()
                    .filter(item -> StringUtils.equals(item.getStoreId(), tabHaobanClerkMainStoreRelated.getStoreId()))
                    .findFirst();
            StaffClerkRelationDTO staffClerkRelation = entry.getValue().get(0);
            if (mainStoreClerkRelation.isPresent()) {
                staffClerkRelation = mainStoreClerkRelation.get();
            }
            log.info("发送应用消息的导购绑定关系 {}", JSON.toJSONString(staffClerkRelation));
            // 需要发送应用消息
            WxEnterpriseQwDTO wxEnterpriseQwDTO = clerkEnterpriseCacheMap.get(staffClerkRelation.getWxEnterpriseId());
            if (wxEnterpriseQwDTO == null) {
                wxEnterpriseQwDTO = wxEnterpriseService.getQwInfo(staffClerkRelation.getWxEnterpriseId());
                clerkEnterpriseCacheMap.put(staffClerkRelation.getWxEnterpriseId(), wxEnterpriseQwDTO);
            }
            wxEnterpriseQwDTO = clerkEnterpriseCacheMap.get(staffClerkRelation.getWxEnterpriseId());
            if (wxEnterpriseQwDTO == null) {
                log.info("企业信息不存在 {}", staffClerkRelation.getWxEnterpriseId());
                continue;
            }
            QywxXcxSendMessageDTO messageDTO = this.buildApplicationMessage(staffClerkRelation, wxEnterpriseQwDTO,
                    customerStaticsBOMap.get(staffClerkRelation.getClerkId()).getNum(), context.buildExtendParams(staffClerkRelation.getStoreId(), staffClerkRelation.getClerkId()));
            boolean sendMessage = qywxSuiteApiService.sendMessage(wxEnterpriseQwDTO.getThirdCorpid(), config.getWxSuiteid(), messageDTO);
            log.info("发送销售线索应用消息结果 {}", sendMessage);
        }
    }

    public QywxXcxSendMessageDTO buildApplicationMessage(StaffClerkRelationDTO staffClerkRelation, WxEnterpriseQwDTO wxEnterpriseQwDTO, int count, String extendParams) {

        StaffDTO staffDTO = staffApiService.selectById(staffClerkRelation.getStaffId());
        String wxUserId = staffDTO.getWxUserId();
        if (wxEnterpriseQwDTO.needOpenUserId3th()) {
            wxUserId = staffDTO.getWxOpenUseId();
        }
        QywxXcxSendMessageDTO messageDTO = new QywxXcxSendMessageDTO();
        ItemDTO itemDTO = new ItemDTO();
        itemDTO.setKey("事件");
        itemDTO.setValue(String.format("新增%s个客户的销售线索，请及时跟进", count));
        ArrayList<String> list = new ArrayList<>();
        list.add(wxUserId);
        messageDTO.setAppid(config.getAppid());
        messageDTO.setUserIds(list);
        messageDTO.setPage(NoticeMessageUtil.buildMiniAppUrl(NoticeMessageTypeEnum.POTENTIAL_CUSTOMER_NOTIFY, extendParams));
        messageDTO.setTitle("销售线索通知");
        messageDTO.setItems(Collections.singletonList(itemDTO));
        return messageDTO;
    }
}
