package com.ibeetl.admin.flow.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
 
/**
 * 百度统计数据获取工具类
 */
public class HttpSend {
	
	private static final JSONObject HEADER = new JSONObject();
	private static final String API_SITE;// 获取站点ID，获取当前用户下的站点和子目录列表以及对应参数信息，不包括权限站点和汇总网站。
	private static final String API_DATA;// 根据站点ID获取站点报告数据。
	private static final String API_URL;// 接口URL相同部分
 
	static {
		HEADER.put("username", "18971900646");
		HEADER.put("password", "06260030yK");
		HEADER.put("token", "38dcf8c2b8e0b9a7ec208075e0b7cc03");//
		HEADER.put("account_type", "1");
		API_SITE = "getSiteList";
		API_DATA = "getData";
		API_URL = "https://api.baidu.com/json/tongji/v1/ReportService/";
	}
	
	/**
	 * 根据URL发送请求
	 * @param url
	 * @param content
	 * @return
	 */
	private static String sendRequest(String url, String content) {
		System.out.println("sendRequest start");
		URLConnection conn = null;
		try {
			conn = new URL(url).openConnection();
			StringBuffer sb=null;
			
			if(conn!=null){
				System.out.println("connnect succeed");
				conn.setUseCaches(false);
				conn.setDoInput(true);
				conn.setDoOutput(true);
				conn.setRequestProperty("Content-Length", "" + content.length());
				conn.setRequestProperty("Cache-Control", "no-cache");
				conn.setRequestProperty("Content-Type", "application/json");
				
				DataOutputStream stream = new DataOutputStream(conn.getOutputStream());
				stream.write(content.getBytes("UTF-8"));
				stream.close();
				
				BufferedReader br = null;
				try {
					br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				sb = new StringBuffer();
				String str = br.readLine();
				while (str != null) {
					sb.append(str);
					str = br.readLine();
				}
				br.close();
			}
			System.out.println("sendRequest end");
			return sb.toString();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 获取用户的站点列表
	 * 文档地址：//http://tongji.baidu.com/open/api/more?p=tongjiapi_getSiteList.tpl
	 * @return
	 */
	public static JSONObject getSite() {
		System.out.println("getSite start");
		
		JSONObject body = new JSONObject();
		body.put("method", API_SITE);// 接口方法名称
		
		JSONObject content = new JSONObject();
		content.put("header", HEADER);
		content.put("body", body);
		
		String result=sendRequest(API_URL + API_SITE, content.toJSONString());
		System.out.println("return data:"+JSON.parseObject(result));
		
		System.out.println("getSite end");
		return JSON.parseObject(result);
	}
 
	/**
	 * 根据站点 ID 获取站点报告数据
	 * @param siteId 站点ID
	 * @param method 要查询的报告 method名称
	 * @param startDate 开始时间
	 * @param endDate 结束时间
	 * @param metrics 指标
	 * @param gran 时间粒度
	 * 文档地址：http://tongji.baidu.com/open/api/more?p=tongjiapi_getData.tpl
	 * @return
	 */
	public static JSONObject getData(String siteId,String method,String startDate,String endDate,String metrics,String gran) {
		System.out.println("getData start");
		JSONObject body = new JSONObject();
		body.put("site_id", siteId);//站点id
		body.put("method", method);//通常对应要查询的报告
		body.put("start_date", startDate);//查询起始时间,例：20160501
		body.put("end_date", endDate);//查询结束时间,例：20160531
		//body.put("start_date2", "");//对比查询起始时间
		//body.put("end_date2", "");//对比查询结束时间
		body.put("metrics",metrics);//自定义指标选择，多个指标用逗号分隔
		body.put("gran", gran);//时间粒度(只支持有该参数的报告): day/hour/week/month
		// body.put("order", "1");//指标排序，示例：visitor_count,desc
		// body.put("start_index", "1");//获取数据偏移，用于分页；默认是0
		body.put("max_results", "0");//单次获取数据条数，用于分页；默认是20; 0表示获取所有数据
		
		JSONObject content = new JSONObject();
		content.put("header", HEADER);
		content.put("body", body);
		
		String result=sendRequest(API_URL + API_DATA, content.toJSONString());
		
		System.out.println("return data:"+JSON.parseObject(result));
		System.out.println("getData end");
		return JSON.parseObject(result);
	}
	
	/**
	 * 获取抖音当月时间为上月最后一天当当前时间
	 * @return
	 */
	public static String[] getPvuvDay(String date){
		String[]  strs = null;
		JSONObject siteJson =	getData("12164871","overview/getTimeTrendRpt",DateUtil.lastMonthStart().replace("-", ""),DateUtil.formatMedium(new Date()),"pv_count,visitor_count","day");
		JSONObject data = (JSONObject) siteJson.get("body");
			if(data.containsKey("data")){
			String str = data.get("data").toString();
			JSONArray json = JSONArray.parseArray(str);
			JSONObject job = json.getJSONObject(0); 
			JSONObject result =  (JSONObject) job.get("result");//items
			JSONArray items = JSONArray.parseArray(result.get("items").toString());		
			JSONArray day = JSONArray.parseArray(items.get(0).toString());	
			JSONArray pvuv = JSONArray.parseArray(items.get(1).toString());
			
			for (int i = 0; i < day.size(); i++) {
				String dayt = day.get(i).toString().replace("[", "").replace("]", "").replace("\"", "");
				if(dayt.equals(date.replace("-", "/"))){
					strs =  pvuv.get(i).toString().replace("[", "").replace("]", "").split(",");
				}
			} 			
		}
		return strs;		
	}
	
	
	/**
	 * 根据时间与渠道编码获取UP UV  未查询到时返回NULL
	 * @param date
	 * @param orderchannel
	 * @return
	 */
	public static String[] getPvuvDayIntoST(String date,int orderchannel){
		String[]  strs = null;
		JSONObject siteJson =getData(intoSiteId(orderchannel),"overview/getTimeTrendRpt",DateUtil.lastMonthStart().replace("-", ""),DateUtil.formatMedium(new Date()),"pv_count,visitor_count","day");
		JSONObject data = (JSONObject) siteJson.get("body");
		if(data.containsKey("data")){
			String str = data.get("data").toString();
			JSONArray json = JSONArray.parseArray(str);
			JSONObject job = json.getJSONObject(0); 
			JSONObject result =  (JSONObject) job.get("result");//items
			JSONArray items = JSONArray.parseArray(result.get("items").toString());		
			JSONArray day = JSONArray.parseArray(items.get(0).toString());	
			JSONArray pvuv = JSONArray.parseArray(items.get(1).toString());		
			for (int i = 0; i < day.size(); i++) {
				String dayt = day.get(i).toString().replace("[", "").replace("]", "").replace("\"", "");
				if(dayt.equals(date.replace("-", "/"))){
					strs =  pvuv.get(i).toString().replace("[", "").replace("]", "").split(",");
				}
			} 	
		}
		return strs;
	}
	
	/**
	 * 根据渠道编码获取百度统计中对应的页面SiteId
	 * @param orderchannel  渠道编码 Int
	 * @return
	 */
	public static String intoSiteId(int orderchannel){		
		switch(orderchannel){
		//55 57
		case 70://抖音APP新资费
			return "12411527";
		case 71://火山APP
			return "12411507"; 
		case 73://头条APP
			return "12411490";
		case 75://西瓜APP
			return "12411514";
		default:
			return "";
		}
	}
	public static void main(String[] args) {
		//获取站点 站点中有百度统计页面SiteId数据
		getSite();
		
		//获取数据		 
		//JSONObject siteJson =	HttpSend.getSite();		
//		JSONArray pvuvJson = JSONArray.parseArray(pvuv.toString());	
		//String[] strs = getPvuvDayIntoST("2018-08-22",70);	
		//System.out.println(strs);
		//System.out.println("---"+strs[0]);
		//System.out.println("---"+strs[1]);

	}

}

