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

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.Page;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.common.utils.PageUtil;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.service.dao.mapper.content.TabHaobanPotentialCustomerMapper;
import com.gic.haoban.manage.service.entity.TabHaobanExternalClerkRelated;
import com.gic.haoban.manage.service.entity.content.TabHaobanPotentialCustomer;
import com.gic.haoban.manage.service.pojo.bo.content.PotentialCustomerBO;
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.pojo.qo.content.InteractRecordQO;
import com.gic.haoban.manage.service.pojo.qo.content.PotentialCustomerQO;
import com.gic.haoban.manage.service.service.ExternalClerkRelatedService;
import com.gic.haoban.manage.service.service.MemberQueryService;
import com.gic.haoban.manage.service.service.StaffClerkRelationService;
import com.gic.haoban.manage.service.service.content.InteractRecordService;
import com.gic.haoban.manage.service.service.content.PotentialCustomerService;
import com.gic.haoban.manage.service.service.content.adaptor.PotentialCustomerNotifyBuilder;
import com.gic.member.api.dto.es.MemberDataDTO;
import com.gic.search.engine.api.constant.MemberDataEnum;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 销售线索(TabHaobanPotentialCustomer)表服务实现类
 *
 * @author makejava
 * @since 2023-03-28 09:48:08
 */
@Slf4j
@Component
public class PotentialCustomerServiceImpl implements PotentialCustomerService {

    @Resource
    private TabHaobanPotentialCustomerMapper potentialCustomerMapper;
    @Autowired
    private PotentialCustomerNotifyBuilder potentialCustomerNotifyBuilder;
    @Autowired
    private InteractRecordService interactRecordService;
    @Autowired
    private ExternalClerkRelatedService externalClerkRelatedService;
    @Autowired
    MemberQueryService memberQueryService;
    @Autowired
    StaffClerkRelationService staffClerkRelationService;


    /**
     * 查询销售线索
     *
     * @param potentialCustomerQO
     * @return
     */
    @Override
    public Page<PotentialCustomerBO> queryPotentialCustomerPage(PotentialCustomerQO potentialCustomerQO) {

        if (StringUtils.isBlank(potentialCustomerQO.getClerkId())) {
            log.info("参数缺失 {}", potentialCustomerQO.getClerkId());
            return new Page<>();
        }
        StaffClerkRelationDTO staffClerkRelationDTO = staffClerkRelationService.getByClerkId(potentialCustomerQO.getClerkId());
        if (staffClerkRelationDTO == null) {
            return new Page<>();
        }
        potentialCustomerQO.setStaffId(staffClerkRelationDTO.getStaffId());
        PageHelper.startPage(potentialCustomerQO.getPageNum(), potentialCustomerQO.getPageSize());
        com.github.pagehelper.Page<TabHaobanPotentialCustomer> pageResult =
                (com.github.pagehelper.Page<TabHaobanPotentialCustomer>) potentialCustomerMapper.queryPotentialCustomerList(potentialCustomerQO);
        Page<PotentialCustomerBO> customerBOPage = PageUtil.changePageHelperToCurrentPage(pageResult, PotentialCustomerBO.class);
        if (CollectionUtils.isEmpty(customerBOPage.getResult())) {
            log.info("查询销售线索列表为空 params: {}", JSON.toJSONString(potentialCustomerQO));
            return customerBOPage;
        }

        List<String> memberIds = customerBOPage.getResult()
                .stream()
                .map(PotentialCustomerBO::getMemberId)
                .distinct()
                .collect(Collectors.toList());
        Map<String, Integer> clerkMemberRelationMap = this.queryMemberRelation(potentialCustomerQO.getStaffId(), memberIds, potentialCustomerQO.getHasMemberRelation());
        Map<String, String> memberExtendInfoMap = this.queryMemberExtendInfo(potentialCustomerQO.getEnterpriseId(), memberIds);

        // 构建是否是会员
        for (PotentialCustomerBO potentialCustomerBO : customerBOPage.getResult()) {
            // 默认未成交过
            potentialCustomerBO.setDealRecord(0);
            if (potentialCustomerBO.getDealRecordNum() != null && potentialCustomerBO.getDealRecordNum() > 0) {
                potentialCustomerBO.setDealRecord(1);
            }
            String url = memberExtendInfoMap.get(potentialCustomerBO.getMemberId());
            potentialCustomerBO.setMemberImageUrl(url);
            if (potentialCustomerQO.getHasMemberRelation() != null) {
                // 查询条件是有好友关系的
                potentialCustomerBO.setHasMemberRelation(1);
                continue;
            }
            // 获取有好友关系的
            Integer hasRelation = clerkMemberRelationMap.get(potentialCustomerBO.getMemberId());
            potentialCustomerBO.setHasMemberRelation(Optional.ofNullable(hasRelation).orElse(0));
        }
        return customerBOPage;
    }

    /**
     * 查询与导购的关系
     *
     * @param staffId
     * @param memberIds
     * @return
     */
    private Map<String, Integer> queryMemberRelation(String staffId, List<String> memberIds, Integer hasMemberRelation) {
        if (hasMemberRelation != null) {
            log.info("按好友条件搜索 无须查询");
            return Collections.emptyMap();
        }

        List<TabHaobanExternalClerkRelated> clerkRelateds = externalClerkRelatedService.queryClerkMemberRelations(staffId, memberIds);
        if (CollectionUtils.isEmpty(clerkRelateds)) {
            log.info("查询导购与本批次会员不存在好友关系 staffId:{}", staffId);
            return Collections.emptyMap();
        }
        return clerkRelateds
                .stream()
                .collect(Collectors.toMap(TabHaobanExternalClerkRelated::getMemberId, item -> 1, (v1, v2) -> v1));
    }

    private Map<String, String> queryMemberExtendInfo(String enterpriseId, List<String> memberIds) {
        List<String> returnFields = Arrays.asList(MemberDataEnum.member_memberId.getCode(), MemberDataEnum.member_photoUrl.getCode());
        List<MemberDataDTO> memberDataDTOS = memberQueryService.queryMemberBatch(enterpriseId, memberIds, StringUtils.join(returnFields, ","));
        if (CollectionUtils.isEmpty(memberDataDTOS)) {
            return Collections.emptyMap();
        }
        return memberDataDTOS
                .stream()
                .filter(item -> StringUtils.isNotBlank(item.getPhotoUrl()))
                .collect(Collectors.toMap(MemberDataDTO::getMemberId, MemberDataDTO::getPhotoUrl, (v1 ,v2) -> v1));
    }

    /**
     * 查询详情
     *
     * @param clerkId
     * @param potentialCustomerId
     * @return
     */
    @Override
    public PotentialCustomerBO queryPotentialCustomerInfo(String clerkId, Long potentialCustomerId) {
        if (StringUtils.isBlank(clerkId)) {
            return null;
        }
        TabHaobanPotentialCustomer haobanPotentialCustomer = potentialCustomerMapper.queryById(potentialCustomerId, clerkId);
        if (haobanPotentialCustomer == null) {
            return null;
        }
        PotentialCustomerBO temp = new PotentialCustomerBO();
        BeanUtils.copyProperties(haobanPotentialCustomer, temp);
        return temp;
    }

    /**
     * 根据导购和会员id查询销售线索
     *
     * @param clerkId
     * @param memberId
     * @return
     */
    @Override
    public PotentialCustomerBO queryPotentialCustomerInfo(String clerkId, String memberId) {
        TabHaobanPotentialCustomer potentialCustomer = potentialCustomerMapper.queryWithClerkIdAndMemberId(clerkId, memberId);
        if (potentialCustomer == null) {
            return null;
        }
        PotentialCustomerBO temp = new PotentialCustomerBO();
        BeanUtils.copyProperties(potentialCustomer, temp);
        return temp;
    }

    /**
     * 标记销售线索为已读 或 星标客户
     *
     * @param potentialCustomerBO
     */
    @Override
    public void markPotentialCustomer(PotentialCustomerBO potentialCustomerBO) {
        if (potentialCustomerBO.getId() == null) {
            log.info("参数缺失");
            return;
        }
        TabHaobanPotentialCustomer temp = new TabHaobanPotentialCustomer();
        temp.setId(potentialCustomerBO.getId());
        temp.setStarFlag(potentialCustomerBO.getStarFlag());
        temp.setSeeFlag(potentialCustomerBO.getSeeFlag());
        potentialCustomerMapper.update(temp);
    }

    /**
     * 更新保存
     *
     * @param potentialCustomerBO
     * @return
     */
    @Override
    public Long saveOrUpdatePotentialCustomer(PotentialCustomerBO potentialCustomerBO) {

        TabHaobanPotentialCustomer temp = new TabHaobanPotentialCustomer();
        BeanUtils.copyProperties(potentialCustomerBO, temp);
        temp.setUpdateTime(new Date());
        if (temp.getId() == null) {
            temp.setId(UniqueIdUtils.uniqueLong());
            potentialCustomerMapper.insert(temp);
        } else {
            potentialCustomerMapper.update(temp);
        }
        return temp.getId();
    }

    /**
     * 销售线索通知
     *
     * @param context
     */
    @Override
    public void sendPotentialCustomerNotice(PotentialCustomerNotifyContext context) {

        log.info("处理企业{}下的销售线索通知", context.getEnterpriseId());

        // 根据企业id + 时间  循环查询时间段内的有新互动记录的导购id 去重
        InteractRecordQO searchQo = new InteractRecordQO();
        searchQo.setEnterpriseId(context.getEnterpriseId());
        searchQo.setStartTime(context.getStartTime());
        searchQo.setEndTime(context.getEndTime());
        List<PotentialCustomerStaticsBO> customerStaticsBos = interactRecordService.staticsClerkNewInteractRecord(searchQo);
        if (CollectionUtils.isEmpty(customerStaticsBos)) {
            log.info("企业下不存在新增线索的导购 {}", JSON.toJSONString(context));
            return;
        }
        context.setCustomerStaticsBos(customerStaticsBos);
        // 获取导购与成员关联关联关系
        potentialCustomerNotifyBuilder.buildClerkRelations(context);
        // 获取成员的主门店
        // 区经 忽略
        potentialCustomerNotifyBuilder.filterAreaManage(context);
        // 构建应用内消息
        potentialCustomerNotifyBuilder.sendHaoBanNotifyMessage(context);
        // 如果该导购id是成员在主门店时的导购id 发送应用消息
        // 如果本批数据中无成员主门店数据 则不发送
        potentialCustomerNotifyBuilder.sendApplicationMessage(context);
    }

    /**
     * 会员合并操作
     *
     * @param mergeMemberId
     * @param memberId
     */
    @Override
    public void mergeMember(String mergeMemberId, String memberId) {
        if (StringUtils.isAnyBlank(mergeMemberId, memberId)) {
            return;
        }
        potentialCustomerMapper.mergeMember(mergeMemberId, memberId);
    }

    /**
     * 处理会员成交记录
     *
     * @param enterpriseId
     * @param memberId
     */
    @Override
    public void updateMemberDealFlag(String enterpriseId, String memberId) {
        log.info("刷新订单是否有成交记录 {}, {}", enterpriseId, memberId);
        if (StringUtils.isAnyBlank(enterpriseId, memberId)) {
            return;
        }
        potentialCustomerMapper.updateMemberDealRecordNum(enterpriseId, memberId);
    }
}
