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.service.StaffApiService;
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.QywxNewsArticleMessageDTO;
import com.gic.wechat.api.dto.qywx.QywxNewsSendMessageDTO;
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.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.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)
                .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.buildNoticeMessage();
        if (CollectionUtils.isEmpty(noticeMessageBos)) {
            log.info("好办消息为空");
            return;
        }
        noticeMessageService.addNoticeMessageBatch(noticeMessageBos);
    }

    /**
     * 发送应用消息
     *
     * @param context
     */
    public void sendApplicationMessage(PotentialCustomerNotifyContext context) {
        if (CollectionUtils.isEmpty(context.getCustomerStaticsBos()) || CollectionUtils.isEmpty(context.getStaffClerkRelations())) {
            log.info("发送应用消息 参数缺失 {}");
            return;
        }
        Map<String, PotentialCustomerStaticsBO> customerStaticsBOMap = context.getCustomerStaticsBos()
                .stream()
                .collect(Collectors.toMap(PotentialCustomerStaticsBO::getClerkId, Function.identity(), (v1, v2) -> v1));
        Map<String, TabHaobanClerkMainStoreRelated> clerkMainStoreMap = new HashMap<>();
        Map<String, WxEnterpriseQwDTO> clerkEnterpriseMap = new HashMap<>();

        for (StaffClerkRelationDTO staffClerkRelation : context.getStaffClerkRelations()) {
            PotentialCustomerStaticsBO customerStaticsBO = customerStaticsBOMap.get(staffClerkRelation.getClerkId());
            if (customerStaticsBO == null || customerStaticsBO.getNum() == null || customerStaticsBO.getNum() == 0) {
                log.info("导购不存在新访问");
                continue;
            }
            String staffId = staffClerkRelation.getStaffId();
            TabHaobanClerkMainStoreRelated temp = clerkMainStoreMap.get(staffId);
            if (temp == null) {
                TabHaobanClerkMainStoreRelated tabHaobanClerkMainStoreRelated = clerkMainStoreRelatedService.selectByWxEnterpriseIdAndStoreId(staffId, staffClerkRelation.getWxEnterpriseId());
                if (tabHaobanClerkMainStoreRelated == null) {
                    tabHaobanClerkMainStoreRelated = new TabHaobanClerkMainStoreRelated();
                }
                clerkMainStoreMap.put(staffId, tabHaobanClerkMainStoreRelated);
                temp = clerkMainStoreMap.get(staffId);
            }

            if (temp != null) {
                if (StringUtils.isBlank(temp.getStoreId())) {
                    // 该成员无主门店
                    log.info("成员无主门店 {}", staffId);
                    continue;
                }
                if (StringUtils.isBlank(temp.getStoreId())) {
                    log.info("成员不存在主门店 {}", staffId);
                    continue;
                }
                // 需要发送应用消息
                WxEnterpriseQwDTO wxEnterpriseQwDTO = clerkEnterpriseMap.get(staffClerkRelation.getWxEnterpriseId());
                if (wxEnterpriseQwDTO == null) {
                    wxEnterpriseQwDTO = wxEnterpriseService.getQwInfo(staffClerkRelation.getWxEnterpriseId());
                    clerkEnterpriseMap.put(staffClerkRelation.getWxEnterpriseId(), wxEnterpriseQwDTO);
                }
                wxEnterpriseQwDTO = clerkEnterpriseMap.get(staffClerkRelation.getWxEnterpriseId());
                if (wxEnterpriseQwDTO == null) {
                    log.info("企业信息不存在 {}", staffClerkRelation.getWxEnterpriseId());
                    return;
                }
                QywxXcxSendMessageDTO messageDTO = this.buildApplicationMessage(staffClerkRelation, wxEnterpriseQwDTO, customerStaticsBO.getNum());
                boolean sendMessage = qywxSuiteApiService.sendMessage(wxEnterpriseQwDTO.getThirdCorpid(), config.getWxSuiteid(), messageDTO);
                log.info("发送应用消息结果 {}", sendMessage);
            }
        }
    }

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

        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("/pageurl?");
        messageDTO.setTitle("销售线索通知");
        messageDTO.setItems(Collections.singletonList(itemDTO));
        return messageDTO;
    }
}
