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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.haoban.manage.api.dto.content.MemberLastInteractDTO;
import com.gic.haoban.manage.api.dto.qdto.content.InteractRecordQDTO;
import com.gic.haoban.manage.api.enums.content.InteractRecordExtendInfoDTO;
import com.gic.haoban.manage.api.enums.content.InteractRecordInfoDTO;
import com.gic.haoban.manage.api.service.content.InteractRecordApiService;
import com.gic.haoban.manage.service.pojo.bo.content.InteractRecordBO;
import com.gic.haoban.manage.service.pojo.bo.content.MemberAttrChangeBO;
import com.gic.haoban.manage.service.pojo.bo.content.binlog.MemberOrderBo;
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.MaterialEnterpriseAdaptor;
import com.gic.haoban.manage.service.task.KafkaMessageServiceImpl;
import com.gic.haoban.manage.service.util.OrderCheckUtil;
import com.gic.member.api.dto.event.lifecycle.CreateMemberEventParam;
import com.gic.member.api.dto.info.MemberSummaryInfoDTO;
import com.gic.member.api.dto.info.qo.QueryMemberInfoDTO;
import com.gic.member.api.service.MemberOutApiService;
import com.gic.order.api.constant.OrderChannelEnum;
import com.gic.order.api.dto.OrderSaveNotifyDTO;
import com.gic.order.api.dto.resp.OrderInfoResp;
import com.gic.order.api.service.member.MemberOrderReadApiService;
import com.gic.haoban.manage.service.util.EventUtils;
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 java.util.*;
import java.util.stream.Collectors;

/**
 * @Author MUSI
 * @Date 2023/3/29 1:12 PM
 * @Description
 * @Version
 **/
@Slf4j
@Component("interactRecordApiService")
public class InteractRecordApiServiceImpl implements InteractRecordApiService {

    @Autowired
    private InteractRecordService interactRecordService;
    @Autowired
    PotentialCustomerService potentialCustomerService;
    @Autowired
    private MaterialEnterpriseAdaptor materialEnterpriseAdaptor;
    @Autowired
    MemberOutApiService memberOutApiService;
    @Autowired
    private MemberOrderReadApiService memberOrderReadApiService;

    /**
     * 查询互动记录
     *
     * @param interactRecordQDTO
     * @return
     */
    @Override
    public ServiceResponse<Page<InteractRecordInfoDTO>> queryInteractRecordList(InteractRecordQDTO interactRecordQDTO) {
        Page<InteractRecordInfoDTO> result = new Page<>();
        result.setTotalCount(0);
        result.setResult(Collections.emptyList());
        InteractRecordQO searchQo = new InteractRecordQO();
        BeanUtils.copyProperties(interactRecordQDTO, searchQo);
        Page<InteractRecordBO> pageResult = interactRecordService.queryInteractRecordPage(searchQo);
        if (pageResult == null || CollectionUtils.isEmpty(pageResult.getResult())) {
            log.info("查询结果为空 {}", JSON.toJSONString(interactRecordQDTO));
            return ServiceResponse.success(result);
        }

        // 拼接描述
        // 组装扩展信息
        List<InteractRecordInfoDTO> recordInfos = pageResult.getResult()
                .stream()
                .map(this::getInteractRecordInfoDTO)
                .collect(Collectors.toList());
        result.setTotalCount(pageResult.getTotalCount());
        result.setResult(recordInfos);
        result.setCurrentPage(interactRecordQDTO.getPageNum());
        result.setPageSize(interactRecordQDTO.getPageSize());
        return ServiceResponse.success(result);
    }

    private InteractRecordInfoDTO getInteractRecordInfoDTO(InteractRecordBO item) {
        InteractRecordInfoDTO temp = new InteractRecordInfoDTO();
        BeanUtils.copyProperties(item, temp);
        if (item.getLastAccessTime() != null) {
            temp.setCreateTime(item.getLastAccessTime());
        }
        temp.setInteractRecordId(item.getId());
        if (item.getExtendInfo() != null) {
            InteractRecordExtendInfoDTO extendInfo = new InteractRecordExtendInfoDTO();
            BeanUtils.copyProperties(item.getExtendInfo(), extendInfo);
            temp.setExtendInfo(extendInfo);
        }
        return temp;
    }

    @Override
    public ServiceResponse<Map<String, InteractRecordInfoDTO>> mapInteractRecord(String enterpriseId, String clerkId, List<MemberLastInteractDTO> list) {
        if (CollectionUtils.isEmpty(list)) {
            return ServiceResponse.success(new HashMap<>());
        }
        List<InteractRecordBO> recordBOS = interactRecordService.lastInteractRecord(enterpriseId, clerkId, EntityUtil.changeEntityListByJSON(MemberLastInteractBO.class, list));
        List<InteractRecordInfoDTO> recordInfos = recordBOS
                .stream()
                .map(this::getInteractRecordInfoDTO)
                .collect(Collectors.toList());
        Map<String, InteractRecordInfoDTO> map = recordInfos.stream().collect(Collectors.toMap(InteractRecordInfoDTO::getMemberId,
                v -> v, (e, x) -> e));
        return ServiceResponse.success(map);
    }

    @Override
    public ServiceResponse<List<MemberLastInteractDTO>> queryMemberIdsByTime(String clerkId, Date lastAccessTime) {
        List<MemberLastInteractBO> list = interactRecordService.queryMemberIdsByTime(clerkId, lastAccessTime);
        List<MemberLastInteractDTO> dtoList = EntityUtil.changeEntityListByJSON(MemberLastInteractDTO.class, list);
        return ServiceResponse.success(dtoList);
    }

    /**
     * 处理member信息变化的MQ
     *
     * @param params
     * @return
     */
    @Override
    public ServiceResponse<Void> memberChangeMQ(String params) {

        log.info("会员合并事件 > {}", params);
        if (StringUtils.isBlank(params)) {
            log.info("会员id发生变化 {}", params);
            return ServiceResponse.success();
        }
        JSONObject jsonObject = JSONObject.parseObject(params);
        int eventFlag = jsonObject.getIntValue("eventFlag") ;
        if(EventUtils.isOpenEvent()) {
            if(eventFlag == 0) {
                log.info("非事件入口,不处理");
                return ServiceResponse.success();
            }
        }else {
            if(eventFlag == 1) {
                log.info("事件入口,不处理");
                return ServiceResponse.success();
            }
        }
        MemberAttrChangeBO memberAttrChangeBO = JSON.parseObject(params, MemberAttrChangeBO.class);
        if (memberAttrChangeBO == null) {
            return ServiceResponse.success();
        }
        if (MemberAttrChangeBO.MemberChangeOpt.MINI_APP_AUTHORIZED.getCode().equals(memberAttrChangeBO.getOpt())) {
            // 会员授权事件
            // 根据unionId 刷新 memberId 并写入销售线索

            // interactRecordService.memberAuthorized(memberAttrChangeBO.getMemberId(), memberAttrChangeBO.getUnionId());

        }
        if (MemberAttrChangeBO.MemberChangeOpt.MEMBER_MERGE.getCode().equals(memberAttrChangeBO.getOpt())) {
            //会员合并
            // 把合并的memberId 修改成 合并后的memberId
            interactRecordService.mergeMember(memberAttrChangeBO.getMergeMemberId(), memberAttrChangeBO.getMemberId());
            potentialCustomerService.mergeMember(memberAttrChangeBO.getMergeMemberId(), memberAttrChangeBO.getMemberId());
        }
        return ServiceResponse.success();
    }

    /**
     * 处理会员线上订单
     *
     * @param params
     * @return
     */
    @Override
    public ServiceResponse<Void> dealMemberOnlineOrder(String params) {
        return dealMemberOrder(params, true);
    }

    private ServiceResponse<Void> dealMemberOrder(String params, boolean isOnlineOrder) {
        if (StringUtils.isBlank(params)) {
            return ServiceResponse.success();
        }
        OrderSaveNotifyDTO orderSaveNotifyDTO = JSON.parseObject(params, OrderSaveNotifyDTO.class);

        if (orderSaveNotifyDTO.getFirstCreate() == null || orderSaveNotifyDTO.getFirstCreate() != 1) {
            log.info("会员订单 非购买事件 {}", params);
            return ServiceResponse.success();
        }
        potentialCustomerService.updateMemberDealFlag(orderSaveNotifyDTO.getEnterpriseId(), orderSaveNotifyDTO.getMemberId());

        String enterpriseId = orderSaveNotifyDTO.getEnterpriseId();
        String memberId = orderSaveNotifyDTO.getMemberId();
        String orderId = orderSaveNotifyDTO.getOrderId();

        ServiceResponse<OrderInfoResp> serviceResponse =
                memberOrderReadApiService.getOrder(enterpriseId, memberId, orderId, isOnlineOrder);
        if (!serviceResponse.isSuccess() || serviceResponse.getResult() == null) {
            log.info("获取订单信息异常 {}", JSON.toJSONString(serviceResponse));
            return ServiceResponse.success();
        }
        OrderInfoResp orderInfoResp = serviceResponse.getResult();
        if (orderInfoResp.getOrderType() == null ||
                !OrderCheckUtil.checkOrderType(orderInfoResp.getOrderType())) {
            log.info("订单 {} 非微盟/自研渠道", orderId);
            return ServiceResponse.success();
        }

        MemberOrderBo memberOrderBo = new MemberOrderBo();
        memberOrderBo.setEnterpriseId(orderSaveNotifyDTO.getEnterpriseId());
        memberOrderBo.setMemberId(orderSaveNotifyDTO.getMemberId());
        memberOrderBo.setOrderId(orderSaveNotifyDTO.getOrderId());
        memberOrderBo.setOrderNumber(orderInfoResp.getRorderNumber());
        memberOrderBo.setOrderTime(orderInfoResp.getOrderTime());
        memberOrderBo.setOrderType(orderInfoResp.getOrderType());
        if (isOnlineOrder) {
            memberOrderBo.setTableName(KafkaMessageServiceImpl.tab_gic_eorder);
        }else {
            memberOrderBo.setTableName(KafkaMessageServiceImpl.tab_gic_order);
        }

        try {
            log.info("发送微盟订单处理消息 {}", params);
            /**
             * @see com.gic.haoban.manage.api.service.content.MallOrderStatusChangeApiService#dealWeimoOrder(String)
             */
            GICMQClientUtil.getClientInstance().sendMessage("dealWeimoOrderForInteractRecord", JSON.toJSONString(memberOrderBo), 120);
        }catch (Exception ex) {
            log.info("处理会员订单异常 ", ex);
        }

        return ServiceResponse.success();
    }

    /**
     * 处理会员线下订单数据
     *
     * @param params
     * @return
     */
    @Override
    public ServiceResponse<Void> dealMemberOffLineOrder(String params) {
        return dealMemberOrder(params, false);
    }

    /**
     * 处理会员新增事件
     *
     * @param params
     * @return
     */
    @Override
    public ServiceResponse<Void> dealMemberEvent(String params) {

        if (StringUtils.isBlank(params)) {
            return ServiceResponse.success();
        }
        CreateMemberEventParam createMemberEventParam = JSON.parseObject(params, CreateMemberEventParam.class);
        String enterpriseId = createMemberEventParam.getEnterpriseId();
        String memberId = createMemberEventParam.getMemberId();

        if (!materialEnterpriseAdaptor.checkEnterpriseHasContentRight(enterpriseId)) {
            log.info("企业 {} 没有内容权限", enterpriseId);
            return ServiceResponse.success();
        }
        QueryMemberInfoDTO queryMemberInfoDTO = QueryMemberInfoDTO
                .queryByMemberId(memberId)
                .setMemberBaseInfoDTO(true)
                .setMemberPersonalInfoDTO(false);
        ServiceResponse<MemberSummaryInfoDTO> serviceResponse = memberOutApiService.queryMemberInfo(queryMemberInfoDTO);
        if (!serviceResponse.isSuccess() || serviceResponse.getResult() == null) {
            log.info("查询会员信息为空 {}", memberId);
            return null;
        }
        String unionId = serviceResponse.getResult().getMemberBaseInfoDTO().getUnionid();
        interactRecordService.memberAuthorized(memberId, unionId);
        return ServiceResponse.success();
    }
}
