/*
 * Description  :
 * Date         :2025-03-14 10:41:16
 * LastEditors  :Xuwei
 * LastEditTime :2025-03-14 16:28:36
 * FilePath     :\upgrade-now\scripts\renew.js
 */
var buyLink = {
  preJp: "https://partition.aomei.jp",
  pre: "https://www.diskpart.com", // 中转平台地址
  current: "upgrade-now.html", // 当前弹窗地址，用以前得购买地址
  current2: "upgrade-advanced-features.html",
  ruCurrent: "https://www.aomeitech.com/ru/partners/pa-upgrade-for-syssoft.html"
};

var fn = {
  fnIsOurCustomBrowser: function() {
    if (window.external.CB_IsOurCustomBrowser != null) {
      return true;
    } else {
      return false;
    }
  },

  //
  theParam: function(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
  },

  // 获取点击标签中传递过来的参数
  getTag: function() {
    var _this = this;
    return _this.theParam("source") || "toolbar";
  },

  // 获取语言参数
  getLang: function() {
    var langArry = ["en", "de", "fr", "it", "es", "tw", "jp", "ja", "ru"];

    var lang = this.theParam("lang");
    var found = false;

    for (var i = 0; i < langArry.length; i++) {
      if (langArry[i] === lang) {
        found = true;
        break;
      }
    }

    if (found) {
      lang === "ja" && (lang = "jp");
    } else {
      lang = "en";
    }

    return lang;
  },

  // 转化语言键值
  getKey: function(o, lang) {
    return o.hasOwnProperty(lang) ? lang : "en";
  },

  // 获取文件名字
  getFilename: function() {
    var pathname = window.location.pathname;
    var filename = pathname.substring(pathname.lastIndexOf("/") + 1, pathname.lastIndexOf(".html"));
    return filename;
  },
  getEdition: function() {
    var allProductName = ["std"];
    var originalCurrent = this.theParam("edition") ? this.theParam("edition").split("_")[1] : "";
    var currentProductName = ""; // 默认值
    for (var i = 0; i < allProductName.length; i++) {
      if (allProductName[i] === originalCurrent) {
        currentProductName = originalCurrent;
        break;
      }
    }
    return currentProductName;
  },
  setPopurl: function() {
    var popurlLang = fn.getLang().match(/jp|en/) ? "/" : "/" + fn.getLang() + "/";
    var trackPage =
      this.getTag() === "create-portable-version" ? buyLink.current2 : buyLink.current;
    var pre = fn.getLang() === "jp" ? buyLink.preJp : buyLink.pre;
    var popurl = pre + popurlLang + trackPage + window.location.search;
    if (fn.getLang() === "ru") {
      popurl = buyLink.ruCurrent + window.location.search;
    }
    return "&popurl=" + encodeURIComponent(popurl);
  },
  // 给main-wrap添加类名
  dealClassName: function() {
    var status = this.theParam("LoginStatus") || "uloged"; // 登录状态
    var hasCloud = this.theParam("cloudSt") || "0"; // 是否已经是傲梅云用户
    status === "loging" || hasCloud === "1" ?
      $(".main-wrap").addClass("logging") :
      $(".main-wrap").removeClass("logging");
  },
  // 构造购买链接
  buildupBuyLink: function(original) {
    var searchPopurl = fn.setPopurl();
    var pre = this.getLang() === "jp" ? buyLink.preJp : buyLink.pre;
    var link = this.getLang() === "ru" ? buyLink.ruCurrent + '?' + searchPopurl.slice(1) : pre + "/cart?" + original + searchPopurl;
    return link;
  },
  // 渲染模版
  renderHtml: function() {
    var theTag = this.getTag();
    var theLang = this.getLang();
    if (theLang === "ja") {
      theLang = "jp";
    }

    // 根据source参数修改pro edition上方文案
    // var theKey = this.getKey(obj, theLang);
    var renderData = this.deepClone(this.proYearIncrease(obj));
    // 'Your subscription will expire in<p><i>20</i><i> days</i><i> day</i></p>'
    var htmlString = renderData.title
    // 找到第一个 <i> 元素的起始位置
    var startIndex = htmlString.indexOf('<i>') + '<i>'.length;
    // 找到第一个 <i> 元素的结束位置
    var endIndex = htmlString.indexOf('</i>', startIndex);
    // 新的文本内容
    var expdays = this.theParam("expdays") || 0;
    // 替换第一个 <i> 元素的文本内容
    var newHtmlString = htmlString.substring(0, startIndex) + expdays + htmlString.substring(endIndex);
    renderData.title = newHtmlString;
    renderData.lang = theLang;
    renderData.show = this.theParam("show");
    $("body").addClass(theLang);
    $("body").addClass(theTag);
    if (expdays < 2) {
      $("body").addClass('oneday');
    }
    renderData.buyLinkPre =
      fn.getLang() === "jp" ? buyLink.preJp + "/cart?" : buyLink.pre + "/cart?";
    renderData.popurl = fn.setPopurl();
    // source=install-complete:首次弹出
    // this.theParam("source") === "install-complete";
    if (/toolbar|register|1st-run|install-complete/.test(this.theParam("source"))) {

    }
    $("#myTmpl").tmpl(renderData).appendTo(".main-wrap");

  },


  goLicenceCode: function() {
    $('[data-go="licenceCode"]').click(function() {
      if (fn.fnIsOurCustomBrowser()) {
        window.external.CB_OpenURL("enter licence code");
      } else {
        chrome.webview.postMessage("enter licence code");
      }
    });
  },
  toTaxPrice: function(price) {
    function formatNumberWithCommas(number) {
      return parseInt(number)
        .toString()
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    // 先去除字符串中的逗号，并替换小数点为点号
    var cleanedPrice = price.replace(/,/g, "").replace("円", "").replace("．", ".").match(/\d+/)[0];
    // 将字符串转换为数字
    var formattedPrice = parseFloat(cleanedPrice) * 1.1;

    formattedPrice = "（税込" + formatNumberWithCommas(formattedPrice) + "円）";

    return formattedPrice;
  },
  // 获取链接里的产品参数
  extractPkNumbers: function(url) {
    var pkNumbers = "";
    var queryString = url.split("?")[1]; // 获取查询字符串部分

    if (queryString) {
      var params = queryString.split("&"); // 分割查询字符串成键值对数组

      for (var i = 0; i < params.length; i++) {
        var param = params[i].split("="); // 分割每个键值对
        var key = param[0];
        var match = key.match(/pk\[(\d+)\]/);

        if (match) {
          pkNumbers = match[1];
        }
      }
    }

    return pkNumbers;
  },
  // 是否参加更换购买平台测试
  isReplacePlatform: function(url) {
    var productId = this.extractPkNumbers(url);
    var isProductId = /230|397|398|232|233/.test(productId);
    var isLang = fn.getLang() === "de"
    // var isSource = /register|install-complete|install/.test(this.theParam("source")); // install这个参数不知道有没有，需求给的就添加上了
    if (isProductId || isLang) { // 不参加更换购买平台因素
      return false
    } else {
      return true
    }
  },
  // 更换购买平台
  replaceBuyPlatform: function(url) {
    if (this.isReplacePlatform(url)) {
      url = url.replace("ep=cb", "ep=vf").replace("ep=si&an=1", "ep=vf");
    }
    return url;
  },
  proYearIncrease: function(data) {
    // object.assign兼容低版本浏览器
    if (typeof Object.assign !== 'function') {
      Object.assign = function(target) {
        if (target == null) {
          throw new TypeError('Cannot convert undefined or null to object');
        }

        target = Object(target);
        for (var i = 1; i < arguments.length; i++) {
          var source = arguments[i];
          if (source != null) {
            for (var key in source) {
              if (Object.prototype.hasOwnProperty.call(source, key)) {
                target[key] = source[key];
              }
            }
          }
        }
        return target;
      };
    }
    // object.assign兼容低版本浏览器
    var xid = fn.theParam("xid");
    // var qid = xid ? xid.split("!")[1] : "";
    return data
  },
  // 深拷贝
  deepClone: function(obj) {
    // 如果是 null 或非对象类型，直接返回
    if (obj === null || typeof obj !== "object") {
      return obj;
    }

    var clone;

    // 检查对象的类型
    if (obj instanceof Array) {
      // 如果是数组，初始化一个新数组
      clone = [];
      for (var i = 0; i < obj.length; i++) {
        clone[i] = this.deepClone(obj[i]); // 递归深拷贝每个元素
      }
    } else {
      // 如果是对象，初始化一个新对象
      clone = {};
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          clone[key] = this.deepClone(obj[key]); // 递归深拷贝每个属性
        }
      }
    }

    return clone;

  }
};
$(function() {
  // 引入对应js
  var scriptElement = document.createElement("script");
  scriptElement.type = "text/javascript";
  scriptElement.src = "scripts/renew" + "/" + fn.getLang() + ".js";

  function init() {
    fn.dealClassName();
    fn.renderHtml();
    fn.goLicenceCode();
    $(".btn-org").click(function() {
      var btnLink = fn.replaceBuyPlatform($(this).attr("data-href"));
      var hash = "#" + $(this).attr("data-num");
      if (fn.fnIsOurCustomBrowser()) {
        window.external.CB_OpenURL(btnLink + hash);
      } else {
        chrome.webview.postMessage("openurl:" + btnLink + hash);
      }
    });
    $(".close").click(function() {
      if (fn.fnIsOurCustomBrowser()) {
        window.external.CB_OpenURL("close");
      } else {
        chrome.webview.postMessage("close");
      }
    });
    $('#dont').click(function() {
      $(this).toggleClass('checked');
      if (fn.fnIsOurCustomBrowser()) {
        window.external.CB_OpenURL("OnClickedCheck1");
      } else {
        chrome.webview.postMessage("OnClickedCheck1");
      }
    });
  }
  // 兼容低版本浏览器
  if (scriptElement.readyState) { // 仅适用于IE
    scriptElement.onreadystatechange = function() {
      if (scriptElement.readyState === "loaded" || scriptElement.readyState === "complete") {
        scriptElement.onreadystatechange = null;
        // 脚本加载完成后的操作
        init();
      }
    };
  } else { // 其他浏览器
    scriptElement.onload = function() {
      // 脚本加载完成后的操作
      init();
    };
  }
  // window.localStorage.clear();
  document.getElementsByTagName("head")[0].appendChild(scriptElement);


});