<template>

  <a-modal
    title="修改手机号"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @cancel="cancelHandel">
    <a-form :form="form">
      <a-form-item>
        <a-input size="large" type="text" placeholder="新手机号" v-decorator="['mobile', {rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号' }, { validator: this.handlePhoneCheck }], validateTrigger: 'change'}]">
          <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input>
      </a-form-item>

      <a-row :gutter="16">
        <a-col class="gutter-row" :span="16">
          <a-form-item>
            <a-input
              size="large"
              autocomplete="false"
              placeholder="图片验证码"
              v-decorator="[
                'captchaCode',
                {rules: [{ required: true, message: '图片验证码' }], validateTrigger: 'blur'}
              ]"
            >
              <a-icon slot="prefix" type="picture" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <img
            class="getCaptcha"
            :src="captchaImage"
            @click.stop.prevent="getCaptchaImage"
          />
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col class="gutter-row" :span="16">
          <a-form-item>
            <a-input size="large" type="text" placeholder="短信验证码" v-decorator="['smsCode', {rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur'}]">
              <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-button
            class="getCaptcha"
            tabindex="-1"
            :disabled="state.smsSendBtn"
            @click.stop.prevent="getCaptcha"
            v-text="!state.smsSendBtn && '获取验证码' || (state.time+' s')"
          ></a-button>
        </a-col>
      </a-row>
    </a-form>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">修改</a-button>
    </template>
  </a-modal>

</template>
<script>
import { getSmsCaptcha, checkCaptchaCode } from '@/api/upms/login'
import { queryUser, changeMobile } from '@/api/upms/user'

export default {
  components: {
  },
  data () {
    return {
      visible: false,
      confirmLoading: false,
      randomStr: '',
      captchaImage: null,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        smsSendBtn: false
      }
    }
  },
  created () {
    this.getCaptchaImage()
  },
  methods: {
    base () {
      this.visible = true
    },
    getCaptcha (e) {
      e.preventDefault()
      const { form: { validateFields }, state } = this

      validateFields(['mobile', 'captchaCode'], { force: true }, (err, values) => {
        if (!err) {
          checkCaptchaCode({ captchaCode: values.captchaCode, randomStr: this.randomStr }).then(res => {
            const flag = res.data
            if (flag) {
              state.smsSendBtn = true

              const interval = window.setInterval(() => {
                if (state.time-- <= 0) {
                  state.time = 60
                  state.smsSendBtn = false
                  window.clearInterval(interval)
                }
              }, 1000)

              const hide = this.$message.loading('验证码发送中..', 0)
              getSmsCaptcha({ mobile: values.mobile, captchaCode: values.captchaCode, randomStr: this.randomStr }).then(res => {
                setTimeout(hide, 2500)
                this.$notification['success']({
                  message: '提示',
                  description: '验证码获取成功，您的验证码为：' + res.data,
                  duration: 8
                })
              }).catch(err => {
                setTimeout(hide, 1)
                clearInterval(interval)
                state.time = 60
                state.smsSendBtn = false
                this.requestFailed(err)
              })
            } else {
              this.$message.error('图片验证码错误')
              this.getCaptchaImage()
            }
          })
        }
      })
    },
    getCaptchaImage () {
      this.randomStr = this.getRandomStr()
      this.captchaImage = process.env.VUE_APP_API_BASE_URL + '/verify/captcha/' + this.randomStr
    },
    getRandomStr () {
      return new Date().getTime() + Math.random() * 1000
    },
    save () {
      const { form: { validateFields } } = this
      this.confirmLoading = true
      validateFields({ force: true }, (errors, values) => {
        if (!errors) {
          values.phone = values.mobile
          changeMobile(values)
            .then(() => {
              setTimeout(() => {
                const userInfo = this.$store.getters.userInfo
                userInfo.phone = values.phone
                this.$store.dispatch('setUserInfo', userInfo)
                this.$emit('ok', values.phone)
                this.cancelHandel()
              }, 1500)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    cancelHandel () {
      this.visible = false
      this.confirmLoading = false
      this.form = this.$form.createForm(this)
      this.form.resetFields()
    },
    handlePhoneCheck (rule, value, callback) {
      if (value && value.length === 11) {
        queryUser({ phone: value }).then(res => {
          if (res.data && res.data.length > 0) {
            const id = res.data[0].userId
            const userId = this.$store.getters.userId
            if (userId == null || id !== userId) {
              callback(new Error('手机号已存在!'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        })
      } else {
        callback()
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }
</style>
