<template>
  <base-dialog v-model="visible" title="个人信息" :footer="false" destroy-on-close>
    <base-form ref="formRef" :model="userModel" :rules="rules" :items="items" :label-width="useVW(72)">
      <template #form-item-confirm>
        <confirm-button class="m-t-large" @confirm="onSubmit" @cancel="visible = false"></confirm-button>
      </template>
    </base-form>
  </base-dialog>
</template>

<script setup lang="ts" name="UpdateUserPwd">
import { reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import useFetch from '@/hooks/useFetch'
import useVModel from '@/hooks/useVModel'
import useVW from '@/hooks/useVW'
import useForm from '@/hooks/useForm'
import BaseForm from '@/components/element/BaseForm.vue'
import BaseDialog from '@/components/element/BaseDialog.vue'
import ConfirmButton from '@/components/common/ConfirmButton.vue'

import type { EpFormItem, EpFormRules } from 'global-type'

const props = defineProps<{
  userName: string
  modelValue: boolean
}>()

const visible = useVModel(props, 'modelValue')

const { formRef, elFormRef } = useForm()

const userModel = reactive<{ name: string; password: string; rePassword?: string }>({
  name: props.userName,
  password: '',
  rePassword: '',
})

watch(
  () => props.userName,
  () => {
    userModel.name = props.userName
  }
)

const rules: EpFormRules = {
  password: [{ required: true, message: '请填写登录密码' }],
  rePassword: [
    {
      required: true,
      validator(_, value, cb) {
        if (!value) {
          cb(new Error('请确认登录密码'))
        } else if (value !== userModel.password) {
          cb(new Error('两次输入密码不一致'))
        } else {
          cb()
        }
      },
    },
  ],
}

const items: EpFormItem[] = [
  { label: '姓名', prop: 'name', slotType: 'input', slot: { disabled: true } },
  { label: '新密码', prop: 'password', slotType: 'input', slot: { type: 'password' } },
  { label: '确认密码', prop: 'rePassword', slotType: 'input', slot: { type: 'password' } },
  { slotName: 'confirm' },
]

const onSubmit = async () => {
  try {
    const valid = await elFormRef?.value?.validate()
    valid && (await useFetch('updateUserPwd').fetch({ password: userModel.password }))
    visible.value = false
    ElMessage.success('修改成功')
  } catch (error) {
    console.error(error)
  }
}
</script>

<style scoped lang="scss"></style>
