package com.platform.util;

import com.alibaba.fastjson.JSONObject;
import com.platform.entity.Result;
import com.platform.exception.CommonBaseException;
import com.platform.interceptor.AuthorizationInterceptor;
import com.platform.service.TokenService;
import com.platform.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;


/**
 * @author harmon
 * @ClassName: ApiBaseAction
 * @gitee https://gitee.com/fuyang_lipengjun/platform
 * @Description: 基础控制类
 * @date 2016年9月2日
 */
public class ApiBaseAction {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 得到request对象
     */
    @Autowired
    protected HttpServletRequest request;
    /**
     * 得到response对象
     */
    @Autowired
    protected HttpServletResponse response;

    @Autowired
    protected TokenService tokenService;

    /**
     * 参数绑定异常
     */
    @ExceptionHandler({BindException.class, MissingServletRequestParameterException.class, UnauthorizedException.class, TypeMismatchException.class})
    @ResponseBody
    public Result bindException(Exception e) {
        if (e instanceof BindException) {
            return toResponsObject(1, "参数绑定异常", e.getMessage());
        } else if (e instanceof UnauthorizedException) {
            return toResponsObject(1, "无访问权限", e.getMessage());
        }
        return toResponsObject(1, "处理异常", e.getMessage());
    }

    /**
     * @param requestCode
     * @param msg
     * @param data
     * @return Map<String,Object>
     * @throws
     * @Description:构建统一格式返回对象
     * @date 2016年9月2日
     * @author zhuliyun
     */
    public Result toResponsObject(int requestCode, String msg, Object data) {
        return Result.failure(requestCode,msg,data);
    }

    public Result toResponsSuccess(Object data) {
        return Result.success(data);
    }

    public Result toResponsMsgSuccess(String msg) {
        return toResponsSuccess(msg);
    }

    public Result toResponsFail(String msg) {
        return Result.failure(msg);
    }

    /**
     * initBinder 初始化绑定 <br>
     * 这里处理了3种类型<br>
     * 1、字符串自动 trim 去掉前后空格 <br>
     * 2、java.util.Date 转换为 "yyyy-MM-dd HH:mm:ss" 格式<br>
     * 3、java.sql.Date 转换为 "yyyy-MM-dd" 格式<br>
     * 4、java.util.Timestamps 时间转换
     *
     * @param binder  WebDataBinder 要注册的binder
     * @param request 前端请求
     */
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {

        // 字符串自动Trim
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
    }

    /**
     * 获取请求方IP
     *
     * @return 客户端Ip
     */
    public String getClientIp() {
    	String xff = request.getHeader("X-Real-IP");
    	if(xff!=null) {
    		return xff;
    	}
        xff = request.getHeader("x-forwarded-for");
        if (xff == null) {
            return "8.8.8.8";
        }
        return xff;
    }

    public JSONObject getJsonRequest() {
        JSONObject result = null;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            result = JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 获取请求的用户Id
     *
     * @return 客户端Ip
     */
    public Long getUserId() {
        String token = request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY);
        Claims claims = null;
        try{
            claims = JwtUtil.parseJWT(token);
        }catch (Exception e){
            throw new CommonBaseException(401,"请先登录");
        }
        return Long.valueOf(claims.get("id", String.class));
    }

    /**
     * 获取请求的用户Id
     *
     * @return 客户端Ip
     */
    public String getUserName() {
        String token = request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY);

        Claims claims;
        try{
            claims = JwtUtil.parseJWT(token);
        }catch (Exception e){
            throw new CommonBaseException(401,"请先登录");
        }
        return claims.get("username", String.class);
    }

    public String getWeixinOpenid() {
        String token = request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY);
        Claims claims;
        try{
            claims = JwtUtil.parseJWT(token);
        }catch (Exception e){
            throw new CommonBaseException(401,"请先登录");
        }
        return claims.get("weixin_openid", String.class);
    }
}
