package com.cool.store.mq.consumer.listener;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.cool.store.constants.CommonConstants;
import com.cool.store.dao.decoration.ShopDecorationAssignDAO;
import com.cool.store.dto.store.StoreUserPositionDTO;
import com.cool.store.dto.store.StoreUserUpdateDTO;
import com.cool.store.entity.decoration.ShopDecorationAssignDO;
import com.cool.store.service.DecorationHandleService;
import com.cool.store.utils.RedisUtilPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @Author suzhuhong
 * @Date 2025/11/3 10:13
 * @Version 1.0
 */
@Slf4j
@Service
public class ShopDecorationAssignListener implements MessageListener {

    @Autowired
    public RedisUtilPool redisUtilPool;
    @Resource
    DecorationHandleService decorationHandleService;
    @Resource
    ShopDecorationAssignDAO shopDecorationAssignDAO;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        String text = new String(message.getBody());
        if(StringUtils.isBlank(text)){
            log.info("消息体为空,tag:{},messageId:{}",message.getTag(),message.getMsgID());
            return Action.CommitMessage;
        }
        String lockKey = "ShopDecorationAssignListener:" + message.getMsgID();
        boolean lock = redisUtilPool.setNxExpire(lockKey, message.getMsgID(), CommonConstants.NORMAL_LOCK_TIMES);
        if(lock){
            try {
                ShopDecorationAssignDO shopDecorationAssignDO = shopDecorationAssignDAO.getById(Long.valueOf(text));
                decorationHandleService.handleDecorationTeam(shopDecorationAssignDO);
            }catch (Exception e){
                log.error("ShopDecorationAssignListener consume error",e);
                return Action.ReconsumeLater;
            }finally {
                redisUtilPool.delKey(lockKey);
            }
            log.info("消费成功,tag:{},messageId:{},reqBody={}",message.getTag(),message.getMsgID(),text);
            return Action.CommitMessage;
        }
        return Action.ReconsumeLater;
    }
}
