import { connect } from 'herculex';
Component(connect({
  mapStateToProps: {
    userInfo: state => state.$global.userInfo || {}
  }
})({
  props: {
    // 传入的phone 可能为空
    phone: '',
    hasPermission: false
  },

  async didMount() {
    const {
      phone,
      hasPermission
    } = this.props;
    const {
      phone: userInfoPhone = ''
    } = this.data.userInfo; // 如果没有上次下单手机号 获取登录的手机号

    this.setData({
      inputPhone: phone || userInfoPhone,
      hasPermission,
      phoneType: phone ? 'LAST_ORDER' : 'MY'
    });
  },

  data: {
    inputPhone: '',
    // phoneType类型 LAST_ORDER/CUSTOM/MY
    phoneType: 'LAST_ORDER'
  },
  methods: {
    /* 一键清除 */
    clearInput(value = '') {
      const {
        inputPhone
      } = this.data;
      return inputPhone.indexOf('*') < 0 ? value : '';
    },

    handleInput(e) {
      // 有输入 phoneType 为 CUSTOM
      const {
        value
      } = e.detail;
      this.setData({
        inputPhone: this.clearInput(value),
        phoneType: 'CUSTOM'
      });
    },

    // 获取手机号授权
    async onGetAuthorize() {
      const {
        phone = ''
      } = this.data.userInfo;

      if (phone) {
        // 成功获取到手机号 phoneType 为MY
        return this.setData({
          phoneType: 'MY',
          inputPhone: phone
        });
      }

      try {
        my.showLoading();
        const success = await this.dispatchGlobal('doLogin', {
          scopes: 'phoneNumber'
        });
        my.hideLoading();

        if (success) {
          this.setData({
            phoneType: 'MY',
            inputPhone: this.data.userInfo.phone
          });
        } else {
          // 无手机号获取权限
          my.showToast({
            content: '获取手机号失败，请检查小程序是否拥有my.getPhoneNumber权限',
            type: 'none'
          });
        }
      } catch (err) {
        my.hideLoading();
      }
    }

  }
}));