import "./bindphone.css";
/* script */
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
import Button from '../button';
import Tips from '../tips';
import PhoneNumber from './phone-number';
import Input from '../input';
import { componentMixin, createComponentName } from '../../utils/base';
const __vue_script__ = {
  name: createComponentName('auth-bindphone'),
  components: {
    Button,
    PhoneNumber,
    Input
  },
  mixins: [componentMixin],
  inject: ['vm'],

  data() {
    return {
      phoneNumberIsUsed: null,
      needRegister: false,
      codePendingRemain: null,
      phoneCheckStatus: 0,
      checkingPhone: false,
      loading: false
    };
  },

  mounted() {
    this.checkIsBinded();
  },

  methods: {
    // TODO: 向商目前只支持校验注册状态，无法区别QQ， Wechat 所以暂时关闭已注册的情况的错误处理
    async checkIsBinded() {
      if (!this.vm.form.phone.number) return;
      this.checkingPhone = true;

      try {
        const {
          result
        } = await this.vm.requestUms('checkPhoneNumberStatus', this.vm.form);
        this.phoneCheckStatus = result;

        if (result === 1) {
          Tips('手机号码未注册，填写密码注册');
          this.phoneNumberIsUsed = false;
          this.needRegister = true;
          return;
        } else if (result === 3) {
          this.phoneNumberIsUsed = true;
        } else if (result === 2) {
          this.phoneNumberIsUsed = false;
        } else {
          throw new Error('未知错误');
        }

        this.needRegister = false;
      } catch (error) {
        Tips(error);
      } finally {
        this.checkingPhone = false;
      }
    },

    beforeDestroy() {
      clearTimeout(this.codePendingTimer);
    },

    async sendVerifyCode() {
      try {
        if (this.phoneCheckStatus === 0) {
          await this.checkIsBinded();
        }

        await this.vm.requestUms('sendVerifyCode', { ...this.vm.form,
          type: 'login'
        });
        this.startCheckCodePending();
      } catch (error) {
        Tips(error);
      }
    },

    startCheckCodePending() {
      const check = () => {
        this.codePendingRemain -= 1;

        if (this.codePendingRemain <= 0) {
          this.codePendingRemain = null;
          return;
        }

        this.codePendingTimer = setTimeout(check, 1000);
      };

      clearTimeout(this.codePendingTimer);
      this.codePendingTimer = setTimeout(check, 1000);
      this.codePendingRemain = 60;
    },

    async skip() {
      try {
        let res;

        if (this.vm.bindphoneType === 'qq') {
          res = await this.vm.requestUms('skipBindQQ');
        } else if (this.vm.bindphoneType === 'wechat') {
          res = await this.vm.requestUms('skipBindWechat');
        } else {
          throw new Error('尚未通过第三方登录');
        }

        this.vm.onLogin(res.authorization_code, this.vm.bindphoneType);
        this.loading = false;
      } catch (error) {
        Tips(error);
        this.loading = false;
        this.vm.$emit('error', {
          action: 'bindphone',
          type: this.vm.bindphoneType,
          error: error
        });
      }
    },

    async onBindPhone() {
      if (this.loading) return;
      this.loading = true;

      try {
        if (this.phoneCheckStatus === 0) {
          throw new Error('请检查手机号或等待手机号检查完成');
        }

        let res;

        if (this.needRegister) {
          if (this.vm.bindphoneType === 'qq') {
            res = await this.vm.requestUms('registerByQQ', this.vm.form);
          } else if (this.vm.bindphoneType === 'wechat') {
            res = await this.vm.requestUms('registerByWechat', this.vm.form);
          } else {
            throw new Error('尚未通过第三方登录');
          }
        } else {
          if (this.vm.bindphoneType === 'qq') {
            res = await this.vm.requestUms('bindQQ', { ...this.vm.form
            });
          } else if (this.vm.bindphoneType === 'wechat') {
            res = await this.vm.requestUms('bindWechat', { ...this.vm.form
            });
          } else {
            throw new Error('尚未通过第三方登录');
          }
        }

        this.vm.$emit('success', {
          action: 'bindphone',
          type: this.vm.bindphoneType
        });
        this.vm.onLogin(res.authorization_code, this.vm.bindphoneType);
        this.loading = false;
      } catch (error) {
        Tips(error);
        this.loading = false;
        this.vm.$emit('error', {
          action: 'bindphone',
          type: this.vm.bindphoneType,
          error: error
        });
      }
    }

  }
};
/* template */

var __vue_render__ = function () {
  var _vm = this;

  var _h = _vm.$createElement;

  var _c = _vm._self._c || _h;

  return _c("div", {
    class: _vm.bem()
  }, [_c("div", {
    class: _vm.bem("title")
  }, [_vm._v("绑定手机号")]), _vm._v(" "), _c("div", {
    class: _vm.bem("skip"),
    on: {
      click: _vm.skip
    }
  }, [_vm._v("跳过")]), _vm._v(" "), _c("div", {
    class: _vm.bem("item")
  }, [_c("PhoneNumber", {
    attrs: {
      countries: _vm.vm.countries,
      loading: _vm.checkingPhone
    },
    on: {
      blur: _vm.checkIsBinded
    },
    model: {
      value: _vm.vm.form.phone,
      callback: function ($$v) {
        _vm.$set(_vm.vm.form, "phone", $$v);
      },
      expression: "vm.form.phone"
    }
  })], 1), _vm._v(" "), _c("div", {
    class: _vm.bem("item")
  }, [_c("Input", {
    attrs: {
      maxlength: "4",
      autocomplete: "off",
      placeholder: "输入短信中的验证码"
    },
    model: {
      value: _vm.vm.form.verifyCode,
      callback: function ($$v) {
        _vm.$set(_vm.vm.form, "verifyCode", $$v);
      },
      expression: "vm.form.verifyCode"
    }
  }), _vm._v(" "), _c("Button", {
    class: _vm.bem("sms-btn"),
    attrs: {
      rect: "",
      nativeType: "button",
      disabled: !!_vm.codePendingRemain
    },
    on: {
      click: _vm.sendVerifyCode
    }
  }, [_vm._v("\n            " + _vm._s(_vm.codePendingRemain ? _vm.codePendingRemain + "秒后获取" : "获取验证码") + "\n        ")])], 1), _vm._v(" "), _c("div", {
    directives: [{
      name: "show",
      rawName: "v-show",
      value: _vm.needRegister,
      expression: "needRegister"
    }],
    class: _vm.bem("item")
  }, [_c("Input", {
    attrs: {
      id: "password",
      type: "password",
      label: "密码",
      name: "new-password",
      autocomplete: "off",
      placeholder: "输入6-30位新密码",
      maxlength: "30"
    },
    on: {
      enter: _vm.onBindPhone
    },
    model: {
      value: _vm.vm.form.password,
      callback: function ($$v) {
        _vm.$set(_vm.vm.form, "password", $$v);
      },
      expression: "vm.form.password"
    }
  })], 1), _vm._v(" "), _c("Button", {
    class: _vm.bem("submit"),
    attrs: {
      type: "primary",
      size: "large",
      nativeType: "submit",
      disabled: _vm.loading
    },
    on: {
      click: _vm.onBindPhone
    }
  }, [_vm._v(_vm._s(_vm.needRegister ? "注册" : "绑定手机号"))])], 1);
};

var __vue_staticRenderFns__ = [];
__vue_render__._withStripped = true;
/* style */

const __vue_inject_styles__ = undefined;
/* scoped */

const __vue_scope_id__ = undefined;
/* module identifier */

const __vue_module_identifier__ = undefined;
/* functional template */

const __vue_is_functional_template__ = false;
/* component normalizer */

import __vue_normalize__ from '../../utils/vue-normalize-component.js';
/* style inject */

/* style inject SSR */

export default __vue_normalize__({
  render: __vue_render__,
  staticRenderFns: __vue_staticRenderFns__
}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined);