package xyz.wbsite.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import xyz.wbsite.frame.utils.LocalData;
import xyz.wbsite.frame.utils.MapperUtil;
import xyz.wbsite.frame.utils.Message;
import xyz.wbsite.frame.base.BaseResponse;
import xyz.wbsite.frame.base.ErrorType;
import xyz.wbsite.frame.base.Token;
import xyz.wbsite.frame.utils.LogUtil;
import xyz.wbsite.frame.base.Error;

@Controller
public class AjaxController {

    @RequestMapping("/ajax")
    @ResponseBody
    public BaseResponse ajax(@RequestParam("method") String method,HttpServletRequest request,HttpServletResponse response) {

        BaseResponse baseResponse = new BaseResponse();
        String jsonString = null;
        try {
            if (method == null){
                baseResponse.addError(new Error(ErrorType.BUSINESS_ERROR, "请求方法不能为空!"));
                return baseResponse;
            }
            Token token = LocalData.getToken();
            if (token == null) {
                token = LocalData.getTempToken();
            }
            if (!token.hasResource(method)) {
                baseResponse.addError(new Error(ErrorType.BUSINESS_ERROR, "无权调用该接口!"));
                return baseResponse;
            }

            InputStreamReader isr = new InputStreamReader(request.getInputStream(),"UTF-8");
            BufferedReader in = new BufferedReader(isr);
            jsonString = in.readLine();

            switch (method) {
                // 示例
                case "ajax.example.example":
                    break;
                default:
                    baseResponse.addError(ErrorType.INVALID_PARAMETER, Message.NOT_EXIST_METHOD);
                    break;
            }

        } catch (Exception ex) {
            baseResponse.addError(ErrorType.SYSTEM_ERROR, Message.ERROR_500);
            LogUtil.dumpException(ex);
        } finally {
            if(baseResponse.hasError()) {
                LogUtil.e("请求方法" + method + ", 请求参数：" + jsonString);
                LogUtil.e("返回结果包含异常" + MapperUtil.toJson(baseResponse));
            }
        }
        return baseResponse;
    }
}
