<template>
<div>
  <el-steps :active="stepActive" align-center>
    <el-step title="步骤1"></el-step>
    <el-step title="步骤2"></el-step>
    <el-step title="步骤3"></el-step>
  </el-steps>
  <div v-if="stepActive === 1" class="step1">
    <el-form ref="form1" :model="accountSet" :rules="accountRules" @submit.native.prevent>
      <el-row>
        <el-col :xs="24" :sm="18" :md="18" :lg="18" :xl="18">
          <el-form-item prop="account">
            <el-input v-model="accountSet.account" type="text" placeholder="输入注册手机号/邮箱" @keyup.enter.native="onSubmitForm1"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
          <el-form-item>
            <el-button type="primary" @click="onSubmitForm1">发送验证码</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="go-back">
      <template v-if="query.rd">
        <router-link class="router-link-class" active-class="router-link-active-class" :to="{ path: '/login/index?rd=' + query.rd }">返回登录</router-link>
      </template>
      <template v-else>
        <router-link class="router-link-class" active-class="router-link-active-class" :to="{ name: 'normalLogin' }">返回登录</router-link>
      </template>
    </div>
  </div>
  <div v-if="stepActive === 2" class="step2">
    <div class="txt">
      验证码已发送至：{{accountSet.account}}
    </div>
    <el-form ref="form2" :model="accountSet" :rules="accountRules" @submit.native.prevent>
      <el-row>
        <el-col :xs="24" :sm="14" :md="14" :lg="14" :xl="14">
          <el-form-item label-width="1.2rem" prop="code" :label="(accountSet.type ? '邮箱验证码' : '手机验证码')">
            <el-input v-model="accountSet.code" type="text" placeholder="输入4位验证码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="10" :md="10" :lg="10" :xl="10">
          <el-form-item>
            <el-button type="primary" :disabled="isSendCode" @click="sendCode">{{sendBtnText}}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="operate">
      <el-row>
        <el-col :span="12">
          <el-button @click="goPrevStep">上一步</el-button>
        </el-col>
        <el-col :span="12">
          <el-button @click="onSubmitForm2">下一步</el-button>
        </el-col>
      </el-row>
    </div>
  </div>
  <div v-if="stepActive === 3" class="step3">
    <el-form ref="form3" :model="accountSet" :rules="accountRules">
      <el-form-item label-width="1.1rem" prop="newpwd" label="新密码">
        <el-input v-model="accountSet.newpwd" type="password" placeholder="请输入6-20个字母、数字及标点符号，不可仅数字"></el-input>
      </el-form-item>
      <el-form-item label-width="1.1rem" prop="repwd" label="重复新密码">
        <el-input v-model="accountSet.repwd" type="password" placeholder="请重新输入新密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmitForm3">完成</el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-dialog
    title=""
    :visible.sync="centerDialogVisible"
    width="30%"
    center append-to-body>
    <i class="el-icon-success" style="display: block; font-size: 0.6rem; text-align: center; color: #67c23a;"></i>
    <span style="display: block; margin-top: 0.2rem; text-align: center;">密码设置成功</span>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="goLogin">登 录</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
import { request } from '@actions'

export default {
  props: {
    params: { type: Object, required: false, default: {} },
    query: { type: Object, required: false, default: {} }
  },
  data () {
    /* 检查账号格式 */
    let checkAccount = (rule, value, callback) => {
      if (!/^(1[3-9]\d{9}|[\w\.]+@\w+(\.\w+)+)$/.test(value)) { // eslint-disable-line
        callback(new Error('请输入正确格式的手机号/邮箱'))
      } else {
        /* 手机格式 */
        if (/^(1[3-9]\d{9}$)/.test(value)) {
          this.accountSet.type = 0
        }
        /* 邮箱格式 */
        if (/^([\w\.]+@\w+(\.\w+)+)/.test(value)) { // eslint-disable-line
          this.accountSet.type = 1
        }
        callback()
      }
    }
    /* 检查密码 */
    let checkPwd = (rule, value, callback) => {
      if (value === this.accountSet.newpwd) {
        callback()
      } else {
        callback(new Error('两次输入密码不一致'))
      }
    }
    return {
      stepActive: 1,
      isSendCode: false, // 是否已发送验证码
      timeInterval: null, // 定时器，倒计时
      sendBtnText: '发送验证码', // 按钮 文字
      accountSet: {
        type: 0, // 0：表示手机格式，1：表示邮箱格式
        account: '',
        code: ''
      },
      accountRules: {
        'account': [
          { required: true, message: '请输入注册手机号/邮箱', trigger: 'blur' },
          { validator: checkAccount, trigger: 'change' }
        ],
        'code': [
          { required: true, message: '请输入4位数字验证码', trigger: 'blur' },
          { pattern: /^(\d{4})$/, message: '请输入4位数字验证码', trigger: 'change' }
        ],
        'newpwd': [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { pattern: /^.*[^\d]+.*$/, message: '请输入6-20个字母、数字及标点符号，不可仅数字', trigger: 'blur' }
        ],
        'repwd': [
          { required: true, message: '请重复输入新密码', trigger: 'blur' },
          { validator: checkPwd, trigger: 'change' }
        ]
      },
      centerDialogVisible: false // 修改密码成功弹框
    }
  },
  beforeDestroy () { /* 清空倒计时 */ this.clearTime() },
  methods: {
    /* 上一步 */
    goPrevStep () {
      this.stepActive -= 1
      /* 清空 第一步 填写内容 */
      this.accountSet.account = ''
      /* 清空倒计时 */
      this.clearTime()
    },
    /* 第一步 提交 */
    onSubmitForm1 () {
      this.$refs['form1'].validate((valid) => {
        if (valid) {
          /* 跳到第二步 */
          this.stepActive = 2
          /* 跳到第二步 并 发送验证码 */
          this.sendCode()
        } else {
          this.$message.error('请检查手机号或邮箱是否输入正确')
          return false
        }
      })
    },
    /* 发送验证码 */
    sendCode () {
      if (!this.isSendCode) {
        request({
          component: this,
          actionName: 'loginAction',
          functionName: 'sendResetPwdCode',
          data: {
            contact: this.accountSet.account,
            source_type: 3
          },
          thenCallback: res => {
            if (res.status === 200) {
              /* 发送验证码不管是否成功，都开始倒计时 */
              let time = 60
              this.isSendCode = true
              this.sendBtnText = '60s后重发'
              this.timeInterval = setInterval(() => {
                if (time-- > 0) {
                  this.sendBtnText = time + 's后重发'
                } else {
                  this.isSendCode = false
                  this.sendBtnText = '发送验证码'
                  clearInterval(this.timeInterval)
                }
              }, 1000)
            } else {
              return new Error(JSON.stringify(res))
            }
          },
          catchCallback: e => { this.goPrevStep() },
          finallyCallback: () => {}
        })
      }
    },
    /* 清空倒计时 */
    clearTime () {
      this.isSendCode = false
      this.sendBtnText = '发送验证码'
      clearInterval(this.timeInterval)
    },
    /* 第二步 提交 */
    onSubmitForm2 () {
      this.$refs['form2'].validate((valid) => {
        if (valid) {
          request({
            component: this,
            actionName: 'loginAction',
            functionName: 'validateCode',
            data: {
              contact: this.accountSet.account,
              code: this.accountSet.code
            },
            thenCallback: data => {
              if (data.status === 200) {
                /* 跳到第三步 */
                this.stepActive = 3
              } else {
                return new Error(JSON.stringify(data))
              }
            },
            catchCallback: () => {},
            finallyCallback: () => {}
          })
        } else {
          this.$message.error('请检查验证码是否输入正确！')
          return false
        }
      })
    },
    /* 第三步 提交 */
    onSubmitForm3 () {
      this.$refs['form3'].validate((valid) => {
        if (valid) {
          request({
            component: this,
            actionName: 'loginAction',
            functionName: 'resetPwd',
            data: {
              contact: this.accountSet.account,
              code: this.accountSet.code,
              new_password: this.accountSet.repwd
            },
            thenCallback: data => {
              if (data.status === 200) {
                this.centerDialogVisible = true
              } else {
                return new Error(JSON.stringify(data))
              }
            },
            catchCallback: () => {},
            finallyCallback: () => {}
          })
        } else {
          this.$message.error('请检查输入项是否输入正确！')
          return false
        }
      })
    },
    /**
     * 关闭弹框时，跳转 登录页
     */
    goLogin () {
      this.centerDialogVisible = false
      /* 跳转到 登录 */
      this.$router.push({ path: '/login/index' })
    }
  }
}
</script>
