package org.springblade.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.utils.ReflectUtil;
import org.springblade.common.vo.*;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 转发 控制器
 *
 * @author wth
 * @since 2024-07-04
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/transpond")
public class ZfController extends BladeController {

	/**
	 * 转发
	 */
	@Transactional
	@PostMapping("/request")
	@ApiOperationSupport(order = 1)
	public ResponseVO request(@RequestBody RequestVO requestVO, @RequestHeader Map<String, String> headers) throws Exception {
		// 解析固定的请求格式
		KeyValueVO keyValueVO = requestVO.getParameter().getCondition().getKeyValueList().get(0);
		RequestCommonVO requestCommonVO = JSONObject.parseObject(keyValueVO.getValue(), RequestCommonVO.class);
		// 拼装固定的返回格式
		ResponseVO responseVO = new ResponseVO();
		responseVO.getData().getDataList().add(new DataListVO());
		FieldValuesVO fieldValuesVO = new FieldValuesVO();
		if ((AuthUtil.getUserId() == null || AuthUtil.getUserId().equals(-1L)) && !requestCommonVO.getClassName().equals("bladeTokenEndPoint")) {
			fieldValuesVO.setValue(JSONObject.toJSONString(R.fail(401, "请求未授权，请重新登录")));
		} else if (!requestCommonVO.getClassName().equals("")) {
			String className = StringUtils.uncapitalize(requestCommonVO.getClassName());
			String methodName = requestCommonVO.getMethodName();
			Object proxyObject = ReflectUtil.getBean(className);
			Method[] methods = proxyObject.getClass().getMethods();
			Method myMethod = null;
			for (Method method : methods) {
				if (method.getName().equalsIgnoreCase(methodName)) {
					myMethod = method;
					break;
				}
			}
			Map<String, Object> params = new HashMap<>();
			if (requestCommonVO.getMethodName().equals("token3")) {
				params.put("username", requestCommonVO.getUsername());
				params.put("password", requestCommonVO.getPassword());
			} else {
				params = requestCommonVO.getParams();
			}
			if (myMethod != null) {
				Object resObj = ParamsConvert.paramsConvert(proxyObject, className, myMethod, params);
				fieldValuesVO.setValue(JSONObject.toJSONString(resObj));
			}
		}
		// 返回结果
		responseVO.getData().getDataList().get(0).getFieldValues().add(fieldValuesVO);
		return responseVO;
	}
}
