<script setup>
import { ref, inject, defineProps, watch, onMounted, computed } from "vue";
import {
  addGraphTableDataWithoutSubSys,
  editGraphTableDataWithoutSubSys,
} from "@/apis/graph";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import * as yup from "yup";

const BASEURL = import.meta.env.VITE_FILE_API_BASEURL;

const props = defineProps({
  updateEditRecord: Function,
  editRecord: Object,
  getTableData: Function,
  openModal: Function,
});

let scheme = yup.object({
  name: yup.string().required("必填"),
  url: yup.string().nullable(true),
});

const { openToast } = inject("app_toast");
const { current_dir } = inject("current_dir");



const onCancel = () => {
  graph_add_item.close();
  handleErrorReset();
  props.updateEditRecord({
    id: null,
    name: "",
    url: "",
    fileList: [],
  });
};

// Form
const form = ref(null);
const formState = ref({
  id: null,
  name: "",
  url: "",
  fileList: [],
});
const { formErrorMsg, handleSubmit, handleErrorReset } =
  useFormErrorMessage(scheme);

const updateFileList = (files) => {
  formState.value.fileList = files;
};

const onOk = async () => {
  const values = await handleSubmit(scheme, formState.value);
  if (!values) return; // 若表單驗證失敗，則不繼續執行

  const formData = new FormData(form.value);
  formData.append("layer_id", current_dir.value.id);
  formData.append("name", formState.value.name);
  formData.append("url", formState.value.url || null);
  formData.delete("oriFile");

  formState.value.fileList.forEach((file) => {
    if (file.id) {
      formData.append("oriFile", null);
      formData.append("oriSavName", file.oriSavName);
    } else {
      formData.append("oriFile", file);
    }
    formData.append("oriOrgName", file?.name);
  });

  let res;
  if (props.editRecord.id) {
    formData.append("id", props.editRecord.id);
    res = await editGraphTableDataWithoutSubSys(formData);
  } else {
    res = await addGraphTableDataWithoutSubSys(formData);
  }
  if (res.isSuccess) {
    onCancel();
    await props.getTableData(current_dir.value.id);
  } else {
    openToast("error", res.data, "#graph_add_item");
  }

};

watch(
  () => props.editRecord,
  (newVal) => {
    if (newVal) {
      formState.value = {
        ...newVal,
        fileList: newVal.oriOrgName
          ? [
              {
                ...newVal,
                size: newVal.oriSize,
                name: newVal.oriOrgName,
                src: newVal.oriSavName,
                ext: newVal.oriOrgName?.split(".")[1],
              },
            ]
          : [],
      };
    }
  }
);
</script>

<template>
  <button class="btn btn-success mr-3" @click.stop.prevent="props.openModal">
    <font-awesome-icon :icon="['fas', 'plus']" />新增
  </button>
  <Modal id="graph_add_item" title="圖資上傳" :onCancel="onCancel" width="600">
    <template #modalContent>
      <form ref="form" class="mt-5">
        <div class="mb-2">
          <p>圖資類別</p>
          <p class="text-lg">{{ current_dir?.remark }}</p>
        </div>
        <Input :value="formState" class="my-2" name="name">
          <template #topLeft>名稱</template>
          <template #bottomLeft>
            <span class="text-error text-base">
              {{ formErrorMsg.name }}
            </span>
          </template>
        </Input>
        <Input :value="formState" class="my-2" name="url">
          <template #topLeft>網址</template>
        </Input>
        <Upload
          name="oriFile"
          :fileList="formState?.fileList"
          :getFileList="updateFileList"
          :multiple="false"
          :baseUrl="`${BASEURL}/upload/graph_manage`"
        >
          <template #topLeft>上傳檔案</template>
        </Upload>
      </form>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="onCancel"
      >
        取消
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.prevent="onOk"
      >
        確定
      </button>
    </template>
  </Modal>
</template>

<style lang="scss" scoped></style>
