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.ServiceResponse;
import com.gic.business.order.dto.ordermanage.OrderOutInfoDTO;
import com.gic.business.order.enums.OrderEnum;
import com.gic.business.order.qdto.ordermanage.OrderInfoQDTO;
import com.gic.business.order.service.ordermanage.OrderInfoOutApiService;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.haoban.manage.api.enums.content.MaterialInteractRecordEventType;
import com.gic.haoban.manage.api.service.content.MallOrderStatusChangeApiService;
import com.gic.haoban.manage.service.pojo.bo.content.InteractRecordBO;
import com.gic.haoban.manage.service.pojo.bo.content.OrderEventMqBO;
import com.gic.haoban.manage.service.pojo.bo.content.message.InteractRecordMessageBO;
import com.gic.haoban.manage.service.service.content.message.InteractRecordMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author MUSI
 * @Date 2023/4/6 5:28 PM
 * @Description
 * @Version
 **/
@Slf4j
@Component("mallOrderStatusChangeApiService")
public class MallOrderStatusChangeApiServiceImpl implements MallOrderStatusChangeApiService {


    @Autowired
    OrderInfoOutApiService orderInfoOutApiService;
    @Autowired
    InteractRecordMessageService interactRecordMessageService;

    private static final String ORDER_EVENT_RETRY = "orderEventRetryMQ";

    /***
     * 订单状态变更事件
     * @param params
     * @return
     */
    @Override
    public ServiceResponse<Void> mallOrderStatusChange(String params) {

        log.info("【MallOrderStatusChangeApiService】处理微商城订单状态变更事件 {}", params);
        OrderEventMqBO orderEventMqBO = JSON.parseObject(params, OrderEventMqBO.class);
        if (orderEventMqBO == null) {
            log.info("订单状态变更事件参数异常 {}", params);
            return ServiceResponse.success();
        }

        Integer toStatus = orderEventMqBO.getToStatus();
        if (!OrderEnum.OrderNodeEnum.PAY_ORDER.getOrderStep().equals(toStatus)) {
            log.info("订单事件不是支付事件 {}", toStatus);
            return ServiceResponse.success();
        }

        OrderInfoQDTO orderInfoQDTO = new OrderInfoQDTO();
        orderInfoQDTO.setEnterpriseId(orderEventMqBO.getEnterpriseId());
        orderInfoQDTO.setOrderNumber(orderEventMqBO.getOrderNumber());
        ServiceResponse<OrderOutInfoDTO> serviceResponse = orderInfoOutApiService.queryOrderInfo(orderInfoQDTO);
        if (!serviceResponse.isSuccess()) {
            log.info("查询订单信息异常 {}", JSON.toJSONString(serviceResponse));
            return ServiceResponse.success();
        }
        OrderOutInfoDTO orderInfo = serviceResponse.getResult();
        String extendJson = orderInfo.getExtendJson();
        if (StringUtils.isBlank(extendJson)) {
            log.info("订单扩展字段为空,不处理 params: {}", params);
            return ServiceResponse.success();
        }

        JSONObject jsonObject = JSON.parseObject(extendJson, JSONObject.class);
        String clerkId = jsonObject.getString("clerkId");
        String contentMaterialId = jsonObject.getString("contentMaterialId");
        String memberId = orderEventMqBO.getMemberId();

        InteractRecordMessageBO interactRecordMessageBO = new InteractRecordMessageBO();
        interactRecordMessageBO.setEnterpriseId(orderEventMqBO.getEnterpriseId());
        interactRecordMessageBO.setMemberId(memberId);
        interactRecordMessageBO.setClerkId(clerkId);
        interactRecordMessageBO.setMaterialId(contentMaterialId);
        interactRecordMessageBO.setEventType(MaterialInteractRecordEventType.ORDER.getCode());
        interactRecordMessageBO.setDurationTime(0);
        interactRecordMessageBO.setLastAccessTime(orderInfo.getCreateTime().getTime());
        interactRecordMessageBO.setOrderNumber(orderEventMqBO.getOrderNumber());
        interactRecordMessageBO.setTimes(orderEventMqBO.getTimes());

        InteractRecordBO interactRecordBO = interactRecordMessageService.getInteractRecordBOWithOrderType(interactRecordMessageBO);
        if (interactRecordBO == null) {
            log.info("订单事件先到达,埋点事件延迟  >>> {}", JSON.toJSONString(interactRecordMessageBO));
            if (orderEventMqBO.getTimes() != null && orderEventMqBO.getTimes() > 60) {
                log.info("订单事件延迟60分钟仍未被消费,忽略 {}", params);
                return ServiceResponse.success();
            }
            if (orderEventMqBO.getTimes() == null) {
                orderEventMqBO.setTimes(0);
            }
            orderEventMqBO.setTimes(orderEventMqBO.getTimes() + 1);
            this.sendDelayMessage(orderEventMqBO);
            return ServiceResponse.success();
        }

        interactRecordMessageService.dealRecord(interactRecordMessageBO);
        return ServiceResponse.success();
    }

    /**
     * 兼容订单事件先到达 埋点数据未到的情况
     *
     * @param params
     * @return
     */
    @Override
    public ServiceResponse<Void> orderEventDelay(String params) {
        // 处理埋点数据延迟的问题
        log.info("处理埋点数据延迟 订单事件先到的场景 >>>> {}", params);
        return this.mallOrderStatusChange(params);
    }


    public boolean sendDelayMessage(OrderEventMqBO orderEventMqBO) {
        log.info("[MallOrderStatusChangeApiService] 发送订单支付事件延迟处理消息 {}", JSON.toJSONString(orderEventMqBO));
        try {
            GICMQClientUtil.getClientInstance().sendMessage(ORDER_EVENT_RETRY, JSON.toJSONString(orderEventMqBO), 60);
        } catch (Exception e) {
            log.info("发送消息异常 {}", JSON.toJSONString(orderEventMqBO), e);
            return false;
        }
        return true;
    }
}
