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

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.bo.potential.MemberLastInteractBO;
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.gic.store.goods.dto.goods.GoodsInfoSimpleDTO;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
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.*;
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 (Objects.equals(interactRecordQO.getClerkId(),"-1")) {
            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<>();
        }
        // 修改为批量查询
        Map<String, GoodsInfoSimpleDTO> goodsMap = interactRecordBuilder.buildGoodsMap(interactRecordQO.getEnterpriseId(), pageResult.getResult());

        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,goodsMap));
                    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) {

        if (StringUtils.isAnyBlank(memberId, unionId)) {
            return;
        }
        log.info("会员授权事件,memberId:{},unionId:{}", memberId,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;
    }

    @Override
    public void modifyUnionId(String enterpriseId, String oldUnionId, String newUnionId) {
        tabHaobanInteractRecordMapper.modifyUnionId(enterpriseId, oldUnionId, newUnionId);
    }

    @Override
    public void modifyFollowTime(String enterpriseId, String clerkId, String memberId) {
        DateTime now = cn.hutool.core.date.DateUtil.date();
        DateTime limitTime = cn.hutool.core.date.DateUtil.offsetDay(cn.hutool.core.date.DateUtil.endOfDay(now), -7);
        log.info("更新跟进时间 now:{},limitTime:{}", now, limitTime);
        tabHaobanInteractRecordMapper.modifyFollowTimeBatch(enterpriseId, clerkId, memberId,limitTime);
        InteractRecordBO interactRecordBO = queryLeastRecord(enterpriseId, clerkId, null, memberId);
        if (interactRecordBO != null) {
            TabHaobanInteractRecord modifyInteractRecord = new TabHaobanInteractRecord();
            modifyInteractRecord.setId(interactRecordBO.getId());
            modifyInteractRecord.setFollowTime(now);
            tabHaobanInteractRecordMapper.update(modifyInteractRecord);
        }
    }

    @Override
    public List<InteractRecordBO> lastInteractRecord(String enterpriseId, String clerkId, List<MemberLastInteractBO> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<TabHaobanInteractRecord> records = tabHaobanInteractRecordMapper.selectLastByMemberIds(clerkId, list);
        List<InteractRecordBO> recordBOList = records.stream()
                .map(item -> {
                    InteractRecordBO temp = new InteractRecordBO();
                    BeanUtils.copyProperties(item, temp);
                    temp.setRecordDesc(interactRecordBuilder.buildDesc(item));
                    temp.setExtendInfo(interactRecordBuilder.convertExtendInfo(item,null));
                    interactRecordBuilder.warpRelationGoodsNum(temp);
                    return temp;
                })
                .collect(Collectors.toList());
        return recordBOList;
    }

    @Override
    public List<MemberLastInteractBO> queryMemberIdsByTime(String clerkId, Date lastAccessTime) {
        return tabHaobanInteractRecordMapper.selectMemberIdsByTime(clerkId, lastAccessTime);
    }
}
