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.dto.store.StoreUserPositionDTO;
import com.cool.store.dto.store.StoreUserUpdateDTO;
import com.cool.store.service.PushService;
import com.cool.store.service.StoreService;
import com.cool.store.service.ThirdFoodService;
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 java.util.Arrays;
import java.util.List;

/**
 * @Author suzhuhong
 * @Date 2025/9/25 14:49
 * @Version 1.0
 */
@Slf4j
@Service
public class StoreUserUpdateListener implements MessageListener {

    @Autowired
    public RedisUtilPool redisUtilPool;
    @Autowired
    StoreService storeService;
    @Autowired
    ThirdFoodService thirdFoodService;

    @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 = "StoreUserUpdateListener:" + message.getMsgID();
        boolean lock = redisUtilPool.setNxExpire(lockKey, message.getMsgID(), CommonConstants.NORMAL_LOCK_TIMES);
        if(lock){
            try {
                List<StoreUserPositionDTO> storeUser = storeService.getStoreUser(Arrays.asList(text));
                if (CollectionUtils.isNotEmpty(storeUser)){
                    //转换 否则验签不通过
                    List<StoreUserUpdateDTO> storeUserUpdateDTOS = JSONObject.parseArray(JSONObject.toJSONString(storeUser), StoreUserUpdateDTO.class);
                    thirdFoodService.pushStoreUser(storeUserUpdateDTOS);
                }
            }catch (Exception e){
                log.error("StoreUserUpdateListener 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;
    }
}
