<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    append-to-body
    width="520px"
    top="25vh"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <!-- 信息输入 -->
    <el-form ref="userForm" :model="userForm" :rules="rules" label-width="90px" label-position="right" v-if="!isPass">
      <el-form-item label="" prop="user" style="margin-bottom: 25px">
        <el-input
          style="width: 300px"
          v-model="userForm.user"
          autocomplete="off"
          type="text"
          placeholder="请输入用户名"
          prefix-icon="el-icon-user"
          clearable
        />
      </el-form-item>
    </el-form>
    <!-- 短信验证 -->
    <el-form
      ref="authCodeForm"
      :model="authCodeForm"
      :rules="rules"
      label-width="100px"
      label-position="right"
      v-if="isPass && !isAuth"
    >
      <el-form-item label="验证码" prop="code" style="margin-bottom: 25px">
        <el-input
          style="width: 300px"
          v-model="authCodeForm.code"
          autocomplete="off"
          type="text"
          placeholder="请输入接收到的短信验证码"
          prefix-icon="el-icon-key"
          clearable
        />
      </el-form-item>
    </el-form>
    <!-- 重置密码 -->
    <el-form ref="restForm" :model="restForm" :rules="rules" label-width="100px" label-position="right" v-if="isAuth">
      <el-form-item label="新密码：" prop="pass" style="margin-bottom: 25px">
        <el-input
          v-model="restForm.pass"
          autocomplete="off"
          type="password"
          placeholder="请输入密码"
          prefix-icon="el-icon-lock"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码：" prop="checkPass">
        <el-input
          v-model="restForm.checkPass"
          autocomplete="off"
          type="password"
          placeholder="请输入密码"
          prefix-icon="el-icon-lock"
          show-password
        />
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="cancel()">取消</el-button>
      <el-button type="primary" v-if="isAuth" @click="confirm()">确定</el-button>
      <el-button type="primary" v-else @click="getNext()">下一步</el-button>
    </template>
    <ModifyPsw :visible="isModify" :modifyParam="modifyParam" @refresh="refreshPass" @close="cancel()" />
  </el-dialog>
</template>

<script lang="ts">
import { Vue, Component, Watch, Prop } from 'vue-property-decorator'
import { regPhone, regNewPassword } from '@/utils/reg'
import { ElForm } from 'element-ui/types/form'
import { authcodeAdd, authcodeCheck, updatePasswordByUser } from '@/api/base'
import ModifyPsw from './modifyPsw.vue'
import { encryption } from '@/utils/encryption'

//重置密码
@Component({ name: 'resetPsw', components: { ModifyPsw } })
export default class resetPsw extends Vue {
  @Prop({ type: String, default: '' }) title!: string
  @Prop({ type: Boolean, default: false }) visible!: any
  @Prop({ type: String, default: '' }) username!: string
  @Prop({ type: Boolean, default: true }) isReset!: any

  @Watch('username', { immediate: true })
  onChange(val) {
    this.userForm.user = val
  }

  @Watch('visible', { immediate: true })
  onVisibleChange(val) {
    this.dialogVisible = val
  }

  dialogVisible = false

  passParam = null
  isPass = false
  isAuth = false
  isModify = false

  modifyParam = null

  userForm = { user: '' }

  authCodeForm = { code: '' }

  restForm = {
    pass: '',
    checkPass: ''
  }
  rules = {
    user: [{ required: true, message: '请输入用户名或者验证手机号', trigger: 'blur' }],
    pass: [{ required: true, validator: this.validatePwd1st, trigger: 'blur' }],
    checkPass: [{ required: true, validator: this.validatePwd2nd, trigger: 'blur' }]
  }

  getNext() {
    if (!this.isPass) {
      ;(this.$refs.userForm as ElForm).validate(async (valid) => {
        if (valid) {
          let value = this.userForm.user.trim()
          // if (Number(value)) {
          //   if (new RegExp(regPhone()).test(value)) {
          //     this.passParam = { phoneNumber: value }
          //     const res = await authcodeAdd(this.passParam)
          //     if (res.code == 1) {
          //       this.$message.success(res.result)
          //       this.isPass = true
          //       this.modifyParam = { username: value }
          //     }
          //   } else {
          //     this.$message.warning('请输入正确的手机号！')
          //   }
          // } else {
          this.passParam = { username: value }
          const res = await authcodeAdd(this.passParam)
          if (res.code == 1) {
            this.$message.success(res.result)
            this.isPass = true
            this.modifyParam = { username: value }
          }
          // }
        }
      })
    } else {
      ;(this.$refs.authCodeForm as ElForm).validate(async (valid) => {
        if (valid) {
          const res = await authcodeCheck({ ...this.passParam, codeInput: this.authCodeForm.code })
          if (res.result == 1) {
            if (this.isReset) {
              this.isAuth = true
            } else {
              this.dialogVisible = false
              this.isModify = true
            }
            setTimeout(() => {
              this.authCodeForm.code = ''
            }, 60000)
          } else {
            this.$message.warning('信息验证失败')
          }
        }
      })
    }
  }
  validatePwd1st(rule, value, callback) {
    if (value === '') {
      callback(new Error('请输入密码！'))
    } else {
      if (this.restForm.pass !== '') {
        if (!regNewPassword().test(value)) {
          callback(new Error('密码位数至少12位，必须包含大小写字母和数字，不可包含非法字符！'))
          return
        }
      }
      callback()
    }
  }
  validatePwd2nd(rule, value, callback) {
    if (value === '') {
      callback(new Error('请再次输入密码'))
    } else if (value !== this.restForm.pass && value !== '') {
      callback(new Error('两次输入密码不一致！'))
    } else {
      callback()
    }
  }
  confirm() {
    ;(this.$refs.restForm as ElForm).validate((valid) => {
      if (valid) {
        const data = {
          ...this.passParam,
          password: encryption(this.restForm.checkPass)
        }
        updatePasswordByUser(data).then((res) => {
          if (res.code == 1) {
            this.$message.success('重置密码成功！')
            // this.$emit('add', { password: this.restForm.checkPass, code: this.authCodeForm.code })
            this.refreshPass(this.restForm.checkPass)
            this.reset()
            this.$emit('cancel')
          }
        })
      } else return false
    })
  }

  refreshPass(password) {
    this.$emit('add', { password, code: this.authCodeForm.code })
  }

  cancel() {
    try {
      this.reset()
    } catch (error) {
      console.log(error)
    }
    this.$emit('cancel')
  }

  reset() {
    this.passParam = null

    this.isPass = false
    this.isAuth = false
    this.isModify = false
    // this.userForm = { user: '' }
    this.authCodeForm = { code: '' }
    this.restForm = {
      pass: '',
      checkPass: ''
    }
    if (this.$refs.userForm) (this.$refs.userForm as ElForm).resetFields()
    if (this.$refs.authCodeForm) (this.$refs.authCodeForm as ElForm).resetFields()
    if (this.$refs.restForm) (this.$refs.restForm as ElForm).resetFields()
  }
}
</script>

<style>
</style>