<template>
  <DialogLayout
    title="修改密码"
    :visible="$store.update_password_dialog.visible"
    @onCancel="onClose"
    @onConfirm="onConfirm"
  >
    <FormLayout
      class="mr-12"
      ref="formLayoutRef"
      :items="form_items"
      :model="form_data"
      :rules="rules"
      label-width="100px"
      label-position="right"
    />
  </DialogLayout>
</template>

<script>
import { DialogLayout, FormLayout } from '@/components/layout'
import { updatePasswordApi } from '@/api/system/user'

export default {
  components: { DialogLayout, FormLayout },

  data: () => ({ form_data: null }),

  created () {
    this.form_data = { oldPassword: '', password: '', confirmPassword: '' }

    this.form_items = [
      { prop: 'oldPassword', label: '旧密码', model: { tag: 'el-input', type: 'password', attrs: { maxlength: 12 } } },
      { prop: 'password', label: '新密码', model: { tag: 'el-input', type: 'password', attrs: { maxlength: 12, placeholder: '6-12位字母加数字' } } },
      { prop: 'confirmPassword', label: '确认密码', model: { tag: 'el-input', type: 'password', attrs: { maxlength: 12 } } }
    ]

    const validator = (rule, value, callback) => {
      if (/^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,12}$/.test(value)) return callback()
      return callback(Error())
    }

    this.rules = {
      oldPassword: { required: true, message: '旧密码输入不合法', trigger: 'blur' },
      password: { required: true, validator, message: '新密码输入不合法', trigger: 'blur' },
      confirmPassword: { required: true, validator, message: '确认密码输入不合法', trigger: 'blur' }
    }
  },

  methods: {
    async onConfirm () {
      await this.$refs.formLayoutRef.validate()
      await updatePasswordApi(this.form_data)
      this.$message.success('密码修改成功')
      this.$store.logout()
    },

    onClose () {
      this.$store.update_password_dialog.visible = false
    }
  }
}
</script>

<style>

</style>
