package cn.hmsoft.ai.baidu;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import cn.hmsoft.ai.util.AiParamUtil;
import cn.hmsoft.frame.data.dao.FrameModuleDao;
import cn.hmsoft.frame.data.model.FrameModule;
import cn.hmsoft.helper.CollectionHelper;
import cn.hmsoft.helper.LocalDateHelper;
import cn.hmsoft.helper.StringHelper;

/**************************
 * 获取百度toketn的服务，确保唯一访问
 */
@Service
public class BaiduTokenService {
	public static String ACCESS_TOKEN = "";
	public static LocalDateTime ACCESS_TOKEN_EXPIRES = null;

	@Autowired
	private FrameModuleDao daoModule;

	@Transactional(isolation = Isolation.SERIALIZABLE)
	public boolean getBaiduToken() {
		if (ACCESS_TOKEN == null || ACCESS_TOKEN_EXPIRES == null
				|| ACCESS_TOKEN_EXPIRES.isBefore(LocalDateTime.now())) {
			
		}else {
			return true;
		}
		FrameModule module = this.daoModule.find(FrameModule.class, "module_name", AiParamUtil.ModuleName);
		Map<String, String> paramMap = StringHelper.toMap(module.getModule_param());
		String access_token = CollectionHelper.getParamValue(paramMap, AiParamUtil.ParamName_BaiduIdPhotoToken, "");
		String access_token_expired = CollectionHelper.getParamValue(paramMap,
				AiParamUtil.ParamName_BaiduIdPhotoTokenExpireTime, "");
		ACCESS_TOKEN = access_token;
		ACCESS_TOKEN_EXPIRES = LocalDateHelper.parseDateTime(access_token_expired);

		if (ACCESS_TOKEN == null || ACCESS_TOKEN_EXPIRES == null
				|| ACCESS_TOKEN_EXPIRES.isBefore(LocalDateTime.now())) {
			String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
			String getAccessTokenUrl = authHost
					// 1. grant_type为固定参数
					+ "grant_type=client_credentials"
					// 2. 官网获取的 API Key
					+ "&client_id=" + AiParamUtil.ParamMap.get(AiParamUtil.ParamName_BaiduIdPhotoAppKey).trim()
					// 3. 官网获取的 Secret Key
					+ "&client_secret=" + AiParamUtil.ParamMap.get(AiParamUtil.ParamName_BaiduIdPhotoSecretKey).trim();
			try {
				URL realUrl = new URL(getAccessTokenUrl);
				// 打开和URL之间的连接
				HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
				connection.setRequestMethod("GET");
				connection.connect();

				// 定义 BufferedReader输入流来读取URL的响应
				BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				String result = "";
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
				/**
				 * 返回结果示例
				 */
				JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
				ACCESS_TOKEN = jsonObject.get("access_token").getAsString();
				ACCESS_TOKEN_EXPIRES = LocalDateTime.now().plusSeconds(jsonObject.get("expires_in").getAsInt());
				// 更新数据库
				module.setModule_param(module.getModule_param()
						.replace("BaiduIdPhotoToken:" + access_token, "BaiduIdPhotoToken:" + ACCESS_TOKEN)
						.replace("BaiduIdPhotoTokenExpireTime:" + access_token_expired,
								"BaiduIdPhotoTokenExpireTime:" + LocalDateHelper.format(ACCESS_TOKEN_EXPIRES)));
				this.daoModule.update(module);
				return true;
			} catch (Exception e) {
				System.err.printf("获取token失败！");
				e.printStackTrace(System.err);
			}
			return false;
		}

		return true;

	}

}
