package com.docus.server.common.consumer.receiver;

import com.docus.server.common.bean.Result;
import com.docus.server.common.consumer.bean.HandleResult;
import com.docus.server.common.consumer.service.Receiver;
import com.docus.server.common.message.MessageData;
import com.docus.server.common.type.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Copyright © 2018 五月工作室. All rights reserved.
 *
 * @Package com.docus.taskdistribute.common.send
 * @ClassName SendService
 * @Description 定义通用消息接收处理基类
 * @Author Amos
 * @Modifier
 * @Date 2019/7/1 15:11
 * @Version 1.0
 **/
public abstract class AbstractReceiver implements Receiver {

    private static final Logger logger = LoggerFactory.getLogger(AbstractReceiver.class);

    /**
     * 用户自定义消息处理
     *
     * @param messageData
     * @return
     */
    public abstract HandleResult exec(MessageData messageData) throws Exception;

    /**
     * 用户自定义验证
     *
     * @param messageData
     * @return
     */
    public abstract Result validate(MessageData messageData);

    /**
     * 成功处理
     *
     * @param messageData
     * @return
     */
    public abstract HandleResult handleSuccess(MessageData messageData);

    /**
     * 失败处理
     *
     * @param messageData
     * @return
     */
    public abstract HandleResult handleFail(MessageData messageData);

    /**
     * 处理
     *
     * @param messageData
     * @return
     */
    @Override
    public final HandleResult handleMessage(MessageData messageData) {
        logger.info(this.getClass().getSimpleName() + "-->handleMessage()参数 unicomData:{}", messageData.toString());
        HandleResult handleResult = null;
        try {
            // 如果自定义验证不通过
            Result result = this.validate(messageData);
            if (!ResultEnum.success().equals(result.getCode())) {
                // 如果验证失败 进行失败处理

                return this.handleFail(messageData);
            }
            // 根据自行处理的返回结果
            handleResult = this.exec(messageData);

            // 执行成功处理的逻辑
            handleResult = this.handleSuccess(messageData);
        } catch (Exception e) {
            e.printStackTrace();
            messageData.setContent(e.getMessage());
            return this.handleFail(messageData);
        }
        return handleResult;
    }

}
