<script setup lang="ts">
import type { VxeFormInstance, VxeFormProps } from 'vxe-pc-ui'

import { updatePassword } from '#/api'
import hud from '#/utils/hud'

import { mj_form_input } from '../mj/mj-table'

type FormData = {
  confirmPassword: string
  newPassword: string
  oldPassword: string
}

defineOptions({ name: 'ModifyPassword' })
const props = withDefaults(
  defineProps<{
    modelValue?: boolean
  }>(),
  {
    modelValue: false,
  },
)
const emits = defineEmits(['update:modelValue', 'ok'])
const show = computed({
  get() {
    return props.modelValue
  },
  async set(newVal) {
    emits('update:modelValue', newVal)
  },
})

const formRef = ref<VxeFormInstance<FormData>>()
const form = {
  rules: {
    oldPassword: [
      {
        required: true,
        message: '旧密码不能为空',
      },
    ],
    newPassword: [
      {
        required: true,
        message: '新密码不能为空',
      },
    ],
    confirmPassword: [
      {
        required: true,
        message: '确认密码不能为空',
      },
    ],
  },
  titleWidth: 100,
  items: [
    {
      field: 'oldPassword',
      title: '旧密码',
      itemRender: {
        name: mj_form_input,
        props: { clearable: true },
      },
      span: 24,
    },
    {
      field: 'newPassword',
      title: '新密码',
      type: 'password',
      itemRender: {
        name: mj_form_input,
        props: { clearable: true, type: 'password' },
      },
      span: 24,
    },
    {
      field: 'confirmPassword',
      title: '确认密码',
      type: 'password',
      itemRender: {
        name: mj_form_input,
        props: { clearable: true, type: 'password' },
      },
      span: 24,
    },
    {
      span: 24,
      slots: {
        default: 'operation',
      },
    },
  ],
  data: {} as FormData,
} as VxeFormProps<FormData>

async function ok() {
  const error = await formRef.value?.validate()
  if (error) return
  if (form.data?.oldPassword === form.data?.newPassword) {
    hud.error('新密码不能和旧密码相同')
    return
  }
  if (form.data?.newPassword !== form.data?.confirmPassword) {
    hud.error('确认密码和新密码不一致')
    return
  }
  hud.load({
    task: async () => {
      await updatePassword({
        oldPassword: form.data?.oldPassword,
        newPassword: form.data?.newPassword,
      })
      emits('update:modelValue', false)
    },
    option: '修改',
    hideSuccess: false,
  })
}
</script>

<template>
  <mj-modal
    v-model="show"
    :options="{
      title: '修改密码',
      width: '500px',
    }"
  >
    <VxeForm ref="formRef" v-bind="form">
      <template #operation>
        <el-button type="primary" class="sure-btn" @click="ok">确定</el-button>
      </template>
    </VxeForm>
  </mj-modal>
</template>

<style lang="scss" scoped>
.sure-btn {
  width: 100%;
}
</style>
