package com.mortals.xhx.busiz.web;

import com.alibaba.fastjson.JSON;
import com.mortals.xhx.busiz.handler.BaseReqHandler;
import com.mortals.xhx.busiz.rsp.ApiResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.util.Map;

@Slf4j
public class BaseAbstractApiController {
    private Map<String, BaseReqHandler> handlers;
    @Autowired
    private ApplicationContext context;

    @SuppressWarnings("unchecked")
    protected <T, K> ApiResp<K> handle(T apiReq, String handleName) {
        BaseReqHandler reqHandler = handlers.get(handleName);
        if (!ObjectUtils.isEmpty(reqHandler)) {
            return reqHandler.process(apiReq);
        } else {
            log.warn(String.format("没有找到业务处理类 handleName:%s", handleName));
            return null;
        }
    }

    protected String getTransmissionAction(String transmissionReq) {
        return JSON.parseObject(transmissionReq).getJSONObject("transmission").getString("action");
    }

    @PostConstruct
    private void init() {
        handlers = context.getBeansOfType(BaseReqHandler.class);
    }
}
