package com.tzld.piaoquan.api.mq;


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.tzld.piaoquan.api.model.bo.ReplyInfo;
import com.tzld.piaoquan.api.model.param.CallbackParam;
import com.tzld.piaoquan.growth.common.dao.mapper.PushMessageCallbackMapper;
import com.tzld.piaoquan.growth.common.model.po.PushMessageCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class MessageCallbackCustomer implements MessageListener {


    @Autowired
    private PushMessageCallbackMapper pushMessageCallbackMapper;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        CallbackParam param = JSONObject.parseObject(new String(message.getBody()), CallbackParam.class);
        log.info("param = {}", param);
        if (CollectionUtils.isEmpty(param.getReplyInfo())) {
            //log.error("CallbackParam replyInfo is empty {}", param);
        }
        PushMessageCallback pushMessageCallback = new PushMessageCallback();
        pushMessageCallback.setGhId(param.getGhId());
        pushMessageCallback.setTimestamp(param.getTimestamp());
        pushMessageCallback.setOpenId(param.getOpenId());
        pushMessageCallback.setCreateTime(new Date());
        List<PushMessageCallback> insertList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(param.getReplyInfo())) {
            for (ReplyInfo replyInfo : param.getReplyInfo()) {
                PushMessageCallback insertPushMessageCallback = new PushMessageCallback();
                BeanUtils.copyProperties(pushMessageCallback, insertPushMessageCallback);
                insertPushMessageCallback.setMsgType(replyInfo.getMsgType());
                insertPushMessageCallback.setVideoId(replyInfo.getMiniVideoId());
                insertList.add(insertPushMessageCallback);
            }
        }
        try {
            if(!CollectionUtils.isEmpty(insertList)){
                pushMessageCallbackMapper.insertList(insertList);
            }
        } catch (Exception e) {
            log.error("PushMessageCallback newPushMessageCallbackMapper insert pushMessageCallback={}, error={}", pushMessageCallback, e.getMessage());
            return Action.ReconsumeLater;
        }
        return Action.CommitMessage;
    }
}
