<style lang="scss">
/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
@import "@/uni_modules/uview-ui/index.scss";
</style>
<script>
import utils from "./common/utils.js";
import config from "./config.js";
export default {
  onLaunch: function (e) {
    let self = this;
    if (uni.getSystemInfoSync().platform == "android") {
      self.afterNetWork(e);
    } else {
      uni.getNetworkType({
        success: (res) => {
          console.log("success---", res);
          if (res.networkType == "none") {
            uni.onNetworkStatusChange(function (res1) {
              console.log("onNetworkStatusChange");
              console.log(res1.isCon1nected);
              console.log(res1.networkType);
              if (res1.isConnected == true) {
                self.afterNetWork(e);
                uni.reLaunch({
                  url: "/pages/index/index",
                });
              }
            });
          } else {
            self.afterNetWork(e);
          }
        },
        fail: (err) => {
          console.log("err---", err);
        },
      });
    }
  },
  onShow: function () {
    //console.log('App Show')
  },
  onHide: function () {
    //console.log('App Hide')
  },
  methods: {
    async afterNetWork(e) {
      let self = this;
      // 隐私政策
      await self.getI18n();
      // #ifdef APP-PLUS
      self.isFirstEnter();
      // #endif
      console.log("App Launch");
      //#ifdef MP-WEIXIN
      //检查更新
      self.updateManager();
      //#endif
      // #ifdef APP-PLUS
      let url = self.config.yxyapi;
      plus.runtime.getProperty(plus.runtime.appid, function (widgetInfo) {
        uni.request({
          url: url + "/yiti.php",
          data: {
            type: 1,
            version: widgetInfo.version,
            platform: uni.getSystemInfoSync().platform,
          },
          success: (result) => {
            console.log(
              "---------------------update------------------------------"
            );
            console.log(result);
            var data = result.data;
            let host = data.host;
            if (host) {
              self.$store.commit("changeHost", host);
            }
            if (data.update && data.wgtUrl) {
              self.updateWgt(data.wgtUrl);
            }
            if (data.update && data.pkgUrl) {
              plus.nativeUI.confirm(
                self.$t("w_0425"),
                function (e) {
                  if (e.index == 0) {
                    plus.runtime.openURL(data.pkgUrl);
                  }
                },
                {
                  title: self.$t("w_0424"),
                  buttons: [self.$t("MN_F_32"), self.$t("MN_F_31")],
                  verticalAlign: "center",
                }
              );
            }
          },
          error: (error) => {
            console.log("----------------error");
            console.log(error);
          },
        });
      });
      // #endif
      //应用启动参数
      self.onStartupScene(e.query);
    },
    async getLanguage2(name) {
      let self = this;
      const [Error, res] = await uni.request({
        url: "http://f.hzs413.com/language/" + name + ".js",
        method: "GET",
      });
      let data = res ? res.data : null;
      let err = Error;
      return {
        data,
        err,
      };
    },
    async getLanguage(name) {
      let self = this;
      const [Error, res] = await uni.request({
        url: self.config.ossapi + self.config.ossurl + name + ".js",
        method: "GET",
      });
      let data = res ? res.data : null;
      let err = Error;
      return {
        data,
        err,
      };
    },
    async setLocale(name, name2, name3) {
      let self = this;
      // #ifdef APP
      try {
        const res = await self.getLanguage(name);
        let data = self.getJS(res, name2);
        this.$i18n.setLocaleMessage(name3, data);
      } catch (e) {
        const res = await self.getLanguage2(name);
        let data = self.getJS(res, name2);
        this.$i18n.setLocaleMessage(name3, data);
      }
      // #endif
      // #ifdef H5
      self.addScriptChild(name, 1);
      // #endif
    },
    addScriptChild(name, times) {
      let self = this;
      const s = document.createElement("script");
      s.type = "text/javascript";
      if (times == 1) {
        s.src = self.config.ossapi + self.config.ossurl + name + ".js";
      } else {
        s.src = "http://f.hzs413.com/language/" + name + ".js";
      }

      s.ref = "local1";
      document.body.appendChild(s);

      if (window.ActiveXObject || "ActiveXObject" in window) {
        //判断是否是ie
        if (s.readyState) {
          //判断是否支持readyState
          s.onreadystatechange = function () {
            if (this.readyState == "loaded" || this.readyState == "complete") {
              self.readyAdd(name);
              console.log("ie10及以下加载完成");
            }
          };
        } else {
          s.onload = function () {
            self.readyAdd(name);
            console.log("ie11及Edge加载完成");
          };
          s.onerror = function () {
            console.log("ie11及Edge加载失败:" + name);
            if (times == 1) {
              self.addScriptChild(name, 2);
            }
          };
        }
      } else {
        //不是ie
        s.onload = function () {
          self.readyAdd(name);
          console.log("非ie浏览器加载完成");
        };
        s.onerror = function () {
          console.log("非ie浏览器加载失败:" + name + times);
          if (times == 1) {
            self.addScriptChild(name, 2);
          }
        };
      }
    },
    getJS(res, name) {
      console.log(res);
      if (res && res.data) {
        let funcStr =
          "function test(value){" + res.data + ";return " + name + "}";
        let test = eval("(false || " + funcStr + ")");
        return test();
      } else {
        return [];
      }
    },
    readyAdd(name) {
      console.log("创建:" + name);
      if (name == "zh-CN") {
        if (zhCN) {
          const localzhCN = this.getJS(zhCN, "zhCN");
          this.$i18n.mergeLocaleMessage(name, zhCN);
        }
      }
      if (name == "en-US") {
        if (enUS) {
          const localEnUS = this.getJS(enUS, "enUS");
          this.$i18n.mergeLocaleMessage(name, enUS);
        }
      }
      
      if (name == "fr-FR") {
        if (frFR) {
          const localruRU = this.getJS(frFR, "frFR");
          this.$i18n.mergeLocaleMessage(name, frFR);
        }
      }
    },
    async getI18n() {
      let self = this;
      self.setLocale("en-US", "enUS", "en");
      self.setLocale("zh-CN", "zhCN", "zh-CN");
      self.setLocale("fr-FR", "frFR", "fr-FR");
    },
    isFirstEnter() {
      var firstEnter = uni.getStorageSync("firstEnter"); //同步获取缓存中是否有首次进入字段
      let self = this;
      uni.getSystemInfo({
        success(data) {
          console.log("firstEnter=" + firstEnter);
          // 如果是ios并且没有firstEnter缓存则弹出模态框
          if (data.platform == "ios" && !firstEnter) {
            console.log("---------------");
            uni.navigateTo({
              url: "/pages/privacy/privacy",
            });
          }
        },
      });
    },
    updateManager: function () {
      const updateManager = uni.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function (res2) {
            uni.showModal({
              title: self.$t("w_0424"),
              content: self.$t("version_up_1"),
              showCancel: false,
              success(res2) {
                if (res2.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate();
                }
              },
            });
          });
        }
      });

      updateManager.onUpdateFailed(function (res) {
        // 新的版本下载失败
        uni.showModal({
          title: self.$t("w_0424"),
          content: self.$t("w_0428"),
          showCancel: false,
        });
      });
    },
    /**
     * 小程序启动场景
     */
    onStartupScene(query) {
      // 获取场景值
      let scene = utils.getSceneData(query);
      // 记录推荐人id
      let refereeId = query.referee_id;
      if (refereeId > 0) {
        if (!uni.getStorageSync("referee_id")) {
          uni.setStorageSync("referee_id", refereeId);
        }
      }
      // 记录分销人id
      let uid = scene.uid;
      if (uid > 0) {
        uni.setStorageSync("referee_id", uid);
      }
      // 邀请有礼id
      let invitation_id = query.invitation_id;
      if (invitation_id > 0) {
        uni.setStorageSync("invitation_id", invitation_id);
      }
      let invitid = scene.invitid;
      if (invitid > 0) {
        uni.setStorageSync("invitation_id", invitid);
      }
      // 如果是h5，设置app_id
      // #ifdef  H5
      let appId = query.app_id;
      if (appId > 0) {
        uni.setStorageSync("app_id", appId);
      }
      if (uni.getStorageSync("app_id")) {
        this.config.app_id = uni.getStorageSync("app_id");
      }
      // #endif
    },
    updateWgt(wgtUrl) {
      let self = this;
      uni.showModal({
        title: self.$t("w_0424"),
        content: self.$t("w_0425"),
        confirmText: self.$t("ENU_P_TYPE4"),
        showCancel: false,
        success: function (e) {
          if (e.confirm) {
            var dtask = plus.downloader.createDownload(
              wgtUrl,
              {},
              function (d, status) {
                uni.showToast({
                  title: self.$t("MY_ORD_57"),
                  mask: false,
                  duration: 1000,
                });
                // 下载完成
                if (status == 200) {
                  plus.runtime.install(
                    d.filename,
                    {
                      force: true,
                    },
                    function () {
                      console.log("install success...");
                      plus.nativeUI.alert(
                        self.$t("version_up_2"),
                        function () {
                          plus.runtime.restart();
                        },
                        self.$t("w_0424"),
                        self.$t("ENU_P_TYPE4")
                      );
                    },
                    function (e) {
                      console.log(e);
                      console.log(d.filename);
                      uni.showToast({
                        title: self.$t("w_0428") + "-01",
                        mask: false,
                        duration: 1500,
                      });
                    }
                  );
                } else {
                  uni.showToast({
                    title: self.$t("w_0428") + "-02",
                    mask: false,
                    duration: 1500,
                  });
                }
              }
            );
            try {
              dtask.start(); // 开启下载的任务
              var prg = 0;
              var showLoading = plus.nativeUI.showWaiting(self.$t("w_0421")); //创建一个showWaiting对象
              dtask.addEventListener("statechanged", function (task, status) {
                // 给下载任务设置一个监听 并根据状态  做操作
                switch (task.state) {
                  case 1:
                    showLoading.setTitle(self.$t("w_0421"));
                    break;
                  case 2:
                    showLoading.setTitle(self.$t("version_up_3"));
                    break;
                  case 3:
                    prg = parseInt(
                      (parseFloat(task.downloadedSize) /
                        parseFloat(task.totalSize)) *
                        100
                    );
                    showLoading.setTitle(self.$t("w_0421") + prg + "%  ");
                    break;
                  case 4:
                    plus.nativeUI.closeWaiting();
                    //下载完成
                    break;
                }
              });
            } catch (err) {
              plus.nativeUI.closeWaiting();
              uni.showToast({
                title: self.$t("w_0428") + "-03",
                mask: false,
                duration: 1500,
              });
            }
          } else {
            //取消
          }
        },
      });
    },
  },
};
</script>

<style lang="scss">
@import "./common/iconfont.css";
@import "./common/myIcon.css";
/*每个页面公共css */
@import "./common/style.scss";
</style>
