package com.mortals.xhx.busiz.handler;


import com.mortals.framework.exception.AppException;
import com.mortals.xhx.busiz.req.ApiReqPdu;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.busiz.rsp.ApiRespPdu;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

/**
 * 骨架类
 * @author:
 * @date: 2023/1/6 15:38
 */
@Slf4j
public abstract class BaseReqHandler<T, K> implements ReqHandler {

    /**
     * 处理请求
     *
     * @param request
     * @return
     */
    public ApiResp<K> process(T request) {
        try {
            validData(request);
            return handle(request);
        } catch (Throwable t) {
            log.error("异常：", t);
            return null;
        }
    }

    /**
     * 业务处理
     *
     * @param request
     * @return
     * @throws AppException
     */
    protected abstract ApiResp<K> handle(T request) throws AppException;

    private ApiRespPdu<K> getApiResponsePdu(ApiRespCodeEnum result, K data, Throwable t) {
        ApiRespPdu<K> response = new ApiRespPdu<>();
        response.setCode(result.getValue());
        response.setMsg(ObjectUtils.isEmpty(t) ? result.getLabel() : t.getMessage());
        response.setData(data);

        return response;
    }

    /**
     * 校验数据
     *
     * @param request
     * @return
     * @throws Exception
     */
    protected abstract void validData(T request) throws IllegalArgumentException;


}
