<script setup lang="ts">
import type { UserModel }                      from '@/model/system.model';
import { updateUserPasswordMethod }            from '@/request/api/system.api';
import { useRequest }                          from 'alova/client';
import type { VxeFormListeners, VxeFormProps } from 'vxe-pc-ui';


interface FormModel {
  userId: string;
  password?: string;
  twice?: string;
}

const props = defineProps<{ data: UserModel, update?: boolean }>();
const emits = defineEmits<{
  submit: [],
}>();
const { loading: submitting, send: submit } = useRequest(
  (data) => updateUserPasswordMethod(data, props.update),
  { immediate: false },
).onSuccess(({ data }) => {
  emits('submit');
});
const formProps = reactive<VxeFormProps<FormModel>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: { userId: props.data.userId },
  items: [
    {
      visible: props.update,
      field: 'old',
      title: '旧密码',
      span: 24,
      itemRender: { name: 'VxeInput', props: { type: 'password' } },
    },
    { field: 'password', title: '新密码', span: 24, itemRender: { name: 'VxeInput', props: { type: 'password' } } },
    { field: 'twice', title: '再次输入', span: 24, itemRender: { name: 'VxeInput', props: { type: 'password' } } },
    { align: 'center', span: 24, slots: { default: 'active' } },
  ],
  rules: {
    old: [
      { required: props.update, validator: 'ValidPassword' },
    ],
    password: [
      { required: true, validator: 'ValidPassword' },
    ],
    twice: [
      { required: true, message: '请再次输入密码' },
      { required: true, validator: 'ValidPassword' },
      {
        required: true, validator: (params) => {
          if ( !params.itemValue || !params.data.password ) return;
          if ( params.data.password !== params.itemValue ) return new Error(`两次输入的密码不一致`);
        },
      },
    ],
  },
});
const formEmits: VxeFormListeners<FormModel> = {
  submit({ data }) { submit(data); },
};
</script>
<template>
  <vxe-form v-bind="formProps" v-on="formEmits">
    <template #active>
      <vxe-button type="submit" status="primary" content="提交" :loading="submitting"></vxe-button>
    </template>
  </vxe-form>
</template>
<style scoped lang="scss">
</style>
