package com.pcloud.book.consumer.isbn;

import com.pcloud.book.book.entity.Book;
import com.pcloud.book.util.common.HttpUtils;
import com.pcloud.book.util.properties.BookProps;
import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.enums.ImageTypeEnum;
import com.pcloud.common.utils.FileUtils;
import com.pcloud.common.utils.UUIDUitl;
import com.pcloud.common.utils.aliyun.OssUtils;
import com.pcloud.common.utils.string.StringUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 通过isbn获取书籍信息
 * 
 * @author:lili
 * @date 创建时间：2017年2月27日 下午3:25:15
 * @version 1.0
 * @return
 */
@Component("isbnConsr")
public class IsbnConsr {

	/**
	 * 
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(IsbnConsr.class);

	/**
	 * 根据isbn返回书籍信息返回书籍对象
	 */
	public Book getBook(String isbn) throws IOException {
		LOGGER.info("【外部】根据isbn获取书籍信息,<START>.[isbn]=" + isbn);
//		Book book = null;
//		try {
			/*String result = getBookInfo4jisu(isbn);
			book = setBook4jisu(result, isbn);
			if (book == null || book.getIsbn() == null) {
				// 调用聚合查询书籍
				String juheBook = getBookInfo(isbn);
				book = setBook(juheBook, isbn);
			}*/
			//if (book == null || book.getIsbn() == null) {
			// 调用阿里查询书籍
//			String aliBook = getBookInfo4Ali(isbn);
//			book = setBook4Ali(aliBook, isbn);
//			//	}
//		} catch (Exception e) {
//			LOGGER.warn("【外部】根据isbn获取书籍信息,<ERROR>", e);
//		}
//		LOGGER.info("【外部】根据isbn获取书籍信息,<END>");
//		return book;
		return null;
	}

	/**
	 * 设置书籍
	 * 
	 * @param result
	 * @param isbn
	 * @return
	 */
//	private Book setBook4Ali(String result, String isbn) {
//		Map<String, Object> temp = JSONObject.parseObject(result);
//		Book book = new Book();
//		if (null != temp) {
//			String errorCode = (String) temp.get("status");
//			// 如果返回成功
//			if ("0".equals(errorCode)) {
//				Map<String, String> bookInfo = (Map<String, String>) temp.get("result");
//				if (!(MapUtils.isEmpty(bookInfo) || StringUtil.isEmpty(bookInfo.get("title")))) {
//					book.setIsbn(isbn);
//					book.setAuthor(bookInfo.get("author"));
//					book.setPublishDate(DateChange(bookInfo.get("pubdate")));
//					book.setRemark(bookInfo.get("summary"));
//					book.setPublish(bookInfo.get("publisher"));
//					book.setBookPrice(bookInfo.get("price"));
//					book.setCoverImg(changePic(bookInfo.get("pic")));
//					book.setBookName(bookInfo.get("title"));
//					book.setDetail(bookInfo.get("summary"));
//					book.setTypeCode(BookTypeEnum.BOOK.value);
//				}
//			}
//		}
//		return book;
//	}

	/**
	 * 设置书籍
	 * 
	 * @param result
	 * @param isbn
	 * @return
	 */
//	@SuppressWarnings("unchecked")
//	private Book setBook4jisu(String result, String isbn) {
//		LOGGER.info("设置书籍result="+result+"isbn="+isbn);
//		if (StringUtil.isEmpty(result)) {
//			return null;
//		}
//		Map<String, Object> temp = JSONObject.parseObject(result);
//		Book book = new Book();
//		if (null != temp) {
//			String errorCode = (String) temp.get("status");
//			// 如果返回成功
//			if ("0".equals(errorCode)) {
//				Map<String, String> bookInfo = (Map<String, String>) temp.get("result");
//				if (!(MapUtils.isEmpty(bookInfo) || StringUtil.isEmpty(bookInfo.get("title")))) {
//					book.setIsbn(isbn);
//					book.setAuthor(bookInfo.get("author") == null ? null : bookInfo.get("author").toString());
//					book.setPublishDate(DateChange(bookInfo.get("pubdate")));
//					book.setRemark(bookInfo.get("summary"));
//					book.setPublish(bookInfo.get("publisher"));
//					book.setBookPrice(bookInfo.get("price"));
//					book.setCoverImg(changePic(bookInfo.get("pic")));
//					book.setBookName(bookInfo.get("title"));
//					book.setDetail(bookInfo.get("summary"));
//					book.setTypeCode(BookTypeEnum.BOOK.value);
//				}
//			}
//		}
//		return book;
//	}

	/**
	 * 修改图片地址
	 * 
	 * @param picUrl
	 * @return
	 */
	private String changePic(String picUrl) {
		String coverImg = "";
		if (StringUtil.isEmpty(picUrl)) {
			coverImg = BookProps.getBookCoverImg();
		} else {
			if (picUrl.contains("\\")) {
				coverImg = picUrl.replace("\\", "");
			} else {
				coverImg = picUrl;
			}
			try {
				byte[] file_buff = FileUtils.downloadByteFromUrl(coverImg);
				UploadResultInfo uploadResultInfo = OssUtils.uploadFileByte(file_buff, UUIDUitl.taskName(),
						ImageTypeEnum.JPG.value);
				if (uploadResultInfo != null) {
					coverImg = uploadResultInfo.getUrl();
				} else {
					coverImg = BookProps.getBookCoverImg();
				}
			} catch (Exception e) {
				coverImg = BookProps.getBookCoverImg();
			}
		}
		return coverImg;
	}

	/**
	 * 设置书籍
	 * 
	 * @param result
	 * @param isbn
	 * @return @
	 */
//	@SuppressWarnings("unchecked")
//	private Book setBook(String result, String isbn) {
//		Book book = new Book();
//		Map<String, Object> temp = JSONObject.parseObject(result);
//		if (null != temp) {
//			Integer errorCode = (Integer) temp.get("error_code");
//			// 如果返回成功
//			if (errorCode == 0) {
//				Map<String, String> bookInfo = (Map<String, String>) temp.get("result");
//				if (!MapUtils.isEmpty(bookInfo)) {
//					book.setIsbn(isbn);
//					book.setAuthor(bookInfo.get("author"));
//					book.setPublishDate(DateChange(bookInfo.get("pubdate")));
//					book.setOriginName(bookInfo.get("origin_title"));
//					book.setRemark(bookInfo.get("summary"));
//					book.setPublish(bookInfo.get("publisher"));
//					book.setBookPrice(bookInfo.get("price"));
//					book.setCoverImg(changePic(bookInfo.get("images_medium")));
//					book.setBookName(bookInfo.get("title"));
//					book.setDetail(bookInfo.get("summary"));
//					book.setTypeCode(BookTypeEnum.BOOK.value);
//				}
//			}
//		}
//		return book;
//	}

	/**
	 * 根据isbn 查询书籍信息返回json
	 */
	public String getBookInfo(String isbn) throws IOException {
		LOGGER.info("【外部】根据isbn获取书籍信息,<START>.[isbn]=" + isbn);
		// 创建HttpClient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String result = null;
		try {
			String url = "http://feedback.api.juhe.cn/ISBN?sub=" + isbn + "&key=" + BookProps.getAppkey();
			HttpGet httpGet = new HttpGet(url);
			// 执行网络请求
			response = httpClient.execute(httpGet);
			// 获取请求实体
			HttpEntity resEntity = response.getEntity();
			if (resEntity != null) {
				// ConverStreamToString是下面写的一个方法是把网络请求的字节流转换为utf8的字符串
				result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
			}
			EntityUtils.consume(resEntity);
		} catch (Exception e) {
			LOGGER.error("【外部】根据isbn获取书籍信息,<ERROR>:" + e.getMessage(), e);
		} finally {
			// 关闭请求
			if (response != null) {
				response.close();
			}
			if (httpClient != null) {
				httpClient.close();
			}

		}
		return result;
	}

	/**
	 * 根据isbn 查询书籍信息返回json
	 */
	public String getBookInfo4jisu(String isbn) throws IOException {
		LOGGER.info("【外部】根据isbn获取书籍信息,<START>.[isbn]=" + isbn);
		// 创建HttpClient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String result = null;
		try {
			String url = "http://api.jisuapi.com/isbn/query?isbn=" + isbn + "&appkey=" + BookProps.getJisuAppKey();
			HttpGet httpGet = new HttpGet(url);
			// 执行网络请求
			response = httpClient.execute(httpGet);
			// 获取请求实体
			HttpEntity resEntity = response.getEntity();
			if (resEntity != null) {
				// ConverStreamToString是下面写的一个方法是把网络请求的字节流转换为utf8的字符串
				result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
			}
			EntityUtils.consume(resEntity);
		} catch (Exception e) {
			LOGGER.warn("【外部】根据isbn获取书籍信息,<ERROR>:" + e.getMessage(), e);
		} finally {
			// 关闭请求
			if (response != null) {
				response.close();
			}
			if (httpClient != null) {
				httpClient.close();
			}
		}
		return result;
	}

	/**
	 * 根据isbn 查询书籍信息返回json
	 */
	public String getBookInfo4Ali(String isbn) {
		LOGGER.warn("【外部ali】根据isbn获取书籍信息,<START>.[isbn]=" + isbn);
		String host = "http://aliapi63.jisuapi.com";
		String path = "/isbn/query";
		String method = "GET";
		Map<String, String> headers = new HashMap<String, String>();
		// 最后在header中的格式(中间是英文空格)为Authorization:APPCODE
		// 83359fd73fe94948385f570e3c139105
		headers.put("Authorization", "APPCODE " + BookProps.getAppCode());
		Map<String, String> querys = new HashMap<String, String>();
		querys.put("isbn", isbn);
		String result = "";
		try {
			/**
			 * 重要提示如下: HttpUtils请从
			 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
			 * 下载
			 *
			 * 相应的依赖请参照
			 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
			 */
			HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
			// 获取response的body
			if (response.getEntity() != null) {
				// ConverStreamToString是下面写的一个方法是把网络请求的字节流转换为utf8的字符串
				result = ConvertStreamToString(response.getEntity().getContent(), "UTF-8");
			}
		} catch (Exception e) {
			LOGGER.error("查询书籍失败" + e.getMessage(), e);
		} 

		return result;
	}

	/**
	 * 此方法是把传进的字节流转化为相应的字符串并返回，此方法一般在网络请求中用到
	 */
	public String ConvertStreamToString(InputStream is, String charset) throws Exception {
		StringBuilder sb = new StringBuilder();
		try (InputStreamReader inputStreamReader = new InputStreamReader(is, charset)) {
			try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\r\n");
				}
			}
		}
		return sb.toString();
	}

//	/**
//	 * 时间转换
//	 *
//	 * @param dateStr
//	 * @return
//	 */
//	public static String DateChange(String dateStr) {
//		if (!(StringUtils.contains(dateStr, '年'))) {
//			if (dateStr != null) {
//				if (dateStr.length() == 6 || dateStr.length() == 7) {
//					return dateStr + "-1";
//				} else if (dateStr.length() == 4) {
//					return dateStr + "-1-1";
//				}
//			}
//		}
//		try {
//			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月");
//			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月DD日");
//			SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年");
//			if (dateStr.contains("年") && dateStr.contains("月") && dateStr.contains("日")) {
//				return DateUtils.formatDate(sdf2.parse(dateStr));
//			} else if (dateStr.contains("年") && dateStr.contains("月")) {
//				return DateUtils.formatDate(sdf1.parse(dateStr));
//			} else if (dateStr.contains("年")) {
//				return DateUtils.formatDate(sdf3.parse(dateStr));
//			} else {
//				dateStr = DateUtils.formatDate(DateUtils.getDateByStr(dateStr));
//			}
//		} catch (Exception e) {
//			dateStr = null;
//		}
//		if (StringUtil.isEmpty(dateStr)) {
//			dateStr = null;
//		}
//		return dateStr;
//	}

}
