<template>
  <div class="comp-concat-info">
    <el-form ref="formRef" :model="form" :rules="formRules" size="small" label-position="top">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" clearable maxlength="11"/>
          </el-form-item>
        </el-col>
        <el-col v-if="needVcode" :span="12">
          <el-row :gutter="8">
            <el-col :span="16">
              <el-form-item label="验证码" prop="veCode">
                <el-input v-model="form.veCode" clearable maxlength="6" placeholder="请输入验证码"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="验证码" class="cci-hidden-form-item-label">
                <el-button :disabled="disableSendBtn" type="primary" size="small" @click.stop="clickSendVeCode">{{ sendBtnText }}</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { validPhone } from '@/utils/validate'
import { sendSmsCaptcha } from '@/api/realname-person'

export default {
  name: 'CompConcatInfo',
  props: {
    data: {
      type: Object,
      default: () => ({})
    },
    needVcode: {
      type: Boolean,
      default: true
    },
    bizType: {
      type: String,
      default: 'rnr'
    }
  },
  data() {
    const checkPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(`请输入手机号`))
      } else if (!validPhone(value)) {
        callback(new Error(`手机号格式不正确`))
      } else {
        callback()
      }
    }
    return {
      form: {
        phone: '',
        veCode: ''
      },
      formRules: {
        phone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ],
        veCode: [
          { required: true, message: '请输入验证码', trigger: 'change' }
        ]
      },
      sendBtnText: '发送验证码',
      countingDown: false
    }
  },
  computed: {
    disableSendBtn() {
      return this.countingDown || (this.form.phone === '' || !validPhone(this.form.phone))
    }
  },
  watch: {
    data() {
      this.updateInternalData()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.updateInternalData()
    },
    updateInternalData() {
      if (typeof this.data === 'object' && this.data !== null) {
        this.form.phone = this.data.phone || ''
        this.form.veCode = this.data.veCode || ''
      } else {
        this.form.phone = ''
        this.form.veCode = ''
        this.countingDown = false
        this.sendBtnText = '发送验证码'
      }
    },

    // 点击发送验证码
    clickSendVeCode() {
      if (this.countingDown) {
        return
      }
      this.countingDown = true
      this.sendVeCode()
      this.startCountingDown()
    },
    // 倒计时
    startCountingDown() {
      clearTimeout(this._ctTid)
      let ctNum = 59
      this.sendBtnText = `${ctNum--}S后重发`
      const countingDownHandler = () => {
        if (ctNum > 0) {
          this.sendBtnText = `${ctNum--}S后重发`
          this._ctTid = setTimeout(countingDownHandler, 1000)
        } else {
          this.sendBtnText = '发送验证码'
          this.countingDown = false
        }
      }
      this._ctTid = setTimeout(countingDownHandler, 1000)
    },

    async sendVeCode() {
      let ret = null
      try {
        ret = await sendSmsCaptcha({
          phone: this.form.phone,
          bizType: this.bizType
        })
      } catch (e) {
        ret = {}
      }
      return ret || {}
    },

    // 校验
    async validate(isErrorAnchor = false) {
      try {
        await this.$refs.formRef.validate()
        return true
      } catch (e) {
        if (isErrorAnchor) {
          this.$refs.formRef.fields.filter(item => item.validateState === 'error')[0].$el.scrollIntoView(true)
        }
        let temp = {
          anchor: () => {
            this.$refs.formRef.fields.filter(item => item.validateState === 'error')[0].$el.scrollIntoView(true)
            temp = null
          }
        }
        throw temp
      }
    },
    // 获取数据
    getFormData() {
      return {
        phone: this.form.phone,
        veCode: this.form.veCode
      }
    },
    // 获取待缓存数据
    getPendingCacheData() {
      return this.getFormData()
    },

    /**
     * 清空校验值
     */
    clearValidate() {
      this.$refs.formRef.clearValidate()
    }
  }
}
</script>

<style lang="scss">
.comp-concat-info {
  .cci-hidden-form-item-label {
    .el-form-item__label {
      visibility: hidden;
    }
  }
}
</style>
