/* jshint esversion: 6 */
//兼容部分安卓机型globalthis报错
!(function(t){
	function e(){
		var e = this || self;
		(e.globalThis = e), delete t.prototype._T_;
	}
	"object" != typeof globalThis && (this ? e() : (t.defineProperty(t.prototype, "_T_", {
		configurable: !0,
		get: e,
	}), _T_))
})(Object);
//end
var app = new Vue({
  el: '#app',
  data: {
    originData: [],  // 所有权限项  需要拿到所有权限项 然后根据 localstorage 中的常用 number 数组 初始化 shrCommonlyUsed
    value: "",
    shrCommonlyUsed: [],  // 常用 的所有数据
    originCategoricalDate:[],  // 源数据 从服务器请求来的数据
    categoricalDate: [],  // 搜索过滤后的数据
    title:"简体中文",
    bannerUrl:"/mbos/store/4000148/shrnewlightapp/banner.png",
    showChangeLan: true,
    search:"",
    versionError: false,
    signAgreement: false, //展示声明协议内容
    agreements: [], //声明协议
    showText: false,
    agreementText: '',
    isAllowVersion: false //8.8.0.0以上版本出现是否同意隐私声明弹窗
  },
  mounted: function () {
    const _this = this
    const usedStorage = JSON.parse(window.localStorage.getItem("shrCommonlyUsed")) || []
    var isYunZhiJia = window.navigator.userAgent.match(/Qing\/.*;(iOS|iPhone|Android).*/) ? true : false;
    var isYzjDesktop = window.navigator.userAgent.match(/.*Qing\/.*/) ? true : false;
    if(isYunZhiJia || isYzjDesktop){
      _this.showChangeLan = false;
    }
	
    setTimeout(() => {
      _this.initsHRVersion()
      _this.search = localeResource.search;
      _this.getAgreementInfo();
      
      mbos.eas.invokeScript({
        name: "commonOSFservice",
        param: ['getLightAppListService', JSON.stringify({})],
        success: function (res) {
          if (res && res.length) {
            _this.originCategoricalDate = res
            _this.categoricalDate = res
               //对分组轻应用进行排序
               _this.categoricalDate.forEach(item => {
                item.children = item.children.sort((a,b)=>{
                  a.index = a.index || 0;
                  b.index = b.index || 0;
                  if(a.index && b.index){
                    return a.index - b.index;
                  }

                })
              });

            _this.originData = res.reduce((acc, item)=> acc.concat(item.children), [])
            _this.shrCommonlyUsed = usedStorage.map((number)=>{
              return _this.originData.find((item)=> item.number === number)
            }).filter(Boolean)
            window.localStorage.setItem("shrCommonlyUsed", JSON.stringify(_this.shrCommonlyUsed.map(({number})=> number)))
          }
        },
        error: function (e) {
          console.log(e);
        }
      })
      
      window.addEventListener('pageshow', function(){
            _this.getAgreementInfo();
        });

      if(easContext.locale === 'en_US'){
        _this.bannerUrl = "/mbos/store/4000148/shrnewlightapp/en_banner.png"
      }else{
        _this.bannerUrl = "/mbos/store/4000148/shrnewlightapp/banner.png"
      }
    })
  },
  methods: {
    onchange(e) {
      const value = e.target.value
      this.categoricalDate = this.originCategoricalDate.map((item)=> (
        {
          id: item.id,
          name: item.name,
          number: item.number,
          children: item.children.filter(({ name }) => name.includes(value))
        }
       ));

      let usedStorage = JSON.parse(window.localStorage.getItem('shrCommonlyUsed')) || [];

      this.shrCommonlyUsed = this.originData.filter(({ name, number }) => name.includes(value) && usedStorage.includes(number));

    },
    onItemClick(item) {
      // 分为常用 和其他分类
      /**
       * 如果是常用，把当前app移到常用的第一个，常用列表不增删
       * 如果是非常用，需要删掉常用的最后一个，然后把当前点击的app加入到常用的第一个，需要把常用的数据保存到 localStorage 
       */
      let usedStorage = JSON.parse(window.localStorage.getItem('shrCommonlyUsed')) || []
      const number = item.number
      const index = usedStorage.indexOf(number)
      if (index === -1) {
          //ES6及以上语法修改，旧版本浏览器和手机不识别，报错
          // usedStorage = [number, ...usedStorage.slice(0, 7)]
          usedStorage = usedStorage.slice(0, 7);
          usedStorage.unshift(number);
          //this.shrCommonlyUsed = [item, ...this.shrCommonlyUsed.slice(0, 7)]
          this.shrCommonlyUsed = this.shrCommonlyUsed.slice(0, 7);
		  this.shrCommonlyUsed.unshift(item);
      }else{
        if(index !== 0) {
          [usedStorage[0], usedStorage[index]] = [usedStorage[index], usedStorage[0]]
          this.shrCommonlyUsed = usedStorage.map((number)=>{
            return this.shrCommonlyUsed.find((data)=> data.number === number)
          })
        }
      }
      window.localStorage.setItem("shrCommonlyUsed", JSON.stringify(usedStorage))

      var params = new URLSearchParams(location.search);
      var searchParams = mbos.getRequestParams()
      
      // 处理天天勤跳转问题
      if(item.number === 'ttqin'){
        var urlArr = item.url.split('?')
        window.location.href =  urlArr[0].startsWith("/mbos/")? urlArr[0] + '?' + "eid=" + searchParams.eid + "&appid=10036" + "&ticket=" + params.get("ticket") + "&mtimestamp=" + new Date().getTime() + "&" + urlArr[1] : item.url;
      }else{

        window.location.href = item.url.startsWith("/mbos/") ? item.url + "&eid=" + searchParams.eid + "&appid=10036" + "&ticket=" + params.get("ticket") + "&mtimestamp=" + new Date().getTime() : item.url;
      }

    },
    initsHRVersion(){
      var _this = this
        var param = [];
        mbos.eas.invokeScript({
          name: "getSHRVersionInfo",
          param: param,
          success: function (resp) {
            if(!resp.isMuiltLang){
              _this.showChangeLan = false
            }
            var version = resp.version.split(".").map(num => num - 0) // 8.8.0.1
            if(version[0] < 8 ){
              _this.versionError = true
            }
            if(version[0] === 8 && version[1] < 8 ){
              _this.versionError = true
            }
            if(version[3] > 0 || version[0] > 8) {
                _this.isAllowVersion = true;
              }
          },
          error: function (res) {
            _this.versionError = true
          },
      });
	},
    switchLanguage() {
      var paramObj = mbos.getRequestParams();
      var url = location.origin + location.pathname + '?';
      var paramIndex = 0;
      
      window.localStorage.setItem("ismoren", 1);
      //window.localStorage.removeItem("lang");
      var l = easContext.locale;
      if (l == "l2") {
        l = "zh_CN";
        localStorage.setItem('lang',l);
      } else if (l == "l1") {
        l = "en_US";
        localStorage.setItem('lang',l);
      } else if (l == "l3") {
        l = "zh_TW";
        localStorage.setItem('lang',l);
      }

      for (var key in paramObj) {
        var val = paramObj[key];
        if (key === 'canChangeLanguage') {
          continue;
        } else if (key === 'locale') {
          continue;
        } else if (key === 'mtimestamp') {
          continue;
        }
        url += paramIndex++ > 0 ? '&' + key + '=' + val : key + '=' + val;
      }
      location.href = url + '&canChangeLanguage=0&locale=' + l + '&mtimestamp=' + new Date().getTime();
    },
    
    //点击跳转隐私声明界面
    turnToPrivacy() {
        path = mbos.pageInfo.path;
        name = 'agreePrivacy.navui'
        mbos.ui.open({
            path: path, 
            name: name
        });
    },
    
    disAgree(){
      	var isYunZhiJia = window.navigator.userAgent.match(/Qing\/.*;(iOS|iPhone|Android).*/) ? true : false;
        var isYzjDesktop = window.navigator.userAgent.match(/.*Qing\/.*/) ? true : false;
        if(isYunZhiJia || isYzjDesktop){
            XuntongJSBridge.call('closeWebView');
        }else{
            window.close();
        }
      },
    
    Agreement(){
        $('.mask-wrapper').hide();
      
      let that = this;
        let arr =[];
        that.agreements.filter(item=>{
            arr.push(item.id);
        });
        let obj = {
            signPerson: easContext.userID,
            agreementIds: arr.join(','),
            signState: 0
        };

        const param = ['signAgreementService', JSON.stringify(obj)];
        mbos.eas.invokeScript({
            name: 'commonOSFservice',
            needShowLoading: true,
            param: param,
            success: function(res){
                console.log(res,'sign');
            },
            error: function(res){
                console.log(res)
            }
        })
      },
    //获取未签署声明协议
    getAgreementInfo(){
        let that = this;
        let obj = {
              target: 'HomePage',//传应用场景的number
              lang: easContext.locale, //当前语言
              person: easContext.userID //当前签署人
            };
        const param = ['getAgreementInfoService', JSON.stringify(obj)];
        setTimeout(() =>{
          mbos.eas.invokeScript({
            name: 'commonOSFservice',
            param: param,
            success: function(res){
              if(res.errorCode == 0){
                if(that.isAllowVersion) {
                    that.signAgreement = true;
                  $('.mask-wrapper').show();
                }
                that.agreements = res.data;
              }else{
				        if(res.data.length == 0) {
                    that.signAgreement = false;
                }
              }
            },
            error: function(res){
              console.log(res,'error')
            }
          })
        },100)
      },
    
    //查看协议内容
    getAgreement(id){
        let that = this;
        let obj= {
            id: id,
            lang: easContext.locale
        };
        const param = ['getAgreementServiceByID', JSON.stringify(obj)];
        mbos.eas.invokeScript({
          name: 'commonOSFservice',
          needShowLoading: true,
          param: param,
          success: function(res){
            if(res.errorCode == '0'){
              that.showText = true;
              that.agreementText = res.data.content;
            }
          },
          error: function(res){
            console.log(res)
          }
        })
      },
    closeBtn(){
        this.showText = false;
      }
  }
})
