package cc.smtweb.framework.core.mvc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * API接口控制器，所有API的入口
 *
 * @author xkliu
 */
@RestController
public class ApiController {
    @Autowired
    private MethodAccessManager methodAccessManager;

    /**
     * 处理API的GET请求
     *
     * @param params   URL请求参数
     * @param request  Http请求类
     * @param response Http应答类
     * @return 返回对象，一般在函数里面使用R
     * @throws Exception API处理异常
     */
    @GetMapping(value = "/api/**", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public Object commonGet(@RequestParam Map<String, Object> params,
                            HttpServletRequest request, HttpServletResponse response) throws Exception {
        String apiUrl = request.getServletPath().substring(5);
        return methodAccessManager.invoke(apiUrl, params, null, request, response);
    }

    /**
     * 处理API的POST请求
     *
     * @param params   URL请求参数
     * @param body     POST内容，JSON格式
     * @param request  Http请求类
     * @param response Http应答类
     * @return 返回对象，一般在函数里面使用R
     * @throws Exception API处理异常
     */
    @PostMapping(value = "/api/**", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public Object commonPost(@RequestParam Map<String, Object> params, @RequestBody(required = false) String body,
                             HttpServletRequest request, HttpServletResponse response) throws Exception {
        String apiUrl = request.getServletPath().substring(5);
        // 保证body在post的清空下不为null，用于区分get时吧参数组合成body
        if (body == null) {
            body = "";
        }
        return methodAccessManager.invoke(apiUrl, params, body, request, response);
    }

    @PreDestroy
    public void fin() {
        methodAccessManager.showdown();
    }
}
