<script setup>
import Modal from "@/components/customUI/Modal.vue";
import Upload from "@/components/customUI/Upload.vue";
import { ref, inject, defineProps, watch, onMounted, computed } from "vue";
import {
  getGraphAddParamOption,
  addGraphTableData,
  addGraphTableDataWithoutSubSys,
  editGraphTableDataWithoutSubSys,
} from "@/apis/graph";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const BASEURL = import.meta.env.VITE_FILE_API_BASEURL;

const props = defineProps({
  updateEditRecord: Function,
  editRecord: Object,
  getTableData: Function,
});
const { openToast } = inject("app_toast");
const { current_dir } = inject("current_dir");

const options = ref([]);

const getOption = async () => {
  const res = await getGraphAddParamOption();
  options.value = res.data.map((d, index) => ({
    ...d,
    key: d.sub_system_tag,
    selected: index === 0,
  }));
};

const onSubSysClick = (option) => {
  options.value = options.value.map((d) => ({
    ...d,
    selected: d.key === option,
  }));
};

const specOptions = computed(() => {
  // console.log("onSubSysClick", options.value);
  return options.value.find(({ selected }) => selected)?.spec || [];
});

// onMounted(() => {
//   getOption();
// });

const openModal = () => {
  graph_add_item.showModal();
};

const onCancel = () => {
  graph_add_item.close();
  props.updateEditRecord(null);
  resetForm();
};

// Form
const form = ref(null);
const fileList = ref([]);
const updateFileList = (files) => {
  fileList.value = files;
};

const resetForm = () => {
  // onSubSysClick(options.value[0].key);
  updateFileList([]);
};

const onOk = async (e) => {
  const formData = new FormData(form.value);
  formData.append("layer_id", current_dir.value.id);
  console.log(fileList);
  formData.delete("oriFile");
  fileList.value.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) {
    formData.append("id", props.editRecord.id);
    res = await editGraphTableDataWithoutSubSys(formData);
  } else {
    // const res = await addGraphTableData(formData);
    res = await addGraphTableDataWithoutSubSys(formData);
  }

  if (!res.isSuccess) {
    openToast("error", res.msg, "#graph_add_item");
  }

  await props.getTableData(current_dir.value.id);
  onCancel();
};

watch(
  () => props.editRecord,
  (newVal) => {
    console.log(newVal);
    if (newVal) {
      // onSubSysClick(newVal.sub_system_tag);
      updateFileList([
        {
          ...newVal,
          size: newVal.oriSize,
          name: newVal.oriOrgName,
          src: newVal.oriSavName,
          ext: newVal.oriOrgName?.split(".")[1],
        },
      ]);
      openModal();
    }
  }
);
</script>

<template>
  <button class="btn btn-add mr-3" @click.stop.prevent="openModal">
    <font-awesome-icon :icon="['fas', 'plus']" />{{ $t("button.add") }}
  </button>
  <Modal id="graph_add_item" :title="t('graphManagement.upload')" :onCancel="onCancel" :width="800">
    <template #modalContent>
      <form ref="form" class="mt-5">
        <div class="mb-2">
          <p>{{ $t("graphManagement.category") }}</p>
          <p class="text-lg">{{ current_dir?.remark }}</p>
        </div>
        <!-- <div class="mt-5 flex">
          <Select
            :options="options"
            Attribute="full_name"
            class="mr-5"
            name="sub_system_tag"
            :onChange="onSubSysClick"
          >
            <template #topLeft>設備</template>
          </Select>
          <Select :options="specOptions" name="spec">
            <template #topLeft name="type">規格</template>
          </Select>
        </div> -->
        <Upload
          name="oriFile"
          :fileList="fileList"
          :getFileList="updateFileList"
          :multiple="false"
          :baseUrl="`${BASEURL}/upload/graph_manage`"
        />
      </form>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="onCancel"
      >
        {{ $t("button.cancel") }}
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.prevent="onOk"
      >
        {{ $t("button.submit") }}
      </button>
    </template>
  </Modal>
</template>

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