package com.union.ai.api.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.util.Base64Util;
import com.union.ai.api.dto.Result;
import com.union.ai.api.enums.ErrorEnum;
import com.union.ai.api.util.CheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * Author: xingxin.jing
 * Date: 2018/12/15
 * Time: 上午8:44
 * 监控点controller
 */
@Slf4j
@Component
@Aspect
public class BodySecurityAspect extends CommonSecurityAspect {

	/**
	 * 前置通知
	 * @param joinPoint
	 */
	@Override
	@Around("execution(* com.union.ai.api.controller.body..*(..))") //该标签声明次方法是一个前置通知：在目标方法开始之前执行
	public Object beforeMethod(ProceedingJoinPoint joinPoint) throws Throwable {

		ServletRequestAttributes ra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ra.getRequest();
		Map<String, String[]> parameterMap = request.getParameterMap();
		if (CheckUtil.isNull(parameterMap)) {
			return new Result(ErrorEnum.ERROR_100000).toString();
		}
		JSONObject object = new JSONObject();
		for (String key : parameterMap.keySet()) {
			String[] values = parameterMap.get(key);
			if (values.length == 0) {
				log.info("key={}值为空", key);
				continue;
			}
			object.put(key, parameterMap.get(key)[0]);
		}
		Object proceed = this.proceed(joinPoint, object.toString());
//		Object proceed = joinPoint.proceed();
		if (proceed != null)
		{
			JSONObject jsonObject = JSON.parseObject(proceed.toString());
			log.info("结果：" + proceed.toString());
			if (jsonObject.get("err_no") != null) {
				jsonObject.put("error_code", jsonObject.remove("err_no"));
			}
			if (jsonObject.get("err_msg") != null) {
				jsonObject.put("error_msg", jsonObject.remove("err_msg"));
			}
			Integer error_code = jsonObject.getInteger("error_code");
			if (new Integer(0).equals(error_code))
			{
				String result = jsonObject.getString("result");
				if (StringUtils.isNotBlank(result)) {
					String s = new String(Base64Util.decode(result), "UTF-8");

					jsonObject.put("result", JSON.parse(s));
				}
			}
			return jsonObject.toJSONString();
		}
		return proceed;
	}

}