package com.trs.web2frame.myutils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.trs.infra.util.CMy3WLib;
import com.trs.infra.util.CMyFile;
import com.trs.web2frame.WCMServiceCaller;
import com.trs.web2frame.dispatch.Dispatch;
import com.trs.web2frame.tool.tyjyh.ConnectionUtil;
import com.trs.web2frame.tool.tyjyh.ConnectionUtil2;
import com.trs.web2frame.tool.tyjyh.Log_Exception;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class MasVideoTest {

	public static void main(String[] args) throws Exception {
//		Map appKey = new HashMap();
//		appKey.put("16", "WCM");// 林草
//		appKey.put("41", "sxgovmas");// 41市政府、32教委、29广电、73审计局、31司法
//		appKey.put("36", "wcmmas");// 发改委
//		appKey.put("38", "mas");// 农业厅
//		appKey.put("70", "mas35");// 水利厅
//
//		appKey.put("68", "");// 粮食厅 无
//		appKey.put("24", "");// 医保局 无
//
//		appKey.put("25", "mas35");// 人社厅xxx
//		appKey.put("66", "mas35");// 统计局xxx
		// 目前人社厅、统计局需要代理mas接口。
		// 林草局、水利厅、人社厅、统计局需要将public目录打包下载

		// http://www.sxwater.gov.cn/mas/openapi/pages.do?method=exQuery&appKey=mas35&id=4459
		// TODO Auto-generated method stub
		// StringBuilder sb = new StringBuilder("select docid,docchannel,dochtmlcon from
		// wcmdocument where siteid IN (41,70,68,66,65,73,32,38,36,31,29,25,24,16,51)
		// and docstatus>=0");
		// StringBuilder sb = new StringBuilder("select docid,docchannel,dochtmlcon from
		// wcmdocument where siteid in(29,31,73,32) and docstatus>=0");
		StringBuilder sb = new StringBuilder(
				"select docid,docchannel,dochtmlcon from wcmdocument where docchannel in(2375) and docstatus>=0 ");//and crtime>'2021-12-09 00:00:00'
		Connection connection = ConnectionUtil2.getConnection();
		Statement st = connection.createStatement();
		ResultSet rs = st.executeQuery(sb.toString());
		// http://lcj.shanxi.gov.cn/mas/openapi/pages.do?method=exQuery&id=322&appKey=WCM
		int index = 0;
		while (rs.next()) {
			index++;
			if (index % 1000 == 0) {
				System.out.println("已完成:" + index);
			}
			String sContent = rs.getString("dochtmlcon");
			// System.out.println(sContent);
			Document doc = Jsoup.parse(sContent);
			Elements eles = doc.getElementsByAttribute("__fckvideo");
			for (int i = 0; i < eles.size(); i++) {
				try {
					Element iframe = eles.get(i).child(0);
					String src = iframe.attr("src");
					String url = src.substring(0, src.indexOf("/mas/"));
					if (url.equals("http://www.sxwater.gov.cn"))
						url = "http://slt.shanxi.gov.cn";
					if (url.equals("http://video.stats-sx.gov.cn"))
						url = "http://tjj.shanxi.gov.cn";
					if (url.equals("http://tjj.shanxi.gov.cn:1934"))
						url = "http://tjj.shanxi.gov.cn";
					if (url.equals("http://video.stats-sx.gov.cn:8010"))
						url = "http://tjj.shanxi.gov.cn";
//					if (url.equals("http://mas.zwy.sxctc.net:9999"))
//						url = "http://tjj.shanxi.gov.cn";

					String videoid = src.substring(src.indexOf("&id=") + 4, src.indexOf("&autoPlay"));
					String api = url + "/mas/openapi/pages.do?method=exQuery&appKey=mas35&id=" + videoid;
					System.out.println(api);
					JSONArray array = JSONArray.fromObject(CMy3WLib.getURLContent(api));
					if (array.size() > 0) {
						String videourl = array.getJSONObject(0).getString("dURL");
						String picurl = array.getJSONObject(0).getString("pic");
						// System.out.println("开始下载：" + videourl);
						// String fileName = CMyFile.extractFileName(videourl);
						String fileUrl = videourl.substring(videourl.indexOf("/masvod/"), videourl.length());
						String picUrl = picurl.substring(picurl.indexOf("/masvod/"), picurl.length());
						String sWidth = iframe.attr("width");
						String sHeight = iframe.attr("height");
						System.out.println(picUrl);
						InsertResult(rs.getString("docchannel"), rs.getString("docid"), fileUrl, picUrl, sWidth,
								sHeight);
						// Common.downLoadFile(videourl, "/Users/zhangyanan/Downloads/video/lcj/" +
						// fileName);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				// System.out.println(array);
			}
			// System.out.println(eles.html());

			// System.out.println(sContent);
		}

		ConnectionUtil2.closeConnection(rs, st, connection);
//		step3();
	}

	public static void InsertResult(String docchannel, String docid, String videourl, String videoimg, String sWidth,
			String sHeight) throws SQLException {
		try {
			StringBuilder sb = new StringBuilder(
					"INSERT INTO VIDEO_RESULT4 (docchannel,docid,VIDEOURL,IMGURL,Width,Height) VALUES(" + docchannel
							+ "," + docid + ",'" + videourl + "','" + videoimg + "','" + sWidth + "','" + sHeight
							+ "')");
			Log_Exception.Logger_txt(sb.toString() + ";");

		} catch (Exception e) {
			// TODO: handle exception
			Log_Exception.Error_txt("InsertResult 方法异常！" + e.getMessage());
		}
	}

	// 第三步，调用海云接口更新文档
	// 需能连接海云接口和海云数据库
	public static void step3() {
		Connection hy_conn = null;
		PreparedStatement query_pstmt = null;
		ResultSet rs = null;

		try {
			hy_conn = ConnectionUtil2.getConnection();
			String query_sql = "select * from VIDEO_RESULT4 order by docid";
			query_pstmt = hy_conn.prepareStatement(query_sql);
			rs = query_pstmt.executeQuery();

			int index = 0;
			while (rs.next()) {
				index++;

				String docid = rs.getString("docid");
				String channelid = rs.getString("docchannel");
				String picUrl = rs.getString("imgurl");
				String fileUrl = rs.getString("videourl");
				int width = rs.getInt("width");
				if (width == 0)
					width = 960;
				int height = rs.getInt("height");
				if (height == 0)
					height = 544;
				JSONObject obj = getNewHtmlCon(hy_conn, docid, picUrl, fileUrl, width, height);
				if (obj.isNullObject())
					continue;
				String htmlcon = obj.getString("dochtmlcon");
				String docTitle = obj.getString("doctitle");
				String docreltime = obj.getString("docreltime");

				Map<String, Object> oPostData = new HashMap<>();
				oPostData.put("ObjectId", docid);
				oPostData.put("ChannelId", channelid);
				oPostData.put("CurrUserName", "dev");
				oPostData.put("DocType", "20");
				oPostData.put("docHtmlCon", htmlcon);
				oPostData.put("docTitle", docTitle);
				oPostData.put("docreltime", docreltime);

				String sServiceId = "gov_webdocument";
				String sMethodName = "saveDocumentInWeb";
				try {
					Dispatch result = WCMServiceCaller.Call(sServiceId, sMethodName, oPostData, true);
					JSONObject rObject = JSONObject.fromObject(result.getResponseText().toString());
					if (rObject.get("ISSUCCESS").toString().equals("true")) {
						System.out.println("更新第" + index + "条，成功！docid:" + docid);
					} else {
						String messageInfo = rObject.getString("MSG");
						System.err.println("更新第" + index + "条，失败！docid:" + docid + " error:" + messageInfo);
					}
				} catch (Exception e) {
					System.err.println("更新第" + index + "条失败！DOCID：" + docid + "，可能网络错误，未成功提交");
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ConnectionUtil.closeConnection(rs, query_pstmt, hy_conn);
		}
	}
	
	private static JSONObject getNewHtmlCon(Connection conn, String docid, String picUrl, String fileUrl, int width, int height) {
		String sql = "select doctitle,dochtmlcon,docreltime from wcmdocument where docid=" + docid;
		PreparedStatement statement = null;
		ResultSet rs = null;
		try {
			statement = conn.prepareStatement(sql);
			rs = statement.executeQuery();
			if (rs.next()) {
				String sContent = rs.getString("dochtmlcon");
				Document doc = Jsoup.parse(sContent);
				Elements eles = doc.getElementsByAttribute("__fckvideo");
				for (int i=0; i<eles.size(); i++) {
					String newiframe = "<p style=\"text-align:center\"><iframe class=\"video_iframe\" allowfullscreen=\"\" frameborder=\"0\" src=\"/masvod/player/index.html?data-cover="+picUrl+"&data-src="+fileUrl+"\" width=\""+width+"\" height=\""+height+"\"></iframe></p>";
					eles.get(i).parent().html(newiframe);
				}
				JSONObject obj = new JSONObject();
				obj.put("doctitle", rs.getString("docTitle"));
				obj.put("docreltime", rs.getString("docreltime"));
				obj.put("dochtmlcon", doc.body().html());
				return obj;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (statement != null) {
					statement.close();
					statement = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
