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

import cn.hutool.db.DaoTemplate;
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.enums.content.ShareBizType;
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.binlog.MemberOrderBo;
import com.gic.haoban.manage.service.pojo.bo.content.message.InteractRecordMessageBO;
import com.gic.haoban.manage.service.service.content.adaptor.MaterialDataAdaptor;
import com.gic.haoban.manage.service.service.content.message.InteractRecordMessageService;
import com.gic.haoban.manage.service.task.KafkaMessageServiceImpl;
import com.gic.order.api.dto.OrderDTO;
import com.gic.order.api.dto.req.MemberOrderOptional;
import com.gic.order.api.service.member.MemberOrderReadApiService;
import com.gic.orderecommerce.api.service.EcommerceOrderOutputApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @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;
    @Autowired
    private MaterialDataAdaptor materialDataAdaptor;



    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 goodsId = jsonObject.getString("proId");
        String memberId = orderEventMqBO.getMemberId();

        InteractRecordMessageBO interactRecordMessageBO = new InteractRecordMessageBO();
        interactRecordMessageBO.setEnterpriseId(orderEventMqBO.getEnterpriseId());
        interactRecordMessageBO.setMemberId(memberId);
        interactRecordMessageBO.setClerkId(clerkId);
        if (StringUtils.isNotBlank(contentMaterialId) && StringUtils.isNumeric(contentMaterialId)) {
            interactRecordMessageBO.setMaterialId(contentMaterialId);
        }else if (StringUtils.isNotBlank(goodsId) && !StringUtils.isNumeric(goodsId)) {
            interactRecordMessageBO.setGoodsId(goodsId);
        }else {
            log.info("订单扩展信息中无要处理的数据 {}", extendJson);
            return ServiceResponse.success();
        }
        interactRecordMessageBO.setEventType(MaterialInteractRecordEventType.ORDER.getCode());
        interactRecordMessageBO.setDurationTime(0);
        interactRecordMessageBO.setLastAccessTime(orderInfo.getCreateTime().getTime());
        interactRecordMessageBO.setOrderNumber(orderEventMqBO.getOrderNumber());
        interactRecordMessageBO.setTimes(orderEventMqBO.getTimes());
        interactRecordMessageBO.setOrderType(1);
        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;
    }

    /**
     * 处理微盟订单
     * MQ： dealWeimoOrder
     * @param params
     * @return
     */
    @Override
    public ServiceResponse<Void> dealWeimoOrder(String params) {

        //订单分为tab_gic_eorder 和 tab_gic_ordeer
        MemberOrderBo memberOrderBo = JSON.parseObject(params, MemberOrderBo.class);
        if (memberOrderBo == null) {
            return ServiceResponse.success();
        }
        String enterpriseId = memberOrderBo.getEnterpriseId();
        String memberId = memberOrderBo.getMemberId();
        String orderId = memberOrderBo.getOrderId();
        String orderNumber = memberOrderBo.getOrderNumber();
        Date orderTime = memberOrderBo.getOrderTime();
        InteractRecordMessageBO interactRecordMessageBO = new InteractRecordMessageBO();
        interactRecordMessageBO.setEnterpriseId(enterpriseId);
        interactRecordMessageBO.setMemberId(memberId);
        MaterialDataAdaptor.MaterialBizInfo materialBizInfo = materialDataAdaptor.queryMaterialBizInfo(enterpriseId, memberId, orderTime, null);

        if (materialBizInfo == null) {
            if (memberOrderBo.getTimes() == null) {
                memberOrderBo.setTimes(1);
            }
            if (memberOrderBo.getTimes() > 60) {
                log.info("订单消费次数已经超出60次, 不再处理 {}", params);
                return ServiceResponse.success();
            }
            memberOrderBo.setTimes(memberOrderBo.getTimes() + 1);
            try {
                log.info("发送微盟订单处理消息 {}", "dealweimoOrder");
                /**
                 * @see com.gic.haoban.manage.api.service.content.MallOrderStatusChangeApiService#dealWeimoOrder(String)
                 */
                GICMQClientUtil.getClientInstance().sendMessage("dealWeimoOrder", JSON.toJSONString(memberOrderBo), 60);
            }catch (Exception ex) {
                log.info("处理会员订单异常 ", ex);
            }
            return ServiceResponse.success();
        }
        interactRecordMessageBO.setClerkId(materialBizInfo.getClerkId());
        interactRecordMessageBO.setMaterialId(materialBizInfo.getBizId());
        interactRecordMessageBO.setBizType(ShareBizType.MATERIAL.getCode());
        interactRecordMessageBO.setEventType(MaterialInteractRecordEventType.ORDER.getCode());
        interactRecordMessageBO.setDurationTime(0);
        interactRecordMessageBO.setLastAccessTime(System.currentTimeMillis());
        interactRecordMessageBO.setOrderNumber(orderNumber);
        interactRecordMessageBO.setOrderId(orderId);
        if (StringUtils.equalsIgnoreCase(memberOrderBo.getTableName(), KafkaMessageServiceImpl.tab_gic_eorder)) {
            interactRecordMessageBO.setOrderType(2);
        }else {
            interactRecordMessageBO.setOrderType(3);
        }
        interactRecordMessageService.dealRecord(interactRecordMessageBO);

        return ServiceResponse.success();
    }
}
