package org.springblade.modules.zf.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.utils.ParamsConvert;
import org.springblade.common.utils.ReflectUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.http.util.HttpUtil;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.modules.application.info.pojo.entity.ApplicationInfoEntity;
import org.springblade.modules.application.info.service.IApplicationInfoService;
import org.springblade.modules.zf.pojo.vo.*;
import org.springblade.modules.zf.pojo.vo.credential.CredentialVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

/**
 * 应用列表 控制器
 *
 * @author BladeX
 * @since 2024-10-15
 */
@RestController
@AllArgsConstructor
@RequestMapping("zf")
@Tag(name = "应用列表", description = "应用列表接口")
public class ZfController extends BladeController {

	@Autowired
	private Environment env;

	private final BladeRedis bladeRedis;

	private final IApplicationInfoService applicationInfoService;

	@PostMapping("/request")
	public String request(@RequestBody RequestVO requestVO, @RequestHeader Map<String, String> headers) {
		String activeProfile = env.getActiveProfiles()[0];
		System.out.println("Active Profiles: " + activeProfile);
		// 解析固定的请求格式
		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 (activeProfile.equals("prod")) {
			// 如果当前是三类区，需要验证用户凭证
			CredentialVO userCredential = requestCommonVO.getUserCredential();
			String result = HttpUtil.postJson("url", JSONObject.toJSONString(userCredential));
		}
		QueryWrapper<ApplicationInfoEntity> queryWrapper = new QueryWrapper<>();
		if ((requestCommonVO.getAppId() == null || requestCommonVO.getAppId() == -1L) && requestCommonVO.getMethodName().equals("token3")) {
			queryWrapper.likeLeft("jkdz", ":6543/transpond/request");
			queryWrapper.last("limit 1");
		} else {
			queryWrapper.eq("id", requestCommonVO.getAppId());
		}
		// 获取要转发到的接口地址
		ApplicationInfoEntity appInfoEntity = applicationInfoService.getOne(queryWrapper);
		// 调用
		String result = HttpUtil.postJson(appInfoEntity.getJkdz(), headers, JSONObject.toJSONString(requestVO));
//		fieldValuesVO.setValue(result);
		// 返回结果
//		responseVO.getData().getDataList().get(0).getFieldValues().add(fieldValuesVO);
		return result;
	}

	/**
	 * 反射
	 */
	@Transactional
	@PostMapping("/reflect")
	public ResponseVO reflect(@RequestBody RequestVO requestVO, @RequestHeader Map<String, String> headers) {
		// 解析固定的请求格式
		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();
		// 反射调用接口
		String result = JSONObject.toJSONString(reflectControl(requestCommonVO));
		fieldValuesVO.setValue(result);
		// 返回结果
		responseVO.getData().getDataList().get(0).getFieldValues().add(fieldValuesVO);
		return responseVO;
	}

	private Object reflectControl(RequestCommonVO commonObj) {
		String className = commonObj.getClassName();
		String methodName = commonObj.getMethodName();
		Map<String, Object> params = commonObj.getParams();
		try {
			//1、获取spring容器中的Bean
			//类名首字母小写
			className = StringUtils.uncapitalize(className);
			Object proxyObject = ReflectUtil.getBean(className);
			//2、利用bean获取class对象，进而获取本类以及父类或者父接口中所有的公共方法(public修饰符修饰的)
			Method[] methods = proxyObject.getClass().getMethods();
			//3、获取指定的方法
			Method myMethod = null;
			for (Method method : methods) {
				if (method.getName().equalsIgnoreCase(methodName)) {
					myMethod = method;
					break;
				}
			}
			//4、封装方法需要的参数
			if (myMethod != null) {
				Object resObj = ParamsConvert.paramsConvert(proxyObject, className, myMethod, params);
				return resObj;
			} else {
				return "未找到对应方法";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}

}
