<script setup>
import { ref, provide, onMounted, watch, computed } from "vue";
import AssetMainList from "./components/AssetMainList.vue";
import AssetSubList from "./components/AssetSubList.vue";
import AssetTable from "./components/AssetTable.vue";
import { getOperationCompanyList } from "@/apis/operation";
import { getIOTSchema, getElecTypeList } from "@/apis/asset";
import useSearchParam from "@/hooks/useSearchParam";
import useBuildingStore from "@/stores/useBuildingStore";
const storeBuild = useBuildingStore();
const { searchParams, changeParams } = useSearchParam();
const companyOptions = ref([]);
const iotSchemaOptions = ref([]);
const elecTypeOptions = ref([]);
const iotSchemaTag = ref(""); // 儲存 IOT Schema 的 tagIoT
const getCompany = async () => {
  const res = await getOperationCompanyList();
  companyOptions.value = res.data.map((d) => ({ ...d, key: d.id }));
};
const getIOTSchemaOptions = async (id) => {
  const res = await getIOTSchema(Number(id));
  const data = res.data || [];

  iotSchemaOptions.value = data.map((d) => ({ ...d, key: d.id }));

  // 取出第一筆的 tagIoT，提供給最深層元件使用
  if (data.length > 0 && data[0].tagIoT) {
    iotSchemaTag.value = data[0].tagIoT;
  } else {
    iotSchemaTag.value = "";
  }
};
const getElecType = async () => {
  const res = await getElecTypeList();
  elecTypeOptions.value = res.data.map((d) => ({ ...d, key: d.id }));
};

const departmentList = computed(() => storeBuild.deptList);
const floors = computed(() => storeBuild.floorList);

onMounted(() => {
  getCompany();
  getElecType();
});

watch(
  () => searchParams.value.subSys_id,
  (newValue) => {
    if (newValue) {
      getIOTSchemaOptions(newValue);
    }
  },
  {
    immediate: true,
  }
);

provide("asset_modal_options", {
  companyOptions,
  iotSchemaOptions,
  elecTypeOptions,
  departmentList,
  floors,
  iotSchemaTag
});
</script>

<template>
  <h1 class="text-2xl font-extrabold mb-2">
    {{ $t("assetManagement.title") }}
  </h1>
  <AssetMainList />
  <AssetSubList />
  <AssetTable />
</template>

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