/*
 * 全局注入器
 */
let page = {
  data() {
    return {
      emptyType: -1, // 0正确,1空,2错误
      isNoMore: false, // 没有更多
      errMsg: '暂无数据',
      pageIndex: 0,
      pageSize: 15,
      isLoad: true, // 是否加载
      isPull: false, // 是否下拉刷新
      isReach: false, // 是否上拉加载
      isFrefresh: false, // 是否加载数据中
      isFirstLoad: true, //是否第一次加载
      isEnabledReachBottom: true, //是否启动上拉加载
      loadOptions: {}, //加载参数
      themeColor: '',
      memberInfo: {},
      isLogin:false,  // 当前是否登录，未登录就是游客状态
    }
  },
  computed: {
    //ios底部安全区域
    safeAreaBottom() {
      let info = uni.getSystemInfoSync()
      let safe = 20
      if (
        info &&
        ['devtools', 'ios'].includes(info.platform) &&
        info.statusBarHeight > safe
      ) {
        return info.statusBarHeight - safe
      }
      return 0
    }
  },
  methods: {
	// 社区begin 
	  setData: function(obj, callback) {
	  	let that = this;
	  	const handleData = (tepData, tepKey, afterKey) => {
	  		tepKey = tepKey.split('.');
	  		tepKey.forEach(item => {
	  			if (tepData[item] === null || tepData[item] === undefined) {
	  				let reg = /^[0-9]+$/;
	  				tepData[item] = reg.test(afterKey) ? [] : {};
	  				tepData = tepData[item];
	  			} else {
	  				tepData = tepData[item];
	  			}
	  		});
	  		return tepData;
	  	};
	  	const isFn = function(value) {
	  		return typeof value == 'function' || false;
	  	};
	  	Object.keys(obj).forEach(function(key) {
	  		let val = obj[key];
	  		key = key.replace(/\]/g, '').replace(/\[/g, '.');
	  		let front, after;
	  		let index_after = key.lastIndexOf('.');
	  		if (index_after != -1) {
	  			after = key.slice(index_after + 1);
	  			front = handleData(that, key.slice(0, index_after), after);
	  		} else {
	  			after = key;
	  			front = that;
	  		}
	  		if (front.$data && front.$data[after] === undefined) {
	  			Object.defineProperty(front, after, {
	  				get() {
	  					return front.$data[after];
	  				},
	  				set(newValue) {
	  					front.$data[after] = newValue;
	  					that.$forceUpdate();
	  				},
	  				enumerable: true,
	  				configurable: true
	  			});
	  			front[after] = val;
	  		} else {
	  			that.$set(front, after, val);
	  		}
	  	});
	  	// this.$forceUpdate();
	  	isFn(callback) && this.$nextTick(callback);
	  },
	  // 社区end

    //获取数据列表
    getDataList(res) {
      this.isFrefresh = false
      let list = []
      if (typeof res == 'object') {
        if (Object.prototype.toString.call(res) == '[object Array]') {
          //data是数组
          list = res
        }

        if (list.length > 0) {
          //正常列表数据
          this.pageIndex += 1
          this.emptyType = 0
        } else {
          if (this.pageIndex <= 0) {
            //第1页时显示空
            this.emptyType = 1
            this.isNoMore = false
          } else {
            //不是第1页显示没有更多
            this.emptyType = 0
            this.isNoMore = true
          }
        }
      }
      return list
    },
    //停止下拉加载器
    stopPullDownRefresh() {
      this.isFrefresh = false
      uni.stopPullDownRefresh()
    },
    onPageLoad(options) {
      //页面加载 页面使用该函数会覆盖此函数
      if (this.isPull) {
      }
    },
    onLoadPage(options) {
	  wx.hideShareMenu();
      this.onPageLoad(options)
    },
    onPullDownRefresh() {
      this.onPullDownRefreshPage()
    },
    onPullDownRefreshPage() {
      //下拉刷新
      //需要在 page.json 文件设置"enablePullDownRefresh": true
      this.isLoad = false
      this.isPull = true
      this.isReach = false
      this.pageIndex = 1
      this.isNoMore = false
      this.isFrefresh = true
      this.onLoadPage(this.loadOptions)
    },
    onReachBottom() {
      this.onReachBottomPage()
    },
    onReachBottomPage() {
      if (this.isEnabledReachBottom) {
        if (!this.isNoMore && !this.isFrefresh) {
          //底部上拉加载更多
          this.isLoad = false
          this.isPull = false
          this.isReach = true
          this.isFrefresh = true
          this.onLoadPage(this.loadOptions)
        }
      }
    },
    onShow() {
      this.onShowPage()
    },
    onShowPage() {
      if (!this.isFirstLoad) {
        let route = this.$util.getCurrentRoute()
        if (this.$util.doIsRefreshPage(route)) {
          this.onPullDownRefresh()
        }
      } else {
        this.isFirstLoad = false
      }
    },

    getSceneValue(scene, name) {
      var arr,
        reg = new RegExp('(^|-)' + name + ':([^-]*)(-|$)')
      if ((arr = scene.match(reg))) {
        return unescape(arr[2])
      } else {
        return ''
      }
    },

    getSceneParams(options) {
      //s:来源Id
      //p:跳转路径
      //r:推荐人Id
      //o:营业点Id
      //pr:路径参数

      // options.scene = "sd:1-ph:goods_des-rmd:1-od:1-par:1_2_3";
      //options.scene="pr%3A175-r%3A3742-p%3A3-o%3A20";

      // options.scene="1-goods_des-1-1-1_2_3";
      // sourceId(来源)+ "-" + path(跳转路径) + "-" + recommond_member_id(推荐人Id)+"-"+org_id(营业点)"-"+params(跳转路径的参数)
      let scene = decodeURIComponent(options.scene)
      if (scene) {
        let obj = {}
        let pat = /\w+:\w+/gi
        let isNewMethod = pat.test(scene)
        if (isNewMethod) {
          obj.s = this.getSceneValue(scene, 's')
          obj.p = this.getSceneValue(scene, 'p')
          obj.r = this.getSceneValue(scene, 'r')
          obj.o = this.getSceneValue(scene, 'o')
          obj.pr = this.getSceneValue(scene, 'pr')
        } else {
          let arr = scene.split('-')
          if (arr.length == 5) {
            obj.s = arr[0]
            obj.p = arr[1]
            obj.r = arr[2]
            obj.o = arr[3]
            obj.pr = arr[4]
          }
        }
        return obj
      }
      return {}
    },

    getSharePageEnume(value) {
      for (let key in this.$global.sharePageList) {
        if (this.$global.sharePageList[key] == value) {
          return key
        }
      }
      return null
    },

    setSceneParamsStr(obj) {
      let arr = Object.keys(obj)
      let scene = ''
      for (let item of arr) {
        scene += item + ':' + obj[item] + '-'
      }
      scene = scene.slice(0, scene.length - 1)
      return scene
    },

    /**
     * 验证方法
     * @param {Object} rules 规则
     * @param {Context} prop 属性归属的对象
     *
     * @return 无
     */
    validate(rules, prop = this) {
      let keys = Object.keys(rules)
      let state = 'continue' // interrupt, finished
      outer: for (let key of keys) {
        let _rule = rules[key]
        for (let o of _rule) {
          let _propValue = prop[key]
          if (o.required) {
            if (o.opt === 'trim') {
              _propValue = _propValue.trim()
            }
            if (!_propValue || _propValue == '') {
              this.$dialog.alert({
                content: o.message
              })
              state = 'interrupt'
              break outer
            }
          }
          if (o.type === 'mobile') {
            if (!this.$util.isPhone(_propValue)) {
              this.$dialog.alert({
                content: o.message
              })
              state = 'interrupt'
              break outer
            }
          }
        }
      }
      if (state === 'continue') {
        return true
      }
      return false
    },
    //打电话
    makePhoneCall(phoneNumber, content) {
      let platform = uni.getSystemInfoSync().platform
      if (['ios', 'devtools'].includes(platform)) {
        uni.makePhoneCall({
          phoneNumber: phoneNumber
        })
        return
      } else {
        this.$dialog.confirm({
          content: content || '确认拨打电话：' + phoneNumber + ' 吗？',
          success: function success(res) {
            if (res.confirm) {
              uni.makePhoneCall({
                phoneNumber: phoneNumber
              })
            }
          }
        })
      }
    }
  },
  onLoad(options) {
    //请直接使用methods的onPageLoad函数
    this.loadOptions = options
    this.isLoad = true
    this.isPull = false
    this.isReach = false
    this.isFrefresh = true
    this.onLoadPage(options)
  }
}

export default page
