<script setup>
import { ref, defineProps, onMounted, watch } from "vue";
import * as yup from "yup";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import useSearchParam from "@/hooks/useSearchParam";
import { getAssetMainList, postAssetSubList } from "@/apis/asset";
import { useI18n } from "vue-i18n";
import useBuildingStore from "@/stores/useBuildingStore";
const store = useBuildingStore();
const { t } = useI18n();
const { searchParams, changeParams } = useSearchParam();
const props = defineProps({
  openModal: Function,
  getData: Function,
  formState: Object,
});
const form = ref(null);
const mainSystem = ref([]);

const updateFileList = (files) => {
  console.log("file", files);
  props.formState.file = files;
  props.formState.device_image = files[0]?.name;
};

const getMainSystems = async () => {
  const res = await getAssetMainList(store.selectedBuilding.building_guid);
  mainSystem.value = res.data.map((d) => ({ ...d, key: d.id }));
};

let subSysSchema = yup.object({
  system_key: yup.string().required(t("button.required")), // 名稱
  system_value: yup.string().required(t("button.required")), // 代稱
  system_parent_id: yup.number().required(t("button.required")), // 大類id
  file: yup.array(),
});

const { formErrorMsg, handleSubmit, handleErrorReset } =
  useFormErrorMessage(subSysSchema);

const onCancel = () => {
  props.formState = {
    id: 0,
    system_key: "",
    system_value: "",
    system_parent_id: 0,
    file: [],
    device_image: "",
  };
  asset_add_sub_item.close();
  updateFileList([]);
  handleErrorReset();
};

watch(
  () => store.selectedBuilding,
  (newBuilding) => {
    if (newBuilding) {
      getMainSystems();
    }
  },
  { immediate: true }
);

const onOk = async () => {
  // 編輯
  const value = await handleSubmit(subSysSchema, props.formState);
  console.log("props.formState", props.formState);

  const formData = new FormData(form.value);
  formData.delete("file");
  formData.append("id", props.formState.id);

  if (props.formState.file[0]) {
    formData.append("file", props.formState.file[0]);
    formData.append("device_image", props.formState.device_image);
  }

  const res = await postAssetSubList(formData);
  if (res.isSuccess) {
    props.getData(parseInt(searchParams.value.mainSys_id));
    store.getSubMonitorPage(store.selectedBuilding.building_guid);
    onCancel();
  }
};
</script>

<template>
  <button class="btn btn-sm btn-success" @click.stop.prevent="openModal">
    <font-awesome-icon :icon="['fas', 'plus']" />{{ $t("button.add") }}
  </button>
  <Modal
    id="asset_add_sub_item"
    :title="
      props.formState?.id
        ? t('assetManagement.edit_device_category')
        : t('assetManagement.add_device_category')
    "
    :open="open"
    :onCancel="onCancel"
    width="400"
  >
    <template #modalContent>
      <form ref="form" class="mt-5 flex flex-col items-center">
        <Input name="system_key" :value="formState">
          <template #topLeft>{{ $t("assetManagement.system_name") }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.system_key }}
            </span></template
          >
        </Input>
        <Input
          name="system_value"
          :value="formState"
          :readonly="props.formState?.id"
        >
          <template #topLeft>{{ $t("assetManagement.system_value") }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.system_value }}
            </span></template
          >
        </Input>
        <Select
          :options="mainSystem"
          Attribute="system_key"
          class=""
          name="system_parent_id"
          :value="formState"
          selectClass="border-info  focus-within:border-info"
          :disabled="props.formState?.id"
        >
          <template #topLeft>{{
            $t("assetManagement.system_parent")
          }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.system_parent_id }}
            </span></template
          >
        </Select>
        <Upload
          name="file"
          :fileList="formState.file || []"
          :getFileList="updateFileList"
          :multiple="false"
        >
          <template #topLeft>{{ $t("operation.upload_file") }}</template>
        </Upload>
      </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>
