<template>
  <m-dialog title="手机号验证" width-type="2" :visible.sync="show" @submit="handleSubmit">
    <div class="mt-3">
      <m-form v-if="show" ref="form" :items="formItems">
        <template #phone>
          <v-btn :disabled="disableSend" color="primary" rounded class="buttons ml-3" @click="sendVerityCode">
            <template v-if="timer">重新发送 {{ timer }}s</template>
            <template v-else>发送验证码</template>
          </v-btn>
        </template>
      </m-form>
    </div>
  </m-dialog>
</template>

<script>
import MDialog from '@/components/Dialog'
import MForm from '@/components/Form/list'
import { getVerificationCode } from '@/api/system'
export default {
  name: 'phone-verify',
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  components: { MDialog, MForm },
  data () {
    return {
      timer: 0,
      intervalTimer: null,
      show: this.value,
      formItems: {
        options: [
          {
            type: 'number',
            key: 'phone',
            value: null,
            label: '请输入手机号码 *',
            slotName: 'phone',
            outlined: true,
            dense: true,
            rules: [v => /^1[3456789]\d{9}$/.test(v) || '请输入正确的手机号码']
          },
          {
            type: 'number',
            key: 'code',
            value: null,
            label: '请输入短信验证码 *',
            outlined: true,
            dense: true,
            rules: [v => !!v || '请输入短信验证码']
          }
        ]
      }
    }
  },
  watch: {
    value (val) {
      this.show = val
    },
    show (val) {
      this.$emit('input', val)
    }
  },
  computed: {
    disableSend () {
      const phone = this.formItems.options.find(_e => _e.key === 'phone').value
      // 定义手机号正则表达式
      const phoneRegex = /^1[3456789]\d{9}$/

      return this.timer > 0 || !phoneRegex.test(phone)
    }
  },
  methods: {
    async sendVerityCode () {
      if (this.disableSend) {
        return
      }
      const phone = this.formItems.options.find(_e => _e.key === 'phone').value
      try {
        await getVerificationCode({ phone })
        this.timer = 60
        this.intervalTimer = setInterval(() => {
          this.timer--
          if (!this.timer) {
            clearInterval(this.intervalTimer)
          }
        }, 1000)
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    handleSubmit () {
      if (!this.$refs.form.validate()) {
        return
      }
      const query = this.formItems.options.reduce((_e, _i) => {
        _e[_i.key] = _i.value
        return _e
      }, {})
      this.$emit('submit', query)
    }
  },
  beforeDestroy () {
    if (this.intervalTimer) {
      clearInterval(this.intervalTimer)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
