/**
 * HCP 整合js
 */
//'use strict';

import $ from 'jquery';
import {Base64} from 'js-base64';
var localStorage_name = "watchlive_current_user"
localStorage.setItem("watch_live_localStorage_name",localStorage_name);
window.finsihed=null;
var current_user = {
	id:"",
	name:'',
	avatar:''
};
function getUrlParam(url, paramName) {
	const reg = new RegExp('(^|&)' + paramName + '=([^&]*)(&|$)', 'i');
	const result = url.slice(url.indexOf('?') + 1).match(reg);
	if (result !== null) {
	  return decodeURIComponent(result[2]);
	}
	return null;
  }
function init_current_user(){
	console.log("init_current_user")
	current_user = JSON.parse(localStorage.getItem(localStorage_name));
	if(current_user == undefined || current_user == null){
		current_user = 
			{
				id: timestamp(),
				name: Base64.encode("游客"+timestamp()),
				avatar: "https://doc.igandan.com/app/html/img/2016/20160714132557.png"
			}
 	}
	return current_user;
}
var timestamp = function(){
	return new Date().getTime();
}
const HCP = {
	options: {
        privilege_async: false, //获取权限时ajax同步异步 （ajax 默认是true：异步，false：同步。)
        user_info_async: false, //获取用户信息时ajax同步异步 （ajax 默认是true：异步，false：同步。)
        add_sources_async: true, //获取权限时ajax同步异步 （ajax 默认是true：异步，false：同步。)
    },
    current_user: init_current_user(),//当前用户信息
    privilege: {},//权限信息
    //获取属性值
    getOption: function (name){
    	return HCP.options[name]
    },
    //设置属性值
    setOption: function(name,value){
    	return HCP.options[name] = value
    },
   
    //检查HCP权限
    getHCPPrivilege: async function(gdxz_unionid,from,project_id){
		let baseUrl = '';
		var path=location.href;
		if (path.indexOf("//wx.igandan.com") > 1 || path.indexOf("oss")>1) {
			baseUrl='https://wx.igandan.com'
			
		} else {
			baseUrl='https://dev-wx.igandan.com'
		}
		await $.ajax({
			url: baseUrl+"/hcp/getHCPPrivilege",
			//url:'https://www.fastmock.site/mock/ebb1956b65d6078940cacb295a06be27/mock/mock',
			async: HCP.options.privilege_async, 
			data: {"unionid":gdxz_unionid, "from": from, "project_id":project_id},
			success:function(res){// 获取用户信息,后端可首先通过cookie,session等判断,没有信息则通过code获取
				//alert(JSON.stringify(res))
				 console.log(res);
				if (res.code == 60001) {
					window.finsihed=true;
					//alert("getHCPPrivilege");
					console.log("授权成功")
					//console.log(HCP.privilege.HCP_INFO);
					localStorage.setItem("userName", Base64.decode(res.HCP_INFO.nickname));
					localStorage.setItem("uuid", res.HCP_INFO.user_uuid);
					localStorage.setItem("avatar", res.HCP_INFO.avatar);
				} else if (res.code == 60002) {
							Dialog.alert({
							  title: '提示信息',
							  message: '您暂时没有权限，无法浏览，请关闭页面',
							}).then(() => {
							  // on close
							});
				} else {
					//alert("222");
					//直接走登录页面
					HCP.gologin();
				}
			}
		})
	},
	//添加HCP 访问记录
	addSources: function(openid,sourcesId,sourcesTitle, sourcesType,userid,userType){
		$.ajax({
			url: "/hcp/addSources",
			async: HCP.options.add_sources_async, 
			data: {
					openid:openid,
					sourcesId:sourcesId,
					sourcesTitle:sourcesTitle, 
					sourcesType:sourcesType,
					userid:userid,
					userType:userType
				}, 
			success:function(res){
				//...
			}
		})
	},
    //转到login页面
	gologin: function (){
		let baseUrl = '';
		var path=location.href;
		if (path.indexOf("//wx.igandan.com") > 1 || path.indexOf("oss")>1) {
			baseUrl='https://wx.igandan.com'
		} else {
			baseUrl='https://dev-wx.igandan.com'
		}
		var path=location.href.split('#')[0];
		window.location.href =baseUrl+"/hcp/Signup2020online_tologin?back_url="+HCP.htmlDecodeByRegExp(path);
	},
	//反转义
	htmlDecodeByRegExp: function (str){ 
		 var s = "";
		 if(str.length == 0) return "";
		 s = str.replace(/&amp;/g,"&");
		 s = s.replace(/&lt;/g,"<");
		 s = s.replace(/&gt;/g,">");
		 s = s.replace(/&nbsp;/g," ");
		 s = s.replace(/'/g,"\'");
		 s = s.replace(/"/g,"\"");
		 return s; 
	} ,
	//判断字符串是否为空
    isNull: function (str) {
   	    if (typeof (str) == "undefined" || str == "undefined" || str == null || str.replace(" ") === "")
   	        return true;
   	    else
   	        return false;
   	},
   	//获取cookie
   	getCookie: function (name){
		var arr;
		var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
		if (arr = document.cookie.match(reg))
		  return unescape(arr[2]);
		else
		  return null;
		// var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
		// if(arr=document.cookie.match(reg))
		// return unescape(arr[2]);
		// else
		// return null;
	},
	//设置cookie
	setCookie: function (cname, cvalue, exdays) {
	    var d = new Date();
	    d.setTime(d.getTime() + (exdays*24*60*60*1000));
	    var expires = "expires="+ d.toUTCString();
	    document.cookie = cname + "=" + cvalue + ";" + expires;
		
	},
	//是否为微信
	is_weixin: function (){
		var ua = navigator.userAgent.toLowerCase();
		if(ua.match(/MicroMessenger/i)=="micromessenger") {
			return true;
	 	} else {
			return false;
		}
	},
	//获得时间戳
	timestamp: function(){
		return new Date().getTime();
	},
	//获取微信用户信息
	getUserInfo: function (){
		let code =getUrlParam("code") ;// 截取url上的code ,可能没有,则返回''空字符串!HCP.getCookie("gdxz_unionid")?'':
		var path=location.href;   //.split('#')[0];
		var url="";
		var appid="";
		if (path.indexOf("//wx.igandan.com") > 1) {
			url="https://wx.igandan.com/";
		   appid="wxa4132ef4701ac5e4";
			
		} else {
			url="https://dev-wx.igandan.com/";
		    appid="wx68affaa9d23528f8";
		}
		// if(path.indexOf(".igandan.org")>1){
		//   url="https://twx.igandan.org/";
		//   appid="wx68affaa9d23528f8";
		// }else{
		//   url="https://wx.igandan.com/";
		//   appid="wxa4132ef4701ac5e4";
		// }
		const ishttps = 'https:' == document.location.protocol ? true : false;
		if(!ishttps){
			url = url.toString().replace("https","http")
		};
			$.ajax({
				url: url+"AuthorizeURL/getUserInfo",
				data: {appid:appid, code: code, scope: "snsapi_userinfo"}, 
				async: HCP.options.user_info_async, 
				success:function(res){// 获取用户信息,后端可首先通过cookie,session等判断,没有信息则通过code获取
					if(res.code == 200 ){
						var user_info = JSON.parse(res.user_info.json)
						current_user = {
							id: user_info.openid,
							name: Base64.encode(user_info.nickname),
							avatar: user_info.headimgurl,
							unionid: user_info.unionid,
						};
						HCP.current_user = current_user;
						HCP.setCookie("gdxz_unionid", user_info.unionid, 1);
						localStorage.setItem(localStorage_name,JSON.stringify(current_user));
						//alert("即将重新加载")
						window.location.reload();
						//HCP.getHCPPrivilege(user_info.unionid, "wechat", "")
						// var currentHref=sessionStorage.getItem("currentHref");
						// if(currentHref){
						// 	window.location.href=currentHref;
						// }
					}else if(res.code == 202){
						// 这个redirectUrl用 当前页路径或者tof.fullPath(将要进入的路径)
						//var myurl="https://" + window.location.host +"/excellencourse/index.htm?"+window.location.href.split("?")[1];
						var redirectUrl =window.location.href;
						//sessionStorage.setItem("currentHref",redirectUrl)
						 redirectUrl = encodeURIComponent(redirectUrl);
						var oauth2_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
						var appid = res.appid;
						window.location.href = oauth2_url.replace("APPID",appid).replace("REDIRECT_URI",redirectUrl);
						//window.location.reload();
					}
				}
			})
	
		
	}
}

export default HCP

