package com.fzm.mall.server.front.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fzm.mall.server.front.constant.MALLGlobalConfig;
import com.fzm.mall.server.front.order.model.Pay;
import com.fzm.mall.server.front.order.service.IOrderService;
import com.fzm.mall.server.front.order.service.IPayService;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class orderCloseCousumer {

    @Autowired
    private IPayService payService;

    @Autowired
    private IOrderService orderService;

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = MALLGlobalConfig.projectMq+".order.close.queue"), exchange = @Exchange(value = MALLGlobalConfig.projectMq+"-order-exchange"), key = MALLGlobalConfig.projectMq+".order.close.key") })
    public void receiver(String message) {
        if(StringUtil.isNullOrEmpty(message)){
            log.error("orderPayConsumer:message为空");
            return;
        }
        Pay pay = payService.getByPid(message);
        if(pay == null){
            log.error("orderPayConsumer:pid:"+message +"订单不存在");
            return;
        }
        if(pay.getState()!=3 && pay.getState()!=6){
            log.error("orderPayConsumer:pid:"+message +"订单状态不成功");
            return;
        }
        String oidsJson = pay.getOidsJson();
        JSONArray oids = JSON.parseArray(oidsJson);
        for (Object oid:oids) {
            orderService.close(oid);
        }
        pay.setState(2);
        payService.updateById(pay);
    }

}
