package com.fjs.scenic.service.scenic.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fjs.scenic.entity.scenic.Scenic;
import com.fjs.scenic.entity.scenic.ScenicDescription;
import com.fjs.scenic.entity.scenic.TicketInformation;
import com.fjs.scenic.mapper.good.GoodsMapper;
import com.fjs.scenic.mapper.news.NewsMapper;
import com.fjs.scenic.mapper.scenic.PicsMapper;
import com.fjs.scenic.mapper.scenic.ScenicMapper;
import com.fjs.scenic.mapper.scenic.TicketInformationMapper;
import com.fjs.scenic.service.scenic.ScenicDescriptionService;
import com.fjs.scenic.service.scenic.ScenicIndexService;
import com.fjs.scenic.utils.ReturnResult;
import com.github.pagehelper.util.StringUtil;

@Service
public class ScenicIndexServiceImpl implements ScenicIndexService {

	private Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private ScenicMapper scenicMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private NewsMapper newsMapper;
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private ScenicDescriptionService scenicDescriptionService;
	@Autowired
	private TicketInformationMapper ticketInformationMapper;
	@Autowired
	private PicsMapper picsMapper;

	@Override
	public ReturnResult scenic(String flage) {
		if (StringUtils.isBlank(flage)) {
			flage = "0";
		}
		JSONObject object = (JSONObject) redisTemplate.opsForValue().get("indexTopData:" + flage);
		if (object != null) {
			redisTemplate.expire("indexTopData", 2, TimeUnit.DAYS);
			return ReturnResult.ok(object);
		}

		JSONObject json = new JSONObject();
		Scenic scenic = scenicMapper.selectByPrimaryKey(1);
		if (scenic == null) {
			ReturnResult.build(500, "网络异常，请稍后再试");
		}
		ScenicDescription scenicDescription = scenicDescriptionService.selectByScenicId(scenic.getId());
		json.put("scenicId", scenic.getId());
		json.put("scenicName", scenic.getName());
		json.put("intro", scenic.getIntro());
		json.put("description", scenicDescription.getDescription());
		json.put("voidUrl", scenic.getVoidUrl());
		json.put("phone", scenic.getPhone());
		json.put("businessTime", scenic.getBusinessTime());
		List<String> news = newsMapper.getNewsLimt3();
		json.put("news", news);
		List<Map<String, String>> goods = goodsMapper.getAllGoodsAndMinPrice(flage);
		json.put("goods", goods);
		Map<String, String> picmap = picsMapper.getIndexPicAndCount(scenic.getId());
		if (picmap != null) {
			json.put("count", picmap.get("count"));
			json.put("picUrl", picmap.get("picUrl"));
		}

		// 查詢购票须知（暂时去掉）
		TicketInformation ticketInformation = ticketInformationMapper.selectByScenicId(1);
		json.put("ticketInformation", ticketInformation);
		redisTemplate.opsForValue().set("indexTopData:" + flage, json, 2, TimeUnit.DAYS);
		return ReturnResult.ok(json);
	}

	// @Override
	// public ReturnResult scenic() {
	// JSONObject json = new JSONObject();
	// Scenic scenic = scenicMapper.selectByPrimaryKey(1);
	// if (scenic == null) {
	// ReturnResult.build(500, "网络异常，请稍后再试");
	// }
	// ScenicDescription scenicDescription =
	// scenicDescriptionService.selectByScenicId(scenic.getId());
	// json.put("scenicId", scenic.getId());
	// json.put("scenicName", scenic.getName());
	// json.put("intro", scenic.getIntro());
	// json.put("description", scenicDescription.getDescription());
	// json.put("voidUrl", scenic.getVoidUrl());
	// json.put("phone", scenic.getPhone());
	// json.put("businessTime", scenic.getBusinessTime());
	// Map<String, String> picmap =
	// picsMapper.getIndexPicAndCount(scenic.getId());
	// if (picmap != null) {
	// json.put("count", picmap.get("count"));
	// json.put("picUrl", picmap.get("picUrl"));
	// }
	//// 门票（暂时去掉）
	//// List<Map<String, String>> goods = goodsMapper.getAllGoodsAndMinPrice();
	//// json.put("goods", goods);
	// // 查詢新闻前3条
	// List<String> news = newsMapper.getNewsLimt3();
	// json.put("news", news);
	// // 查詢购票须知（暂时去掉）
	//// TicketInformation ticketInformation =
	// ticketInformationMapper.selectByScenicId(1);
	//// json.put("ticketInformation", ticketInformation);
	// return ReturnResult.ok(json);
	// }

	@Override
	public ReturnResult getWeather(String url) {
		// 取缓存中的weather值和地点名称
		JSONObject object = (JSONObject) redisTemplate.opsForValue().get("weather");

		// 上次调取天气的时间
		Date oldDate = (Date) redisTemplate.opsForValue().get("weatherDate");
		Date date = new Date();

		// 若日期相等且地点相同返回缓存中的值
		if (object != null && oldDate.getDay() == date.getDay()) {
			return ReturnResult.ok(object);
		}

		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				log.info(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			object = JSONObject.parseObject(result);

			// 将返回对象，地点参数，调取时间存入redis
			redisTemplate.opsForValue().set("weather", object);
			redisTemplate.opsForValue().set("weatherDate", date);
		} catch (Exception e) {
			log.error("发送GET请求出现异常！");
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}

		return ReturnResult.ok(object);
	}

}
