<script setup lang="ts">
import { computed, ref, unref, watch } from "vue";
import Description from "./description.vue";
import { BasicForm, FormItem } from "/@/components/BasicForm";
import { ActionType } from "/@/components/PageContent";
import { createBasicTitle } from "./utils/create-basic-title";
import { modalProps } from "./types";

const props = defineProps(modalProps);
const emit = defineEmits(["confirmBtnClick"]);

const formData = ref({});

const type = ref<ActionType>("preview");
const formRef = ref<InstanceType<typeof BasicForm>>(null);
const dialogVisible = ref(false);
const confirmLoading = ref(false);

//状态是否处于预览详情
const isPreview = computed(() => type.value === "preview");
const title = computed(() => {
  const basicTitle = createBasicTitle(type.value);
  return type.value === "preview"
    ? props.modalConfig.title + basicTitle
    : basicTitle + props.modalConfig.title;
});

function changeDefaultInfo(formItems: Array<FormItem>, newVal: any) {
  for (const item of formItems) {
    const isCheckBox = item.type === "checkbox";

    formData.value[item.field] = isCheckBox
      ? newVal[item.field]
        ? newVal[item.field].split(",")
        : []
      : newVal[item.field]
      ? String(newVal[item.field])
      : "";
  }
}

watch(
  () => props.defaultInfo,
  newVal => {
    const { formGroup, formItems } = props.modalConfig;
    if (!formGroup) return changeDefaultInfo(formItems, newVal);
    formGroup.forEach(item => changeDefaultInfo(item.formItems, newVal));
  }
);

watch(
  () => formData.value,
  () => {
    const { modalConfig } = props;
    const { onDataChange } = modalConfig;
    if (!onDataChange) return;
    const newData = onDataChange(unref(formData));
    Object.keys(newData).forEach(key => (formData.value[key] = newData[key]));
  },
  {
    deep: true
  }
);

function handleConfirmClick() {
  formRef.value.vaildate(isVaild => {
    //表单校验通过派发事件
    isVaild && emit("confirmBtnClick", unref(type), unref(formData));
  });
}

defineExpose({
  dialogVisible,
  confirmLoading,
  type
});
</script>

<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    center
    destroy-on-close
    :close-on-click-modal="false"
  >
    <!-- 表单 -->
    <BasicForm
      ref="formRef"
      v-if="!prviewDescription"
      v-bind="modalConfig"
      v-model:form-data="formData"
      :disabled="isPreview"
      :support="support"
    />

    <!-- 预览详情为描述列表 -->
    <Description
      v-if="prviewDescription"
      :config="modalConfig"
      :default-info="defaultInfo"
    />

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