<template>
  <div class="p-2">
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" :draggable="draggable">
      <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="人员姓名" prop="realName">
          <el-input v-model="realNames" type="textarea" :rows="5" />
        </el-form-item>
        <el-form-item label="消费密码" prop="consumePwd">
          <el-input v-model="formData.consumePwd" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="formLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ResetConsumePwdForm" lang="ts">
import * as api from '@/api/payment/account';
import { PtUserAccountForm } from '@/api/payment/account/types';

defineOptions({ name: 'ResetConsumePwdForm' });

/** 接收父组件传入属性 */
//const props = defineProps({resetName})

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 对话框
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 窗体是否可以拖动
const draggable = ref(true);
// 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formLoading = ref(false);
// 表单的类型：create - 新增；update - 修改
const formType = ref('');
// 表单引用
const formRef = ref<ElFormInstance>();
// 表单数据
const formData = ref<PtUserAccountForm>({
  realName: '',
  consumePwd: '123456'
});
// 表单校验规则
const formRules = reactive({
  consumePwd: [{ required: true, message: '消费密码不能为空', trigger: 'blur' }]
});
const userIds = ref<string | number | Array<string | number>>();
const realNames = ref();
/** 当前组件方法 */
/** 窗体打开事件 */
const open = async (id?: string | number, name?: string) => {
  dialog.visible = true;
  dialog.title = '重置消费密码';
  formType.value = 'edit';
  userIds.value = id;
  realNames.value = name;

  resetForm();
};
/** 表单重置 */
const resetForm = () => {
  formData.value = {
    realName: '',
    consumePwd: '123456'
  };
  formRef.value?.resetFields();
};
/** 传回给父组件的属性与方法 */
// 提供 open 方法，用于打开弹窗
defineExpose({ open });

/** 触发父组件的事件 */
// 定义 success 事件，用于操作成功后的回调
const emit = defineEmits(['success']);
/** 提交按钮 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return;
  const valid = await formRef.value?.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as PtUserAccountForm;
    await api.resetConsumePwd(userIds.value, data.consumePwd);
    dialog.visible = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};

/** 初始化 */
onMounted(() => {});
</script>
