package com.ssj.conch.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ssj.framework.core.util.PropertiesUtil;
import com.ssj.weixin.utils.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yangcan
 * 类描述:AI识别服务调用工具类
 * 创建时间:2018年12月26日 下午2:58:57

 */
public class AIServiceUtils {
	//aigpu服务器公网
//	public static String AI_SERVICE_URL = "http://47.106.35.168:5000";
	//aigpu服务器内网
	public static String AI_SERVICE_URL = "http://172.18.106.201:5000";
	private static Logger logger = LoggerFactory.getLogger(AIServiceUtils.class);


	/**
	 * @param filePath
	 * @return
	 * @throws Exception
	
	 * 方法说明:算数计算识别对错
	
	 * 创立日期:2018年12月26日 下午3:35:36
	 * 创建人:yangcan
	
	 */
	public static String calculateAI(String filePath, String ossPath) throws Exception {
		String result = null;
		Map<String,String> querys=new HashMap<String, String>();
    	querys.put("file_path", filePath);
    	querys.put("oss_path", ossPath);
    	HttpResponse response = HttpUtils.doPost(AI_SERVICE_URL, "/",
    			"POST", 
    			new HashMap<String, String>(), 
    			new HashMap<String, String>(), 
    			querys
    			);
		System.out.println(response);
    	if(response.getStatusLine().getStatusCode()==200){
    		result = EntityUtils.toString(response.getEntity());
    		if(!"Error".equals(result)){
    			return result;
    		}else{
    			return null;
    		}
    	}
    	return result;
	}
	
	/**
	 * @param filePath
	 * @return
	 * @throws Exception
	
	 * 方法说明:答题卡识别(废弃)  返参:{ “Wrong_No.”: [0. 0. 0. 0. 0. 1. 1. 1. 1. 0. 0. 0. 0. 0. 1.]}
	 * 创立日期:2018年12月26日 下午3:40:42
	 * 创建人:yangcan
	
	 */
//	public static String answerDetectAI(String filePath) throws Exception {
//		String result = null;
//		Map<String,String> querys=new HashMap<String, String>();
//    	querys.put("file_path", filePath);
//    	HttpResponse response = HttpUtils.doPost("http://47.112.205.102:8080", "/AnswerDetect",
//    			"POST", 
//    			new HashMap<String, String>(), 
//    			new HashMap<String, String>(), 
//    			querys
//    			);
//    	if(response.getStatusLine().getStatusCode()==200){
//    		result = EntityUtils.toString(response.getEntity());
//    		if(!"Error".equals(result)){
//    			return result;
//    		}else{
//    			return null;
//    		}
//    	}
//    	return result;
//	}

	/**
	 * @param querys
	 * @return
	 * @throws Exception

	 * 方法说明:以题搜题

	 * 创立日期:2018年12月26日 下午3:35:36
	 * 创建人:yangcan

	 */
	public static String recognitionExerciseBook (Map<String, String> querys) throws Exception {
		String result = null;
		HttpResponse response = HttpUtils.doPost(AI_SERVICE_URL, "/query",
				"POST",
				new HashMap<String, String>(),
				new HashMap<String, String>(),
				querys
		);

		logger.info("请求ai返回{}", JSON.toJSONString(response));
		if(response.getStatusLine().getStatusCode()==200){
			result = EntityUtils.toString(response.getEntity());
			if(!"Error".equals(result)){
				return result;
			}else{
				return null;
			}
		}
		return result;
	}
	/**
	 * @param querys
	 * @return
	 * @throws Exception

	 * 方法说明: 使用oss网络图片请求识别练习册的接口

	 * 创立日期:2019年10月22日
	 * 创建人:chchen

	 */
	public static String recognitionExerciseBookV1 (Map<String, String> querys) throws Exception {
		String result = null;
		HttpResponse response = HttpUtils.doPost(AI_SERVICE_URL, "/query_via_oss",
				"POST",
				new HashMap<String, String>(),
				new HashMap<String, String>(),
				querys
		);

		logger.info("请求ai返回{}", JSON.toJSONString(response));
		if(response.getStatusLine().getStatusCode()==200){
			result = EntityUtils.toString(response.getEntity());
			if(!"Error".equals(result)){
				return result;
			}else{
				return null;
			}
		}
		return result;
	}

	/**
	 * @param querys
	 * @return
	 * @throws Exception

	 * 方法说明: 使用oss网络图片请求识别练习册的接口

	 * 创立日期:2019年10月22日
	 * 创建人:chchen

	 */
	public static String recognitionExerciseBookV2 (Map<String, String> querys) throws Exception {
		String result = null;
		HttpResponse response = HttpUtils.doPost(AI_SERVICE_URL, "/querySimilarQuestionAsync",
				"POST",
				new HashMap<String, String>(),
				new HashMap<String, String>(),
				querys
		);

		logger.info("请求ai返回{}", JSON.toJSONString(response));
		if(response.getStatusLine().getStatusCode()==200){
			result = EntityUtils.toString(response.getEntity());
			if(!"Error".equals(result)){
				return result;
			}else{
				return null;
			}
		}
		return result;
	}


	/**
	 * @param querys
	 * @return
	 * @throws Exception

	 * 方法说明: 查询相似题

	 * 创立日期:2019年10月22日
	 * 创建人:chchen

	 */
	public static String querySimilarQuestion (Map<String, String> querys) throws Exception {
		String result = null;
		HttpResponse response = HttpUtils.doPost(AI_SERVICE_URL, "/querySimilarQuestion",
				"POST",
				new HashMap<String, String>(),
				new HashMap<String, String>(),
				querys
		);

		logger.info("请求ai返回{}", JSON.toJSONString(response));
		if(response.getStatusLine().getStatusCode()==200){
			result = EntityUtils.toString(response.getEntity());
			if(!"Error".equals(result)){
				return result;
			}else{
				return null;
			}
		}
		return result;
	}

	/**
	 * @param
	 * @return 
	 * 方法说明:ai图片识别文本内容
	 * 创建时间:2019/7/12 11:27
	 * @author yangcan
	 */
	public static String discernPicture(String filePath) throws Exception {
		String result = null;
		Map<String,String> querys = new HashMap<String, String>();
		querys.put("file_path", filePath);
		HttpResponse response = HttpUtils.doPost(AI_SERVICE_URL, "/discernPicture",
				"POST",
				new HashMap<String, String>(),
				new HashMap<String, String>(),
				querys
		);
		if(response.getStatusLine().getStatusCode()==200){
			result = EntityUtils.toString(response.getEntity());
			if(!"Error".equals(result)){
				JSONObject jsonObject = JSON.parseObject(result);
				if ("success".equals(jsonObject.getString("status"))){
					StringBuffer sb = new StringBuffer();
					JSONArray contentArray = jsonObject.getJSONObject("data").getJSONArray("content");
					for (int i = 0; i < contentArray.size(); i++) {
						sb.append(contentArray.get(i).toString());
					}
					return sb.toString();
				}
			}else{
				return null;
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		try {
//			Map<String, String> querys = new HashMap<>();
//			querys.put("path", "/www/files/data/upload/2020/04/13/e8656971b1634bad87354e9eaf4d4c90.png");
//			querys.put("ossPath", "https://img-sharingschool.oss-cn-shenzhen-internal.aliyuncs.com/2020/04/13/e8656971b1634bad87354e9eaf4d4c90.png");
//			querys.put("subject", "数学");
//			querys.put("grade", "二年级下册");
//			querys.put("version", "");
//			querys.put("mode", "question");
//			long begin = System.currentTimeMillis();
//			String result = AIServiceUtils.recognitionExerciseBookV1(querys);
//			long end = System.currentTimeMillis();
//			System.out.println((end - begin)/1000);
//			System.out.println(result);
			String str = "{\"quantity\":3,\"subject\":\"语文\",\"knowledge\":{\"日积月累\":[\"de0885fc-34b7-11e9-a55b-00163e04df3f\"],\"重点内容、语句理解\":[\"de088597-34b7-11e9-a55b-00163e04df3f\"],\"文章基本内容\":[\"cf109cd6-5b2f-458f-90e8-dea7757f5cdc\"],\"提取信息\":[\"e906dadd-c133-4f41-8210-68ce2f05494f\"],\"词语搭配\":[\"30eb7ae9-12cf-4829-8eba-38fc59b2cfc3\"]}}";
			JSONObject jsonObject = JSON.parseObject(str);
			AIServiceUtils.queryTrainingRecommendedQuestions(jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("线程1开始");

//		try {
//			Map<String, String> querys = new HashMap<>();
//			querys.put("path", "/www/files/xtdata/upload/2019/12/11/57f77089f0a14404ab671934ac052b85.jpg");
//			querys.put("ossPath", "https://xt-sharingschool.oss-cn-shenzhen-internal.aliyuncs.com/2019/12/11/57f77089f0a14404ab671934ac052b85.jpg");
//			querys.put("subject", "");
//			querys.put("grade", "");
////			querys.put("version", "");
////			querys.put("mode", "question");
//			System.out.println(JSONObject.toJSON(querys));
//			long begin = System.currentTimeMillis();
//			String result = AIServiceUtils.querySimilarQuestion(querys);
//			long end = System.currentTimeMillis();
//			System.out.println((end - begin)/1000);
//			System.out.println(result);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}

//		try {
//			Map<String, String> querys = new HashMap<>();
//			querys.put("path", "/www/files/xtdata/upload/2019/12/11/57f77089f0a14404ab671934ac052b85.jpg");
//			querys.put("ossPath", "https://xt-sharingschool.oss-cn-shenzhen-internal.aliyuncs.com/2019/12/11/57f77089f0a14404ab671934ac052b85.jpg");
//			querys.put("subject", "");
//			querys.put("grade", "");
////			querys.put("version", "");
////			querys.put("mode", "question");
//			System.out.println(JSONObject.toJSON(querys));
//			long begin = System.currentTimeMillis();
//			String result = AIServiceUtils.querySimilarQuestion(querys);
//			long end = System.currentTimeMillis();
//			System.out.println((end - begin)/1000);
//			System.out.println(result);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}

//        try {
//            String url = "https://xt.sharingschool.com/sz/api/common/common/uploadForm";
//            String filePath = "/images/111.png";
//
//            RestTemplate rest = new RestTemplate();
//            FileSystemResource resource = new FileSystemResource(new File(filePath));
//            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
//            param.add("files", resource);
//            param.add("accessToken", "FBA31BBCFBDA43ECA57317D384E2FFB9");
//
//            String string = rest.postForObject(url, param, String.class);
//
//            JSONObject jo = JSONObject.parseObject(string);
//
//            String str = jo.getJSONObject("data").getJSONArray("pics").getJSONObject(0).getString("filePath");
//            System.out.println(str);
//
//            Map<String, String> querys = new HashMap<>();
//			querys.put("path", "/www/files/xtdata/upload" + str);
//			querys.put("subject", "语文");
//			querys.put("grade", "六年级上册");
//			querys.put("version", "");
//			querys.put("mode", "question");
//			long begin = System.currentTimeMillis();
//			String result = AIServiceUtils.recognitionExerciseBook(querys);
//			long end = System.currentTimeMillis();
//			System.out.println((end - begin)/1000);
//			System.out.println(result);
//
//        } catch (Exception e){
//            e.printStackTrace();
//        }


//		System.out.println("----------------------------------------------------------------");
//		String path = "/www/files/data/upload/2020/01/16/231e263a201e4d5a81aa0a0deed8019a.jpg";
//        //String path = "";
//		String ossPath = "https://img.sharingschool.com/2020/01/16/231e263a201e4d5a81aa0a0deed8019a.jpg";
//		try{
//			long begin = System.currentTimeMillis();
//			String result = AIServiceUtils.calculateAI(path, ossPath);
//			long end = System.currentTimeMillis();
//			System.out.println((end - begin)/1000);
//			System.out.println("返回结果:"+result);
//		} catch (Exception e){
//			e.printStackTrace();
//		}
	}

	/**
	 * 根据知识点推荐题目，每个知识点推荐指定数量的题目（以大题为单位），每道大题下的小题数量需要做限制（语文、数学科目小于等于3道，英语不限），
	 * 相似度规则优先于题目数量限制（如果某知识点下只有两道题，但不符合相似度规则，只能二选一）
	 *
	 * @param bodyMap post请求的body参数
	 * @return 查询结果
	 */
	public static JSONObject queryTrainingRecommendedQuestions(Map<String, Object> bodyMap) {
		try {
			HttpResponse response = HttpUtils.doPost(AI_SERVICE_URL, "/queryTrainingRecommendedQuestions",
					"POST",
					Collections.emptyMap(),
					Collections.emptyMap(),
					JSON.toJSONString(bodyMap),
					10000);

			if (response.getStatusLine().getStatusCode() != 200) {
				logger.info("调用AI提分训练题目推荐接口失败，bodyMap={}，response={}", JSON.toJSONString(bodyMap), JSON.toJSONString(response));
				return null;
			}
			String result = EntityUtils.toString(response.getEntity());
			if ("Error".equals(result)) {
				logger.info("调用AI提分训练题目推荐接口失败，bodyMap={}，result=Error", JSON.toJSONString(bodyMap));
				return null;
			}
			JSONObject resultMap = JSON.parseObject(result);
			if (!"success".equals(resultMap.getString("status"))) {
				logger.info("调用AI提分训练题目推荐接口失败，result={}", result);
				return null;
			}
			return resultMap.getJSONObject("data");
		} catch (ConnectTimeoutException e) {
			logger.error("bodyMap={}", JSON.toJSONString(bodyMap));
			logger.error("调用AI提分训练题目推荐接口响应超时");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("status", "Timeout");
			return jsonObject;
		} catch (Exception e) {
			logger.error("bodyMap={}", JSON.toJSONString(bodyMap));
			logger.error("调用AI提分训练题目推荐接口异常", e);
		}
		return null;
	}
}
