package org.springblade.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.controller.vo.*;
import org.springblade.common.controller.vo.jllj.TestEntity;
import org.springblade.common.utils.HttpClientUtil;
import org.springblade.common.utils.ReflectUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.TimeZone;

/**
 * app公共接口调用，通过反射分发调用接口
 *
 * @author wth
 */
@Slf4j
@RestController
@RequestMapping("/commonBd")
public class CommonRequestControllerBd {

	/**
	 * 利用反射调用接口
	 */
	@PostMapping("reflectControl")
	public ResponseVO reflectControl(RequestVO commonObj) {
		ResponseVO responseVO = new ResponseVO();
		String condition = commonObj.getParams().getData().getCondition();
		log.info("利用反射调用接口获取反射参数：" + condition);
		//本地
		RequestCommonVO requestParams = JSONObject.parseObject(condition.substring(6, condition.length() - 1), RequestCommonVO.class);
		String className = requestParams.getClassName();
		String methodName = requestParams.getMethodName();
		Map<String, Object> params = requestParams.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);
				ObjectMapper objectMapper = new ObjectMapper()
					.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
					.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
					.setDateFormat(new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"))
					.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
				String jsonString = objectMapper.writeValueAsString(resObj);

//				String value = JSONObject.toJSONString(resObj);
				responseVO.getResult().getData().add(new ResponseDataVO());
				responseVO.getResult().getData().get(0).getFieldValues().add(new ResponseFieldValuesVO(jsonString));
				return responseVO;
			} else {
				responseVO.getResult().setMsg("未找到对应方法");
				return responseVO;
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseVO.getResult().setMsg(e.getMessage());
			return responseVO;
		}
	}


	/**
	 * 公共新增接口
	 */
	@PostMapping("/add")
	public ResponseVO commonAdd(@RequestBody RequestVO commonObj) {
		return reflectControl(commonObj);
	}

	/**
	 * 公共删除接口
	 */
	@PostMapping("/delete")
	public ResponseVO commonDelete(@RequestBody RequestVO commonObj) {
		return reflectControl(commonObj);
	}

	/**
	 * 公共修改接口
	 */
	@PostMapping("/edit")
	public ResponseVO commonEdity(@RequestBody RequestVO commonObj) {
		return reflectControl(commonObj);
	}

	/**
	 * 公共查询接口
	 */
	@PostMapping("/query")
	public Object commonQuery(@RequestBody RequestVO commonObj) {
		log.info("二类区接收参数params" + commonObj.toString());
		if (commonObj.getMethod().equals("connect")) {
			TestEntity testEntity = new TestEntity();
			testEntity.setId("1");
			testEntity.setJsonrpc("2.0");
			TestEntity.ResultBean result = new TestEntity.ResultBean();
			result.setCode("1");
			result.setSign("1qqqqwwwwwwwwwwwwww");
			result.setMsg("OK");
			TestEntity.ResultBean.DataBean data = new TestEntity.ResultBean.DataBean();
			data.setNonce("QswduIyb");
//			二类
//			data.setAppId("4eeb7eb13f9c4753ad3263de95b71ff1");
//			data.setSessionId("4eeb7eb13f9c4753ad3263de95b71ff1");
			//三类
			data.setAppId("e1bf9f1751bc4798ae4b56d000823de8");
			data.setSessionId("e1bf9f1751bc4798ae4b56d000823de8");
			data.setTimestamp(getTimestamp());
			result.setData(data);
			testEntity.setResult(result);
			return JSONObject.toJSON(testEntity);
		} else {
			return connectToAuthorization(commonObj);
		}
	}

	/**
	 * 新的公共查询接口query1
	 */
	@PostMapping("/query1")
	public Object commonQuery1(@RequestBody RequestVO commonObj) {
		return reflectControl(commonObj);
	}
	/**
	 * 一类到二类信大捷安connect转发后没有携带请求头，重新转发后封装请求头
	 */
	@PostMapping("/connectToAuthorization")
	public String  connectToAuthorization(@RequestBody RequestVO commonObj) {
		log.info("封装请求头是传递参数："+commonObj.toString());
		String condition = commonObj.getParams().getData().getCondition();
		//本地
		RequestCommonVO requestParams = JSONObject.parseObject(condition.substring(6, condition.length() - 1), RequestCommonVO.class);
		String headValue = requestParams.getToken();
		String url ="";
		//线上
//		if("4eeb7eb13f9c4753ad3263de95b71ff1".equals(commonObj.getParams().getData().getSessionId())){
//			url = "http://localhost:6543/common/query1";
//		}else{
//			url = "http://localhost:6543/common/query1";
//		}
		//本地
		url = "http://localhost:6543/commonBd/query1";
		String s = HttpClientUtil.doPost1(url, (JSONObject) JSONObject.toJSON(commonObj), headValue);
		return s;
	}


	/**
	 * 二类区转发三类区
	 * @param commonObj
	 * @return
	 */
	@PostMapping("/zfThreebd")
	public String zfThreebd(@RequestBody RequestVO commonObj) {
		String condition = commonObj.getParams().getData().getCondition();
		RequestCommonVO requestParams = JSONObject.parseObject(condition.substring(6, condition.length() - 1), RequestCommonVO.class);
		String headValue = requestParams.getToken();
//		 将app请求转发到三类区
		String result3 = HttpClientUtil.doPost1("http://localhost:6541/common/query", (JSONObject) JSONObject.toJSON(commonObj), headValue);
		return result3;
	}





	/**
	 * 获取时间戳工具类
	 * @return
	 */
	public static String getTimestamp() {
		LocalDateTime now = LocalDateTime.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
		String formattedDateTime = now.format(formatter);
		return formattedDateTime;
	}

	/**
	 * 封装一类到二类connect参数
	 * @return
	 */
	public static ConnectVo getConnectVo(RequestVO commonObj) {
		ConnectVo connectVo = new ConnectVo();
		connectVo.setJsonrpc("2.0");
		connectVo.setId("1");
		connectVo.setMethod("connect");
		ConnectDataVO connectDataVO = new ConnectDataVO();
		connectDataVO.setVersion("20190221");
		connectDataVO.setAppId(commonObj.getParams().getData().getSessionId());
		connectDataVO.setTimestamp(getTimestamp());
		connectDataVO.setNonce("vMksKOwd");
		ConnectParamsVO connectParamsVO = new ConnectParamsVO();
		connectParamsVO.setData(connectDataVO);
		connectParamsVO.setSign("1qqqqwwwwwwwwwwwwww");
		connectVo.setParams(connectParamsVO);
		return connectVo;
	}



}
