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

const { searchParams, changeParams } = useSearchParam();

const { openToast, cancelToastOpen } = inject("app_toast");
const subSys = ref([]);
const filterSubSys = ref([]);
const {
  items: iotTypesItems,
  changeActiveBtn: changeIotTypeActiveBtn,
  setItems: setIotTypesItems,
  selectedBtn: selectedIotType,
} = useActiveBtn();
const {
  items: subSysItems,
  changeActiveBtn: changeSubSysActiveBtn,
  setItems: setSubSysItems,
  selectedBtn: selectedSubSysBtn,
} = useActiveBtn();

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

  subSys.value = sub;
  filterSubSys.value = subSys.value.filter((item) => 
    item.is_IOT === (Number(selectedIotType.value.key) )
  );
  setSubSysItems(filterSubSys.value);
};

onMounted(() => {
  getSubSystems();
  setIotTypesItems([
    { title: "IOT設備", key: "1", active: true },
    { title: "非IOT設備", key: "0", active: false },
  ]);
});

watch(selectedSubSysBtn, (newValue) => {
  changeParams({ ...searchParams.value, 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) => {
  openToast("warning", "是否確認刪除該項目?", "body", async () => {
    await cancelToastOpen();
    const res = await deleteAssetSubItem(id);
    if (res.isSuccess) {
      getSubSystems();
      openToast("success", "刪除成功");
    } else {
      openToast("error", res.msg);
    }
  });
};

watch(
  selectedIotType,
  (newValue, oldValue) => {
    if (newValue?.key) {
      filterSubSys.value = subSys.value
        .filter((item) => 
          item.is_IOT === (Number(newValue.key) )
        )
        .map((d, index) => ({
          ...d,
          active: index === 0,
        }));

      setSubSysItems(filterSubSys.value);
    }
  },
  {
    immediate: true,
  }
);
</script>

<template>
  <div class="mt-4">
    <ButtonGroup
      :items="iotTypesItems"
      :withLine="true"
      :onclick="
        (e, item) => {
          changeIotTypeActiveBtn(item);
        }
      "
      class="my-3"
    />
    <div class="flex  flex-wrap">
      <AssetSubListAddModal
        v-if="selectedIotType?.key == '0'"
        :openModal="openModal"
        :onCancel="onCancel"
        :getData="getSubSystems"
        :editRecord="editRecord"
      />
      <ButtonConnectedGroup
        :items="subSysItems"
        :onclick="
          (e, item) => {
            changeSubSysActiveBtn(item);
          }
        "
        :className="`flex `"
        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>
  </div>
</template>

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