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.DateUtil;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.manage.service.dao.mapper.content.TabHaobanInteractRecordMapper;
import com.gic.haoban.manage.service.entity.content.TabHaobanInteractRecord;
import com.gic.haoban.manage.service.pojo.bo.content.InteractRecordBO;
import com.gic.haoban.manage.service.pojo.bo.content.InteractRecordExtendInfoBO;
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.qo.content.InteractRecordQO;
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.InteractRecordBuilder;
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.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 互动记录明细(TabHaobanInteractRecord)表服务实现类
 *
 * @author makejava
 * @since 2023-03-28 10:32:48
 */
@Slf4j
@Component
public class InteractRecordServiceImpl implements InteractRecordService {

    @Resource
    private TabHaobanInteractRecordMapper tabHaobanInteractRecordMapper;
    @Autowired
    private InteractRecordBuilder interactRecordBuilder;
    @Autowired
    PotentialCustomerService potentialCustomerService;

    /**
     * 查询互动记录
     *
     * @param enterpriseId
     * @param traceId
     * @return
     */
    @Override
    public InteractRecordBO queryWithInteractInfo(String enterpriseId, String traceId) {

        if (StringUtils.isAnyBlank(enterpriseId, traceId)) {
            return null;
        }

        TabHaobanInteractRecord interactRecord = tabHaobanInteractRecordMapper.queryWithEnterpriseIdAndTraceId(enterpriseId, traceId);
        if (interactRecord == null) {
            return null;
        }
        InteractRecordBO temp = new InteractRecordBO();
        BeanUtils.copyProperties(interactRecord, temp);
        if (StringUtils.isNotBlank(interactRecord.getExtendInfo())) {
            InteractRecordExtendInfoBO extendInfo = JSON.parseObject(interactRecord.getExtendInfo(), InteractRecordExtendInfoBO.class);
            temp.setExtendInfo(extendInfo);
        }
        return temp;
    }

    /**
     * 互动记录查询
     *
     * @param interactRecordQO
     * @return
     */
    @Override
    public Page<InteractRecordBO> queryInteractRecordPage(InteractRecordQO interactRecordQO) {

        if (StringUtils.isBlank(interactRecordQO.getClerkId())) {
            log.info("queryInteractRecordPage 参数缺失");
            return new Page<>();
        }
        // 默认查最近一年内的的数据
        if (interactRecordQO.getStartTime() == null || interactRecordQO.getStartTime().before(DateUtil.addNumForYear(new Date(), -1))) {
            interactRecordQO.setStartTime(DateUtil.addNumForYear(new Date(), -1));
        }
        PageHelper.startPage(interactRecordQO.getPageNum(), interactRecordQO.getPageSize());
        com.github.pagehelper.Page<TabHaobanInteractRecord> pageResult =
                (com.github.pagehelper.Page<TabHaobanInteractRecord>) tabHaobanInteractRecordMapper.queryInteractRecordList(interactRecordQO);
        if (pageResult == null || CollectionUtils.isEmpty(pageResult)) {
            log.info("查询互动记录数据为空 {}", JSON.toJSONString(interactRecordQO));
            return new Page<>();
        }
        Page<InteractRecordBO> result = new Page<>();
        result.setTotalCount((int) pageResult.getTotal());
        List<InteractRecordBO> recordBos = pageResult.getResult()
                .stream()
                .map(item -> {
                    InteractRecordBO temp = new InteractRecordBO();
                    BeanUtils.copyProperties(item, temp);
                    temp.setRecordDesc(interactRecordBuilder.buildDesc(item));
                    temp.setExtendInfo(interactRecordBuilder.convertExtendInfo(item));
                    interactRecordBuilder.warpRelationGoodsNum(temp);
                    return temp;
                })
                .collect(Collectors.toList());
        result.setResult(recordBos);
        return result;
    }

    /**
     * 统计总数
     *
     * @param interactRecordQO
     * @return
     */
    @Override
    public Integer countInteractRecord(InteractRecordQO interactRecordQO) {
        interactRecordQO.setPageNum(1);
        interactRecordQO.setPageSize(1);
        PageHelper.startPage(interactRecordQO.getPageNum(), interactRecordQO.getPageSize());
        com.github.pagehelper.Page<TabHaobanInteractRecord> pageResult =
                (com.github.pagehelper.Page<TabHaobanInteractRecord>) tabHaobanInteractRecordMapper.queryInteractRecordList(interactRecordQO);
        if (pageResult == null || CollectionUtils.isEmpty(pageResult)) {
            log.info("查询互动记录数据为空 {}", JSON.toJSONString(interactRecordQO));
            return 0;
        }
        return (int)pageResult.getTotal();
    }

    /**
     * 保存互动记录
     *
     * @param interactRecordBO
     * @return
     */
    @Override
    public Long saveOrUpdateInteractRecord(InteractRecordBO interactRecordBO) {
        TabHaobanInteractRecord temp = new TabHaobanInteractRecord();
        BeanUtils.copyProperties(interactRecordBO, temp);
        if (interactRecordBO.getExtendInfo() != null) {
            temp.setExtendInfo(JSON.toJSONString(interactRecordBO.getExtendInfo()));
        }
        if (interactRecordBO.getId() == null) {
            temp.setId(UniqueIdUtils.uniqueLong());
            tabHaobanInteractRecordMapper.insert(temp);
        }else {
            tabHaobanInteractRecordMapper.update(temp);
        }
        return temp.getId();
    }

    /**
     * 统计导购的互动记录总数
     *
     * @param interactRecordQO
     * @return
     */
    @Override
    public List<PotentialCustomerStaticsBO> staticsClerkNewInteractRecord(InteractRecordQO interactRecordQO) {
        return this.tabHaobanInteractRecordMapper.staticsClerkInteractRecordNew(interactRecordQO);
    }

    /**
     * 会员合并操作
     *
     * @param mergeMemberId
     * @param memberId
     */
    @Override
    public void mergeMember(String mergeMemberId, String memberId) {
        if (StringUtils.isAnyBlank(memberId, mergeMemberId)) {
            log.info("合并会员参数缺失 mergeMemberId: {} memberId: {}", mergeMemberId, memberId);
            return;
        }
        tabHaobanInteractRecordMapper.mergeMember(mergeMemberId, memberId);
    }

    /**
     * 会员授权事件
     *
     * @param memberId
     * @param unionId
     */
    @Override
    public void memberAuthorized(String memberId, String unionId) {

        InteractRecordQO interactRecordQO = new InteractRecordQO();
        interactRecordQO.setUnionId(unionId);
        List<TabHaobanInteractRecord> interactRecords = this.tabHaobanInteractRecordMapper.queryInteractRecordList(interactRecordQO);
        if (CollectionUtils.isEmpty(interactRecords)) {
            log.info("会员授权事件, 该会员未产生过互动记录 {}", unionId);
            return;
        }
        tabHaobanInteractRecordMapper.memberAuthorized(memberId, unionId);
        Map<String, List<TabHaobanInteractRecord>> interactRecordMap = interactRecords
                .stream()
                .collect(Collectors.groupingBy(item -> item.getClerkId() + item.getBizId()));

        for (Map.Entry<String, List<TabHaobanInteractRecord>> entry : interactRecordMap.entrySet()) {
            this.handlerRecord(memberId, entry.getValue());
        }

    }

    private void handlerRecord(String memberId, List<TabHaobanInteractRecord> interactRecords) {

        Integer durationTime = interactRecords
                .stream()
                .map(TabHaobanInteractRecord::getDurationTime)
                .filter(Objects::nonNull)
                .reduce(0, Integer::sum);
        interactRecords.sort(Comparator.comparing(TabHaobanInteractRecord::getId).reversed());
        TabHaobanInteractRecord interactRecord = interactRecords.get(0);
        interactRecord.setMemberId(memberId);
        PotentialCustomerBO potentialCustomerBO = potentialCustomerService.queryPotentialCustomerInfo(interactRecord.getClerkId(), memberId);
        if (potentialCustomerBO == null) {
            potentialCustomerBO = interactRecordBuilder.build(interactRecord);
        }
        potentialCustomerBO.setDurationTime(durationTime);
        potentialCustomerService.saveOrUpdatePotentialCustomer(potentialCustomerBO);
    }

    /**
     * 查询最新的一条互动记录
     *
     * @param clerkId
     * @param bizId
     * @param memberId
     * @return
     */
    @Override
    public InteractRecordBO queryLeastRecord(String enterpriseId, String clerkId, String bizId, String memberId) {
        InteractRecordQO interactRecordQO = new InteractRecordQO();
        interactRecordQO.setEnterpriseId(enterpriseId);
        interactRecordQO.setClerkId(clerkId);
        interactRecordQO.setBizId(bizId);
        interactRecordQO.setMemberId(memberId);
        PageHelper.startPage(1, 1);
        com.github.pagehelper.Page<TabHaobanInteractRecord> pageResult =
                (com.github.pagehelper.Page<TabHaobanInteractRecord>) tabHaobanInteractRecordMapper.queryInteractRecordList(interactRecordQO);
        if (pageResult == null || CollectionUtils.isEmpty(pageResult)) {
            log.info("查询互动记录数据为空 {}", JSON.toJSONString(interactRecordQO));
            return null;
        }
        TabHaobanInteractRecord tabHaobanInteractRecord = pageResult.getResult().get(0);
        InteractRecordBO interactRecordBO = new InteractRecordBO();
        BeanUtils.copyProperties(tabHaobanInteractRecord, interactRecordBO);
        if (StringUtils.isNotBlank(tabHaobanInteractRecord.getExtendInfo())) {
            InteractRecordExtendInfoBO extendInfo = JSON.parseObject(tabHaobanInteractRecord.getExtendInfo(), InteractRecordExtendInfoBO.class);
            interactRecordBO.setExtendInfo(extendInfo);
        }
        return interactRecordBO;
    }
}
