<script setup lang="ts">
import { computed, ref, unref } from "vue";
import { BasicForm } from "/@/components/BasicForm";
import { modalProps } from "./types";
import { ElMessage } from "element-plus";
import { useNav } from "/@/layout/hooks/useNav";
import { responseHandle } from "/@/utils/responseHandle";
const props = defineProps(modalProps);
const { logout } = useNav();
const modelTitle = computed(() => props.modalConfig.title);
const modelFormItems = computed(() => props.modalConfig.formItems);
const formData = ref({});
const formRef = ref<InstanceType<typeof BasicForm>>(null);
const dialogVisible = ref(false);
const confirmLoading = ref(false);
function handleConfirmClick() {
  formRef.value.validate(async isVaild => {
    //表单校验通过派发事件
    if (isVaild) {
      if (confirmLoading.value) return;
      if (
        formData.value[modelFormItems.value[1].field] !==
        formData.value[modelFormItems.value[2].field]
      ) {
        ElMessage.warning("新密码与确认密码不一致");
        return;
      }
      confirmLoading.value = true;
      const { modalConfig } = props;
      const { httpChangePwd } = modalConfig;
      const { code, message } = await httpChangePwd(unref(formData));
      responseHandle({
        code,
        message,
        logout,
        hasError: true,
        handler: () => {
          dialogVisible.value = false;
          confirmLoading.value = false;
          ElMessage.success(message);
        },
        error: () => {
          ElMessage.error(message);
          confirmLoading.value = false;
        }
      });
    }
  });
}
async function show(id) {
  modelFormItems.value.forEach(item => {
    if (item.field === "id") {
      formData.value[item.field] = id;
    } else {
      formData.value[item.field] = "";
    }
  });
  dialogVisible.value = true;
}
defineExpose({
  show
});
</script>

<template>
  <el-dialog
    :title="modelTitle"
    v-model="dialogVisible"
    :close-on-press-escape="false"
    center
    append-to-body
    destroy-on-close
    width="500px"
  >
    <!-- 表单 -->
    <BasicForm
      ref="formRef"
      v-bind="props.modalConfig"
      v-model:form-data="formData"
    />

    <!-- 保存/重置 -->
    <div class="flex justify-end">
      <el-button
        type="primary"
        :loading="confirmLoading"
        @click="handleConfirmClick"
        >保存</el-button
      >
      <el-button @click="dialogVisible = false">关闭</el-button>
    </div>
  </el-dialog>
</template>
