<template>
  <div id="password_reset">
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="120px"
             class="demo-ruleForm">
      <el-form-item label="服务商手机号码" prop="phone">
        <el-input class="input_class" type="tel" v-model="ruleForm.phone"
                  autocomplete="off" v-on:readonly="true"></el-input>
        <el-button style="margin-left: 5px" type="primary" v-on:click="sendVerificationCode"
                   :disabled="isDisabled">{{ content }}
        </el-button>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input class="input_class" type="text" v-model="ruleForm.code"
                  autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="用户手机号码" prop="userPhone">
        <el-input class="input_class" type="tel" v-model="ruleForm.userPhone"
                  autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { AxiosRequestData } from '@/data/axios_request'
import cache from '@/utils/cache'

export default {
  name: 'password_reset',
  data() {
    let checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号码不能为空！'))
      }
      if (!(/^1[3456789]\d{9}$/.test(value))) {
        callback(new Error('手机号码有误，请重填！'))
      } else {
        callback()
      }
    }
    let checkCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('验证码不能为空！'))
      } else {
        callback()
      }
    }
    return {
      form: {
        username: '',
        password: ''
      },
      loading: false,
      isForgotPasswordShow: false,
      ruleForm: {
        phone: '',
        code: '',
        userPhone: ''
      },
      rules: {
        phone: [
          { validator: checkPhone, trigger: 'blur' }
        ],
        code: [
          { validator: checkCode, trigger: 'blur' }
        ],
        userPhone: [
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      isDisabled: false, // 控制按钮是否可以点击（false:可以点击，true:不可点击）
      content: '获取短信验证码', // 发送验证码按钮的初始显示文字
      timer: null,
      count: ''
    }
  },
  created() {
    this.ruleForm.phone = this.$attrs.passwordReset.account
  },
  methods: {
    // 获取服务商手机号码
    getServerPhone(account) {
      this.ruleForm.phone = account
    },
    // 发送验证码
    async sendVerificationCode() {
      if (!this.ruleForm.phone || this.ruleForm.phone === '') {
        this.$message({
          message: '请输入手机号',
          type: 'warning'
        })
        return
      }
      if (!(/^1[345789]\d{9}$/.test(this.ruleForm.phone))) {
        this.$message({
          message: '请输入正确的手机号',
          type: 'warning'
        })
        return
      }
      const url = '/sms/getSmscode'
      let token = null
      let response = await AxiosRequestData(
          url,
          token,
          {
            phoneNo: this.ruleForm.phone
          },
          false,
          1
      )
      if (response) {
        if (response.code === 0) {
          this.$message({
            message: '验证码发送成功！',
            type: 'success'
          })
          this.sendCode()
        } else {
          this.$message.error('验证码发送失败！')
        }
      } else {
        this.$message.error('验证码发送失败！')
      }
    },
    // 发送验证码
    sendCode() {
      // 控制倒计时及按钮是否可以点击
      const TIME_COUNT = 60
      this.count = TIME_COUNT
      this.timer = window.setInterval(() => {
        if (this.count > 0 && this.count <= TIME_COUNT) {
          // 倒计时时不可点击
          this.isDisabled = true
          // 计时秒数
          this.count--
          // 更新按钮的文字内容
          this.content = this.count + 's后重新获取'
        } else {
          // 倒计时完，可点击
          this.isDisabled = false
          // 更新按钮文字内容
          this.content = '获取短信验证码'
          // 清空定时器!!!
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000)
    },
    // 修改用户密码
    changePassword(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitChangePassword()
        } else {
          return false
        }
      })
    },
    // 取消密码修改
    passwordChangeClose(formName) {
      this.$refs[formName].resetFields()
      this.isDisabled = false
      this.content = '获取短信验证码'
      this.timer = null
      this.count = ''
      this.ruleForm.code = ''
      this.ruleForm.phone = ''
      this.ruleForm.userPhone = ''
    },
    // 提交密码修改
    async submitChangePassword() {
      let token = cache.getToken()
      if (this.ruleForm.phone && token) {
        const url = '/auth/isp/user/resetPasswd'
        let response = await AxiosRequestData(
            url,
            token,
            {
              resetMobile: this.ruleForm.userPhone,
              smsCode: this.ruleForm.code,
              mobile: this.ruleForm.phone,
              reqChannel: 4
            },
            false,
            1
        )
        if (response) {
          if (response.code === 0) {
            this.$message({
              message: '密码重置成功！',
              type: 'success'
            })
            this.$attrs.passwordReset.passwordResetCancel()
          } else {
            this.$message.error(response.msg)
          }
        }
      }
    }
  }
}
</script>

<style scoped>
.input_class {
  width: 200px;
}
</style>
