<script setup>
import { inject, defineProps, watch, ref, onMounted } from "vue";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import useActiveBtn from "@/hooks/useActiveBtn";
import {
  getAssetBuildList,
  postAssetBuild,
  deleteAssetBuild,
  getAssetFloorList,
  postAssetFloor,
  deleteAssetFloor,
} from "@/apis/asset";
import * as yup from "yup";
const {
  items: typeItems,
  changeActiveBtn: changeTypeActiveBtn,
  setItems: setTypeItems,
  selectedBtn: selectedTypeBtn,
} = useActiveBtn();
const {
  items: functionItems,
  changeActiveBtn: changeFunctionActiveBtn,
  setItems: setFunctionItems,
  selectedBtn: selectedFunctionBtn,
} = useActiveBtn();

const { openToast, cancelToastOpen } = inject("app_toast");
const props = defineProps({
  openModal: Function,
  onCancel: Function,
  buildData: Object,
  fetchBuildData: Function,
});

const form = ref(null);
const formState = ref([
  {
    building_guid: null,
    full_name: "",
  },
  {
    building_guid: null,
    floor_guid: null,
    full_name: "",
    floorFile: [],
  },
]);

let buildScheme = yup.object({
  full_name: yup.string().required("必填"),
});
let floorScheme = yup.object({
  building_guid: yup.string().required("必填"),
  full_name: yup.string().required("必填"),
  floorFile: yup.array(),
});
const {
  formErrorMsg: buildFormErrorMsg,
  handleSubmit: handleBuildSubmit,
  handleErrorReset: handleBuildErrorReset,
} = useFormErrorMessage(buildScheme);
const {
  formErrorMsg: floorFormErrorMsg,
  handleSubmit: handleFloorSubmit,
  handleErrorReset: handleFloorErrorReset,
} = useFormErrorMessage(floorScheme);

const floors = ref([]);
const getFloors = async (building_guid) => {
  const res = await getAssetFloorList(building_guid);
  floors.value = res.data[0]?.floors.map((d) => ({ ...d, key: d.floor_guid }));
};

watch(
  () => formState.value[1].building_guid,
  (newValue) => {
    if (newValue) {
      const building = props.buildData.find(
        ({ building_guid }) => building_guid === newValue
      );
      if (building?.building_guid) {
        getFloors(building.building_guid);
      }
    } else {
      floors.value = [];
    }
  }
);
watch(
  () => formState.value[1].floor_guid,
  (newValue) => {
    if (newValue) {
      const floor = floors.value.find(
        ({ floor_guid }) => floor_guid === newValue
      );
      formState.value[1] = {
        ...formState.value[1],
        full_name: floor.full_name,
        floorFile: floor.floor_map_name
          ? [
              {
                name: floor.floor_map_name,
                src: `${floor.floor_map_url}.svg`,
                ext: "svg",
              },
            ]
          : [],
      };
    } 
  }
);



const saveBuild = async () => {
  const value = await handleBuildSubmit(buildScheme, formState.value[0]);
  console.log("value", value);
  const res = await postAssetBuild(value);
  if (res.isSuccess) {
    props.fetchBuildData();
    closeModal();
  } else {
    openToast("error", res.msg, "#asset_add_floor");
  }
};

const saveFloor = async () => {
  const value = await handleFloorSubmit(floorScheme, formState.value[1]);
  const formData = new FormData(form.value);
  formData.append(
    "floor_guid",
    formState.value[1].floor_guid ? formState.value[1].floor_guid : ""
  );
  formData.append("initMapName", formState.value[1].floorFile[0].name);
  formData.append("mapFile", formState.value[1].floorFile[0]);
  formData.delete("floorFile");

  const res = await postAssetFloor(formData);
  if (res.isSuccess) {
    props.fetchBuildData();
    closeModal();
  } else {
    openToast("error", res.msg, "#asset_add_floor");
  }
};

const deleteBuildorFloor = async () => {
  openToast("warning", "是否確認刪除該項目?", "#asset_add_floor", async () => {
    await cancelToastOpen();
    const id =
      selectedTypeBtn.value?.key == "building"
        ? formState.value[0].building_guid
        : formState.value[1].floor_guid;
    const deleteApi =
      selectedTypeBtn.value?.key == "building"
        ? deleteAssetBuild
        : deleteAssetFloor;
    const res = await deleteApi(id);
    if (res.isSuccess) {
      props.fetchBuildData();
      openToast("success", "刪除成功");
      closeModal();
    } else {
      openToast("error", res.msg);
    }
  });
};

const onOk = async () => {
  if (selectedFunctionBtn.value?.key == "Delete") {
    deleteBuildorFloor();
  } else {
    if (selectedTypeBtn.value?.key == "building") {
      saveBuild();
    } else {
      saveFloor();
    }
  }
};

const closeModal = () => {
  formState.value = [
    {
      building_guid: null,
      full_name: "",
    },
    {
      building_guid: null,
      floor_guid: null,
      full_name: "",
      floorFile: [],
    },
  ];
  handleBuildErrorReset();
  handleFloorErrorReset();
  props.onCancel();
};

const updateFileList = (files) => {
  formState.value[1].floorFile = files;
};

onMounted(() => {
  setTypeItems([
    {
      title: "棟別",
      key: "building",
      active: true,
    },
    {
      title: "樓層",
      key: "floor",
      active: false,
    },
  ]);
  setFunctionItems([
    {
      title: "新增",
      key: "Add",
      active: true,
    },
    {
      title: "修改",
      key: "Edit",
      active: false,
    },
    {
      title: "刪除",
      key: "Delete",
      active: false,
    },
  ]);
});
</script>

<template>
  <Modal
    id="asset_add_floor"
    title="棟別-樓層"
    :open="open"
    :onCancel="closeModal"
    width="400"
  >
    <template #modalContent>
      <form ref="form">
        <ButtonGroup
          :items="typeItems"
          :withLine="true"
          class="my-3"
          :onclick="(e, item) => changeTypeActiveBtn(item)"
        />

        <ButtonGroup
          :items="functionItems"
          :withLine="true"
          class=""
          :onclick="(e, item) => changeFunctionActiveBtn(item)"
        />
        <hr class="mt-8 mb-6 border-info" />

        <Select
          v-if="
            (selectedTypeBtn?.key == 'building' &&
              selectedFunctionBtn?.key != 'Add') ||
            selectedTypeBtn?.key == 'floor'
          "
          :value="
            selectedTypeBtn?.key == 'building' ? formState[0] : formState[1]
          "
          selectClass="border-info focus-within:border-info"
          name="building_guid"
          Attribute="full_name"
          :options="props.buildData"
          :isBottomLabelExist="false"
        >
          <template #topLeft>棟別</template>
        </Select>
        <Select
          v-if="
            selectedTypeBtn?.key == 'floor' && selectedFunctionBtn?.key != 'Add'
          "
          :value="formState[1]"
          selectClass="border-info focus-within:border-info"
          name="floor_guid"
          Attribute="full_name"
          :options="floors"
          :isBottomLabelExist="false"
        >
          <template #topLeft>樓層</template>
        </Select>

        <Input
          v-if="
            selectedTypeBtn?.key == 'building' &&
            selectedFunctionBtn?.key != 'Delete'
          "
          :value="formState[0]"
          width="270"
          name="full_name"
        >
          <template #topLeft>棟別名稱</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ buildFormErrorMsg.full_name }}
            </span></template
          ></Input
        >
        <Input
          v-if="
            selectedTypeBtn?.key == 'floor' &&
            selectedFunctionBtn?.key != 'Delete'
          "
          :value="formState[1]"
          width="270"
          name="full_name"
        >
          <template #topLeft>樓層名稱</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ floorFormErrorMsg.full_name }}
            </span></template
          ></Input
        >

        <Upload
          v-if="
            selectedTypeBtn?.key == 'floor' &&
            selectedFunctionBtn?.key != 'Delete'
          "
          name="floorFile"
          :fileList="formState[1].floorFile"
          :getFileList="updateFileList"
          :multiple="false"
          class="col-span-2"
        >
          <template #topLeft>上傳樓層平面圖</template>
        </Upload>
      </form>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="closeModal"
      >
        取消
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.prevent="onOk"
      >
        確定
      </button>
    </template>
  </Modal>
</template>

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