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

const REPHONE = /^(?:\+?86)?1(?:3\d{3}|5[^4\D]\d{2}|8\d{3}|7(?:[0-35-9]\d{2}|4(?:0\d|1[0-2]|9\d))|9[0-35-9]\d{2}|6[2567]\d{2}|4(?:[14]0\d{3}|[68]\d{4}|[579]\d{2}))\d{6}$/;

// -----url-------------------------------------

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

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

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

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

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

    if (args.length == 1) {
        // 存在args参数
        if (typeof args[0].title !== 'undefined' && args[0].title != "") {
            title = args[0].title;
        }
        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;
        }
        if (typeof args[0].size !== 'undefined' && args[0].size != "") {
            size = args[0].size;
        }
        if (typeof args[0].onShow !== 'undefined' && typeof args[0].onShow === "function") {
            onShow = args[0].onShow;
        }
    }

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

    mSize = "";
    if (size == "lg") {
        mSize = " modal-lg"
    }

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

// 在某个元素内显示alert信息
function ShowAlert(ele, content, type, showtime = 3000) {
    let msg = `<div class="alert alert-${type}" role="alert">
        ${content}
    </div>`;
    $(ele).html(msg);
    $(ele).show();
    if (showtime > 0) {
        setTimeout(() => {
            $(ele).html("");
        }, showtime);
    }
}

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

// -----cookie-------------------------------------

// 设置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;';
}

// -----base64-------------------------------------
function base64_decode (encodedData) { // eslint-disable-line camelcase
  //  discuss at: https://locutus.io/php/base64_decode/
  // original by: Tyler Akins (https://rumkin.com)
  // improved by: Thunder.m
  // improved by: Kevin van Zonneveld (https://kvz.io)
  // improved by: Kevin van Zonneveld (https://kvz.io)
  //    input by: Aman Gupta
  //    input by: Brett Zamir (https://brett-zamir.me)
  // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
  // bugfixed by: Pellentesque Malesuada
  // bugfixed by: Kevin van Zonneveld (https://kvz.io)
  // improved by: Indigo744
  //   example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==')
  //   returns 1: 'Kevin van Zonneveld'
  //   example 2: base64_decode('YQ==')
  //   returns 2: 'a'
  //   example 3: base64_decode('4pyTIMOgIGxhIG1vZGU=')
  //   returns 3: '✓ à la mode'

  // decodeUTF8string()
  // Internal function to decode properly UTF8 string
  // Adapted from Solution #1 at https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
  var decodeUTF8string = function (str) {
    // Going backwards: from bytestream, to percent-encoding, to original string.
    return decodeURIComponent(str.split('').map(function (c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
    }).join(''))
  }

  if (typeof window !== 'undefined') {
    if (typeof window.atob !== 'undefined') {
      return decodeUTF8string(window.atob(encodedData))
    }
  } else {
    return new Buffer(encodedData, 'base64').toString('utf-8')
  }

  var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  var o1
  var o2
  var o3
  var h1
  var h2
  var h3
  var h4
  var bits
  var i = 0
  var ac = 0
  var dec = ''
  var tmpArr = []

  if (!encodedData) {
    return encodedData
  }

  encodedData += ''

  do {
    // unpack four hexets into three octets using index points in b64
    h1 = b64.indexOf(encodedData.charAt(i++))
    h2 = b64.indexOf(encodedData.charAt(i++))
    h3 = b64.indexOf(encodedData.charAt(i++))
    h4 = b64.indexOf(encodedData.charAt(i++))

    bits = h1 << 18 | h2 << 12 | h3 << 6 | h4

    o1 = bits >> 16 & 0xff
    o2 = bits >> 8 & 0xff
    o3 = bits & 0xff

    if (h3 === 64) {
      tmpArr[ac++] = String.fromCharCode(o1)
    } else if (h4 === 64) {
      tmpArr[ac++] = String.fromCharCode(o1, o2)
    } else {
      tmpArr[ac++] = String.fromCharCode(o1, o2, o3)
    }
  } while (i < encodedData.length)

  dec = tmpArr.join('')

  return decodeUTF8string(dec.replace(/\0+$/, ''))
}

async function getCaptcha() {
    var num = new Date().getTime();
    var rand = Math.round(Math.random() * 10000);
    num = num + rand;

    let resp = await fetch(`/captcha/generate?${num}`, {
        headers: {
            'content-type': 'application/json'
        },
        method: 'GET',
    });
    let rs = await resp.json();
    if (rs.code !== 0) {
        ShowMsg("获取验证码失败：" + rs.msg);
        return;
    } else {
        $('#imgCaptcha').attr({
            src: rs.result.data,
        });
        $("#iptCaptchaid").val(rs.result.captchaId)
    }
}

Date.prototype.format = function (format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
                date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}

// 页面加载触发
$(document).ready(function () {

    window.onscroll = function () { scrollFunction() };

    function scrollFunction() {
        if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
            $("#btnScrollTop").show();
        } else {
            $("#btnScrollTop").hide();
        }
    }

});

// 滚动到页面顶部
function gotop() {
    $('html, body').animate({ scrollTop: 0 }, 'slow'); 
}