// Copyright 2019 The GoKeep Authors. All rights reserved.
// license that can be found in the LICENSE file.

function Log(...any) {
	console.log(...any);
}

function GoURL(url) {
	window.location.href = url;
}

function DirectTo(url) {
	window.location.replace(url);
}

function PageReload(){
	window.location.reload(false); 
}

function TokenName() {
	if (typeof ISGOKEEP != "undefined") {
		return "gokeep_token_x"
	} else {
		return "gokeep_token"
	}
}

// 生成一个随机ID
function guid() {
    function S4() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    }
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

// 设置Cookie
function SetCookie(name,value,hours) {
    var expires = "";
    if (hours) {
        var date = new Date();
        date.setTime(date.getTime() + (hours*60*60*1000));
        expires = "; expires=" + date.toUTCString();
        document.cookie = name + "=" + (value || "")  + expires + "; path=/";
    }
}

// 获取Cookie
function GetCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

// 删除Cookie
function EraseCookie(name) {   
    document.cookie = name + '=;Path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

// 隐藏并销毁modal
function CloseModal(modalID) {
	$("#"+modalID).modal('hide');
	$("#"+modalID).on('hidden.bs.modal', function (e) {
		if ($("#"+modalID).length > 0) {
			$("#"+modalID).remove();
		}
		
	})
}

// 显示对话框，动态创建modal并显示，退出自动销毁窗体
// args是以下结构体
/*
args = {
	footer : "",        // 底部按钮，可以自定义按钮
	noClose : false,    // 是否显示右上角关闭按钮，默认显示
}
*/
// 函数会返回一个modalID，通过这个ID可自已定义一些方法
// 这里用到了一个展开语法
// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Spread_syntax
function ShowMsg(content, ...args) {
	title = "GoKeep";
	if (typeof content == "undefined") content = "";
	modalID = guid();
	var footer = '';
	var noClose = false;
	if (args.length == 0) {
		footer = '<button type="button" class="btn btn-primary" onClick="CloseModal(\'GKModal'+modalID+'\')">Ok</button>';
	}

	if (args.length == 1) {
		// 存在args参数
		if (typeof args[0].footer !== 'undefined' && args[0].footer != "") {
			footer = args[0].footer;
		}
		if (typeof args[0].noClose !== 'undefined' && args[0].noClose == true) {
			noClose = true;
		}
	}

	footer = footer.replace("~modalID~", modalID);
	content = content.replace("~modalID~", modalID);

	var modal = '<div id="GKModal'+modalID+'" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="GKModalLabel'+modalID+'" aria-hidden="true">';
	modal += '<div class="modal-dialog" role="document">';
	modal += '<div class="modal-content">';
	modal += '<div class="modal-header">';
	modal += '<h5 class="modal-title" id="GKModalLabel'+modalID+'">'+title+'</h5>';
	if (!noClose) {
		modal += '<button type="button" class="close" data-dismiss="modal" aria-label="Close">';
		modal += '<span aria-hidden="true">&times;</span>';
		modal += '</button>';
	}
	modal += '</div>';
	modal += '<div class="modal-body">';
	modal += content;
	modal += '</div>';
	modal += '<div class="modal-footer">';
	modal += footer;
	modal += '</div>';
	modal += '</div>';
	modal += '</div>';
	modal += '</div>';
	$("body").append(modal)
	$("#GKModal"+modalID).modal({
		backdrop:'static',
		show:true
	});
	$("#GKModal"+modalID).on('hidden.bs.modal', function (e) {
	  $("#GKModal"+modalID).remove();
	})
	return modalID;
}

// 加载会员信息
function LoadMemberInfo() {
	var gokeep_token = GetCookie(TokenName())
    if (gokeep_token == null) {
      DirectTo("/login");
    }

    $.ajax({
		type: "GET",
		dataType: 'json',
		contentType:"application/json;",
		url: "/api/v1/auth/member/info",
		beforeSend: function(xhr) {
			xhr.setRequestHeader('Authorization', 'Bearer ' + gokeep_token);
		}
    }).done(function(data){
		Log(data);
		if (data.code == 0) {
			$("#_money").html(data.result.money);
			$("#_userid").html(data.result.userid);
		} else {
			ShowMsg("获取用户信息失败");
		}
    }).fail(function() {
      DirectTo("/login");
    });
}

// 退出
function Logout() {
	EraseCookie(TokenName());
	DirectTo('/login');
}

// 当前unix时间
var NowUnix = Math.floor(Date.now() / 1000);

// 用来检查用户是否登录
// 如果登录header部分显示用户中心链接，否则显示登录链接
function CheckLoginState() {
	var gokeep_token = GetCookie(TokenName());
	if (gokeep_token != null) {
		time_login = localStorage.getItem('time_login');

		// 超过半个小时则重新获取下token
		if ((NowUnix-time_login) > 60 * 30) {
			$.ajax({
				type: "GET",
				dataType: 'json',
				contentType:"application/json;",
				url: "/api/v1/auth/refresh_token",
				beforeSend: function(xhr) {
		            xhr.setRequestHeader('Authorization', 'Bearer ' + gokeep_token);
		        }
			}).done(function(data){
		      if (data.code == 200) {
	            SetCookie(TokenName(), data.token, 1);
	            localStorage.setItem('time_login', NowUnix);
		      }
		    })
		}
		// 这里通过缓存状态判断是否登录，每一分钟请求1次
		time_check_me = localStorage.getItem('time_check_me');
		check_me = localStorage.getItem('check_me'); // 为true则为登录状态，否则没有正常登录
		if ((NowUnix-time_check_me) > 60) {
			$.ajax({
				type: "GET",
				dataType: 'json',
				contentType:"application/json;",
				url: "/api/v1/auth/me",
				beforeSend: function(xhr) {
		            xhr.setRequestHeader('Authorization', 'Bearer ' + gokeep_token);
		        }
			}).done(function(data){
		      Log(data);
		      if (data.code == 0) {
		      	localStorage.setItem('time_check_me', NowUnix);
		      	localStorage.setItem('check_me', true);
		      } else {
		      	localStorage.setItem('check_me', false);
		      }
		    }).fail(function() {
		      localStorage.setItem('check_me', false);
		    });
		}
		if (check_me) {
			$("#btnHeader").addClass('btn-danger');
			$("#btnHeader").removeClass('btn-outline-danger')
			if (typeof ISGOKEEP != "undefined") {
				$("#btnHeader").attr({href: '/kas/'});
				$("#btnHeader").html('<i class="fa fa-user-o"></i> 管理中心');
			} else {
				$("#btnHeader").attr({href: '/member/'});
				$("#btnHeader").html('<i class="fa fa-user-o"></i> 会员中心');
			}
			var locPath = location.pathname.match("/view/([0-9a-zA-Z]+)");
			if (locPath != null) {
				// 如果已经登录，查看内容时候对内容进行判断
				// TODO 判断是否已经购买
				Log("check view,unqid=", locPath[1]);
			}
		} else {
			$("#btnHeader").addClass('btn-outline-danger');
			$("#btnHeader").removeClass('btn-danger')
			$("#btnHeader").attr({href: '/login'});
			$("#btnHeader").html('<i class="fa fa-sign-in"></i> 注册登录');
		}

	}
}
var md = new MobileDetect(window.navigator.userAgent);
$(document).ready(function() {
	CheckLoginState();
	if ($(".litvd").length > 0 && typeof DISVDHOVER == "undefined") {
	   $(".litvd").mouseover(function() {
	      if (md.phone() != null || md.tablet() != null) {
	        return
	      }
	      var id = guid();
	      var uuid = $(this).attr("uuid");
	      if (typeof uuid == "undefined") {
	          uuid = id
	          $(this).attr("uuid", uuid);
	      }
	      var video = $(this).attr("video");
	      if ($("video[uuid='"+uuid+"']").length == 0) {
	        $(this).wrap("<div/>")
	          $(this).after('<video preload autoplay loop src="'+video+'" uuid="'+uuid+'" width="100%" style="display:none"></video>');
	          $("video[uuid='"+uuid+"']").mouseout(function(){
	              $(this).hide();
	              $("img[uuid='"+uuid+"']").show();
	              $("video[uuid='"+uuid+"']").get(0).pause();
	              $("video[uuid='"+uuid+"']").parent().parent().parent().find(".icon-play").show();
	          });
	          $("video[uuid='"+uuid+"']").show();
	          $("video[uuid='"+uuid+"']").parent().parent().parent().find(".icon-play").hide();
	      } else {
	          $("video[uuid='"+uuid+"']").show();
	          $("video[uuid='"+uuid+"']").parent().parent().parent().find(".icon-play").hide();
	      }
	      $("video[uuid='"+uuid+"']").get(0).play();
	      $(this).hide();
	   })
	}
});

// 加载栏目选项
function LoadTypeidSelectOptions(selector, sel, tid) {
	if (typeof tid == "undefined") {
		tid = 1;
	}
    $.ajax({
      type: "GET",
      dataType: 'json',
      data: {
        typeid: tid,
        gtype: 'son',
      },
      url: "/api/v1/auth/category/list",
      beforeSend: function (xhr) {
          xhr.setRequestHeader('Authorization', 'Bearer ' + gokeep_token);
      }
    }).done(function (data) {
      Log(data);
      if (data.code == 0) {
        for (var i = 0; i <= data.result.length - 1; i++) {
          type = data.result[i];
          selected = "";
          if (sel == type.ID) {
          	selected = " selected"
          }
          $(selector).append('<option value="' + type.ID + '"'+selected+'>' + type.Typename + '</option>')
        }
      }

    }).fail(function (data) {
      Log("fail:", data);
      ShowMsg("获取栏目失败，可能登录已经超时，请刷新页面重试");
      EraseCookie(TokenName());
    });
}