<template>
  <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="off" label-position="left">
    <el-form-item prop="phone">
      <el-input v-model="loginForm.phone" placeholder="手机号码" autocomplete="off" type="text" maxlength="11" auto-complete="on" />
    </el-form-item>
    <slot name="password"/>
    <el-form-item prop="captcha">
      <div class="phone-captcha">
        <el-input v-model="loginForm.captcha" placeholder="图形验证码" autocomplete="off" type="text" maxlength="6" auto-complete="on">
          <img slot="suffix" :src="captchaImg" class="captch-img" alt="验证码" @click="fetchVerifyGraphic">
        </el-input>
      </div>
    </el-form-item>
    <el-form-item prop="sms">
      <div class="input-wrap">
        <el-input v-model="loginForm.sms" placeholder="验证码" autocomplete="off" type="text" maxlength="6" auto-complete="on">
          <el-button slot="suffix" :disabled="time > 0" type="text" @click="getSmsCaptcha">{{ captchaBtnText }}</el-button>
        </el-input>
      </div>
    </el-form-item>
  </el-form>
</template>

<script>
import { validPhone } from '@/utils/validate'
import SvgIcon from '@/components/SvgIcon'
import { sendSmsCaptcha, getGraphic } from '@/api/user'
export default {
  name: 'Msg',
  components: { SvgIcon },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('请输入手机号码'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('请输入短信验证码'))
      } else {
        callback()
      }
    }
    const validateCaptcha = (rule, value, callback) => {
      if (value.length !== 4) {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        phone: '',
        captcha: '',
        sms: ''
      },
      loginRules: {
        phone: [
          { trigger: 'blur', validator: validateUsername }
        ],
        captcha: [
          { trigger: 'blur', validator: validateCaptcha }
        ],
        sms: [
          { trigger: 'blur', validator: validatePassword }
        ]
      },
      // 图片验证码
      captchaImg: '',
      // 请求图片验证码返回的请求id
      requestId: '',
      captchaBtnText: '发送验证码',
      timer: null,
      time: 0
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    // 默认查询图片验证码
    this.fetchVerifyGraphic()
  },
  methods: {
    /**
     * 查询图片验证码
     */
    async fetchVerifyGraphic() {
      // 获取图片验证码
      const { captchaImg, requestId } = await getGraphic({ platformSource: 'Web' })
      // 记录当前图片验证码
      this.captchaImg = captchaImg
      // 请求id
      this.requestId = requestId
    },

    /**
     * 获取短信验证码
     */
    getSmsCaptcha() {
      // 校验结果
      const validResult = []
      this.$refs.loginForm.validateField(
        ['phone', 'captcha'],
        (errorMsg) => {
          if (!errorMsg) {
            validResult.push(errorMsg)
            // 没有校验完全
            if (validResult.length !== 2) {
              return
            }
            clearTimeout(this.timer)
            sendSmsCaptcha({
              phone: this.loginForm.phone,
              captchaImage: this.loginForm.captcha,
              requestId: this.requestId,
              platformSource: 'Web'
            }).then(data => {
              this.time = 60
              this.captchaBtnText = `${this.time - 1}S后重发`
              this.countdown()
            }).catch(() => {
              // 如果接口报错了，则刷新二维码
              this.fetchVerifyGraphic()
              this.captchaBtnText = '重新获取'
            })
          }
        })
    },

    /**
     * 开始倒计时
     */
    countdown() {
      this.timer = setTimeout(() => {
        if (this.time > 1) {
          this.time--
          this.captchaBtnText = `${this.time}S后重发`
          this.countdown()
        } else {
          this.time = 0
          clearTimeout(this.timer)
          this.captchaBtnText = '重新获取'
        }
      }, 1000)
    },
    getData() {
      // 校验结果
      let result
      const validResult = []
      this.$refs.loginForm.validateField(
        ['phone', 'sms'],
        (errorMsg) => {
          if (!errorMsg) {
            validResult.push(errorMsg)
            // 没有校验完全
            if (validResult.length !== 2) {
              result = false
              return
            }
            result = this.loginForm
          }
        })
      return result
    },
    // 失败，清空验证码们，并重新获取图形验证码
    clearInit() {
      this.fetchVerifyGraphic()
      this.loginForm.captcha = ''
      this.loginForm.sms = ''
    }
  }
}
</script>

<style lang="scss">

    .login-form {
      width: 100%;
      .btn-send-sms {
        background-color: #ffffff;
        border-color: #2A68FF;
        color: #2A68FF;
        height: 36px;
        padding: 0;
        width: 120px;
      }

      .phone-captcha {
        display: flex;
        .captcha-img-wrap {
          align-items: center;
          display: flex;
          margin-top: 1px;
          .captch-img {
            flex-shrink: 0;
            width: 90px;
            height: 40px;
          }
          .refresh-captcha {
            cursor: pointer;
            font-size: 20px;
            width: 20px;
            height: 20px;
            margin-left: 4px;
          }
        }
        .el-button {
          margin-left: 10px;
          flex: none;
          width: 120px;
        }
        .captch-img {
          width: 90px;
          height: 40px;
          margin-top: -6px;
        }
      }
      .input-wrap {
        display: flex;
      }
      .forget-password {
        display: flex;
        justify-content: flex-end;
        .el-button {
          padding: 24px 0 0;
        }
      }
    }

</style>
