package com.zzwtec.wechat.sdk.aop.inject.impl;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.zzwtec.wechat.sdk.aop.flow.FlowData;
import com.zzwtec.wechat.sdk.aop.inject.InjectHandler;
import com.zzwtec.wechat.sdk.api.ApiConfigKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class ApiHandler implements InjectHandler {

    private static final String DEFAULT_APP_ID_KEY = "appId";
    @Autowired
    private HttpServletRequest request;



    @Override
    public FlowData preHandle(Object target, Method method, Object... args) {
        String appId = request.getParameter(DEFAULT_APP_ID_KEY);
        ApiConfigKit.setThreadLocalAppId(appId);
        return FlowData.CONTINUE;
    }

    @Override
    public void afterHandler(Object o) {

    }

    @Override
    public Object throwHandler(Exception e) {
        String message = e.getMessage();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message",message);
        modelAndView.addObject("code",-1);
        modelAndView.setView(new FastJsonJsonView());
        return modelAndView;

    }

    @Override
    public void finallyHandler() {
        ApiConfigKit.removeThreadLocalAppId();
    }
}
