<script setup>
import { getAssetSubList, deleteAssetSubItem } from "@/apis/asset";
import { ref, onMounted, watch } from "vue";
import useSearchParam from "@/hooks/useSearchParam";
import useActiveBtn from "@/hooks/useActiveBtn";
import AssetSubListAddModal from "./AssetSubListAddModal.vue";

const { searchParams, changeParams } = useSearchParam();
const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();

const getSubSystems = async () => {
  const res = await getAssetSubList();
  const sub = res.data.map((d, index) => ({
    ...d,
    title: d.system_key,
    key: d.id,
    active: searchParams.value?.subSys_id
      ? parseInt(searchParams.value?.subSys_id) === d.id
      : index === 0,
  }));
  setItems(sub);
};

onMounted(() => {
  getSubSystems();
});

watch(selectedBtn, (newValue) => {
  changeParams({ subSys_id: newValue.key });
});

const editRecord = ref(null);
// 編輯 modal
const openModal = () => {
  asset_add_sub_item.showModal();
};
const onCancel = () => {
  editRecord.value = null;
  asset_add_sub_item.close();
};

const edit = (item) => {
  editRecord.value = item;
  openModal();
};

const deleteItem = async (id) => {
  deleteAssetSubItem(id);
  getSubSystems();
};
</script>

<template>
  <div class="mt-4">
    <!-- <AssetSubListAddModal
      :openModal="openModal"
      :onCancel="onCancel"
      :getData="getSubList"
      :editRecord="editRecord"
    /> -->
    <ButtonConnectedGroup
      :items="items"
      :onclick="
        (e, item) => {
          changeActiveBtn(item);
        }
      "
      :className="`flex w-full mt-4`"
      size="sm"
      color="info"
    >
      <template #buttonContent="{ item }">
        <span class="text-base">{{ item.title }}</span>
        <!-- <template v-if="!item.is_IOT">
          <span
            class="ml-2 text-base text-warning"
            @click.stop.prevent="() => edit(item)"
          >
            <FontAwesomeIcon :icon="['fas', 'pencil-alt']"></FontAwesomeIcon>
          </span>
          <span
            class="text-base mx-1 text-error"
            @click.stop.prevent="() => deleteItem(item.id)"
          >
            <FontAwesomeIcon :icon="['fas', 'trash-alt']" />
          </span>
        </template> -->
      </template>
    </ButtonConnectedGroup>
  </div>
</template>

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