<script setup>
import Collapse from "@/components/customUI/Collapse.vue";
import Checkbox from "@/components/customUI/Checkbox.vue";
import { computed, ref, watch } from "vue";
import useBuildingStore from "@/stores/useBuildingStore";
import useSearchParam from "@/hooks/useSearchParam";
import { getHistorySideBar } from "@/apis/history";

const { searchParams, changeParams } = useSearchParam();

// const store = useBuildingStore();
const selectedBuilding = ref([]);
const deviceData = ref([]); // 原始設備資料
const searchTerm = ref(""); // 搜尋文字
const activeSearchTerm = ref(""); // 啟用的搜尋文字

// 取得設備資料
const getDeviceData = async (sub_tag) => {
  const res = await getHistorySideBar(sub_tag);
  deviceData.value = res.data.map((d) => ({
    ...d,
    key: d.building_tag,
  }));
  selectedBuilding.value = res.data.map((d) => d.building_tag);
  changeSelected([res.data[0]?.device_list[0]?.device_number]);
};

// 過濾設備資料
const filteredDeviceData = computed(() => {
  if (!activeSearchTerm.value.trim()) return deviceData.value;

  return deviceData.value
    .map((building) => ({
      ...building,
      device_list: building.device_list.filter((device) =>
        device.device_name.includes(activeSearchTerm.value)
      ),
    }))
    .filter((building) => building.device_list.length > 0);
});

// 當輸入框變動時更新文字
const handleInput = (e) => {
  searchTerm.value = e.target.value;
};

// 當按下 Enter 鍵時，啟用搜尋
const handleSearch = (e) => {
  e.preventDefault();
  activeSearchTerm.value = searchTerm.value;
};

const sysIsExisted = (building_tag) => {
  return selectedBuilding.value.includes(building_tag);
};

const toggleSelectedBuilding = (building_tag) => {
  const isExisted = sysIsExisted(building_tag);
  if (isExisted) {
    selectedBuilding.value = deviceData.value.filter(
      (selected) => building_tag !== selected
    );
  } else {
    selectedBuilding.value = [...selectedBuilding.value, building_tag];
  }
};

watch(
  searchParams,
  (newVal, oldVal) => {
    if (
      newVal.sub_system_tag &&
      newVal.sub_system_tag != oldVal?.sub_system_tag
    ) {
      getDeviceData(newVal.sub_system_tag);
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

// 取得 checked 設備列表
const selectedDeviceNumber = computed(() => {
  return typeof searchParams.value.Device_list === "string"
    ? [searchParams.value.Device_list]
    : searchParams.value.Device_list || [];
});

const isChecked = (device, checked) => {
  if (checked) {
    changeSelected([...selectedDeviceNumber.value, device]);
  } else {
    changeSelected(
      selectedDeviceNumber.value.filter(
        (device_number) => device_number !== device
      )
    );
  }
};

const checkedBuilding = computed(() => {
  let selected = [];
  deviceData.value.forEach(({ building_tag, device_list }) => {
    if (
      selectedDeviceNumber.value?.filter(
        (d) => d.split("_")[1] === building_tag
      ).length === device_list.length
    ) {
      selected.push(building_tag);
    }
  });
  return selected;
});
const buildingCheck = (building_tag) => {
  if (checkedBuilding.value?.includes(building_tag)) {
    changeSelected(
      selectedDeviceNumber.value.filter(
        (device_number) => device_number.split("_")[1] !== building_tag
      )
    );
  } else {
    changeSelected([
      ...new Set(
        [
          ...selectedDeviceNumber.value,
          ...deviceData.value
            .find((d) => d.building_tag === building_tag)
            ?.device_list.map(({ device_number }) => device_number),
        ].filter((d) => d !== "")
      ),
    ]);
  }
};

const changeSelected = (Device_list) => {
  changeParams({
    ...searchParams.value,
    Device_list,
  });
};
</script>

<template>
  <div class="custom-border p-4">
    <label
      class="input input-bordered bg-transparent rounded-sm flex items-center px-2 border-info focus-within:border-info"
    >
      <font-awesome-icon
        :icon="['fas', 'search']"
        class="w-6 h-6 mr-2 text-info"
      />
      <input
        type="text"
        placeholder="輸入文字後按下 Enter"
        class="text-white bg-transparent w-full"
        @input="handleInput"
        @keyup.enter="handleSearch"
      />
    </label>
    <template v-for="d in filteredDeviceData" :key="d.building_tag">
      <Collapse
        :open="selectedBuilding.includes(d.building_tag)"
        :data="
          d.device_list?.map((device) => ({
            ...device,
            key: device.device_number,
          }))
        "
        :toggle="() => toggleSelectedBuilding(d.building_tag)"
      >
        <!--  :checked="selectedDeviceNumber.includes(data.device_number)" -->
        <template #collapseTitle>
          <Checkbox
            :title="d.building_name"
            :checked="checkedBuilding.includes(d.building_tag)"
            :onClick="
              () => {
                buildingCheck(d.building_tag);
              }
            "
          />
        </template>
        <template #collapseContent="{ data }">
          <span class="flex items-center text-xl">
            <Checkbox
              :title="data.device_name"
              :checked="selectedDeviceNumber.includes(data.device_number)"
              :onClick="
                () => {
                  isChecked(
                    data.device_number,
                    !selectedDeviceNumber.includes(data.device_number)
                  );
                }
              "
            />
          </span>
        </template>
      </Collapse>
    </template>
  </div>
</template>

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