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.buser.UserEventDTO;
import com.cool.store.dto.dept.DepartmentEventDTO;
import com.cool.store.enums.RocketMqTagEnum;
import com.cool.store.service.EnterpriseSyncService;
import com.cool.store.utils.RedisUtilPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zhangchenbiao
 * @FileName: EnterpriseInitService
 * @Description: 消息监听
 * @date 2023-06-09 16:28
 */
@Slf4j
@Service
public class FeiShuEventListener implements MessageListener {

    @Autowired
    private RedisUtilPool redisUtilPool;
    @Autowired
    private EnterpriseSyncService enterpriseSyncService;

    @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;
        }
        log.info("重试消费次数 messageId：{}，try times：{}", message.getMsgID(), message.getReconsumeTimes());
        String lockKey = "DingMsgDealListener:" + message.getMsgID();
        boolean lock = redisUtilPool.setNxExpire(lockKey, message.getMsgID(), CommonConstants.NORMAL_LOCK_TIMES);
        if(lock){
            try {
                RocketMqTagEnum tag = RocketMqTagEnum.getByTag(message.getTag());
                switch (tag){
                    case USER_EVENT:
                        UserEventDTO userBody = JSONObject.parseObject(text, UserEventDTO.class);
                        enterpriseSyncService.userUpdateEvent(userBody);
                        break;
                    case AUTH_SCOPE_CHANGE:
                        enterpriseSyncService.syncAll();
                        break;
                    case DEPT_EVENT:
                        DepartmentEventDTO deptBody = JSONObject.parseObject(text, DepartmentEventDTO.class);
                        enterpriseSyncService.deptUpdateEvent(deptBody);
                        break;
                    default:
                        break;
                }
            }catch (Exception e){
                log.error("DingMsgDealListener consume dealAddressBookChange error",e);
                return Action.ReconsumeLater;
            } finally {
                redisUtilPool.delKey(lockKey);
            }
            log.info("消费成功,tag:{},messageId:{}",message.getTag(),message.getMsgID());
            return Action.CommitMessage;
        }
        return Action.ReconsumeLater;
    }
}
