<script setup>
import { getAssetIOTList } from "@/apis/asset";
import { ref, computed, inject, watch, onMounted } from "vue";
import ButtonGroup from "@/components/customUI/ButtonGroup.vue";
import useActiveBtn from "@/hooks/useActiveBtn";
import useBuildingStore from "@/stores/useBuildingStore";
import { getAssetSubPoint } from "@/apis/asset";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { formState } = inject("asset_table_modal_form");
const tableColumns = computed(() => [
  {
    title: t("assetManagement.index"),
    key: "index",
  },
  {
    title: "tag",
    key: "device_name",
  },
  {
    title: t("assetManagement.point"),
    key: "point_name",
  },
  {
    title: t("assetManagement.operation"),
    key: "operation",
    width: 100,
  },
]);
// 選小類
const store = useBuildingStore();
const {
  items: sysTagItems,
  changeActiveBtn: changeSysActiveBtn,
  setItems: setSysItems,
  selectedBtn: selectedSysItems,
} = useActiveBtn();
const modalColumns = computed(() => [
  {
    title: t("assetManagement.choose"),
    key: "check",
    width: 100,
  },
  {
    title: "tag",
    key: "device_name",
  },
  {
    title: t("assetManagement.point"),
    key: "point_name",
  },
]);

// 設定點位
const {
  items: points,
  changeActiveBtn: changeActivePoint,
  setItems: setPoints,
  selectedBtn: selectedPoints,
} = useActiveBtn();

const getPoint = async (sub_system_tag) => {
  const res = await getAssetSubPoint(sub_system_tag);
  setPoints(
    res.data.map((d, index) => ({
      ...d,
      title: d.points,
      key: d.points,
      active: false,
    }))
  );
};

// TODO: 抓取ＩＯＴ
const iotData = ref([]);
const iotCheckedList = ref([]); // 初始選中的項目
const currentCheckedList = ref([]); // 當前勾選的項目

const getIOTData = async (sub_system_tag = null, points = null) => {
  const res = await getAssetIOTList(sub_system_tag, points);
  let data = res.data.map((d) => ({
    ...d,
    title: d.full_name,
    key: d.device_number + d.points,
    checked: formState.value.sub_device?.some(
      ({ device_number, points }) =>
        device_number + points === `${d.device_number}${d.points}`
    ),
  }));
  iotData.value = data;
  if (!sub_system_tag && !points) {
    iotCheckedList.value = data.filter(({ checked }) => checked);
    currentCheckedList.value = [...iotCheckedList.value];
  }
};

const onChange = (value, checked) => {
  const d = iotData.value.find(
    ({ device_number, points }) => `${device_number}${points}` === value
  );
  let newList = [];
  if (checked) {
    newList = [...currentCheckedList.value, d];
  } else {
    newList = currentCheckedList.value.filter(
      (item) => item.device_number + item.points !== value
    );
  }
  currentCheckedList.value = newList;
  return newList;
};

const openModal = () => {
  asset_add_IoT_item.showModal();
};

const onOk = () => {
  iotCheckedList.value = currentCheckedList.value;
  formState.value.sub_device = currentCheckedList.value.map(
    ({ device_number, points }) => ({
      device_number,
      points,
    })
  );
  onCancel();
};

const onCancel = () => {
  asset_add_IoT_item.close();
};

watch(
  [selectedSysItems, selectedPoints],
  ([newSys, newPoint]) => {
    if (newSys || newPoint) {
      getIOTData(newSys?.key, newPoint?.key);
    }
  },
  {
    deep: true,
  }
);
watch(selectedSysItems, (newVal) => {
  if (newVal) {
    getPoint(newVal.key);
  }
});
watch(
  formState,
  () => {
    getIOTData();
    setSysItems(
      store.subSys.map(({ full_name, sub_system_tag }, index) => ({
        title: full_name,
        key: sub_system_tag,
        active: 0,
      }))
    );
  },
  {
    deep: true,
  }
);

const deleteItem = (value) => {
  const itemToDelete = iotCheckedList.value.find(
    ({ device_number, points }) => `${device_number}${points}` === value
  );

  if (itemToDelete) {
    iotCheckedList.value = iotCheckedList.value.filter(
      (item) => item.device_number + item.points !== value
    );
    currentCheckedList.value = iotCheckedList.value;

    formState.value.sub_device = iotCheckedList.value.map(
      ({ device_number, points }) => ({
        device_number,
        points,
      })
    );
  }
};
</script>

<template>
  <!-- IoT -->
  <div class="flex flex-col mt-8 col-span-2">
    <div class="flex justify-between items-center">
      <span class="label-text-alt text-lg">
        {{ $t("assetManagement.equipment_point") }}
      </span>
      <button
        type="button"
        class="btn btn-sm btn-add"
        @click.stop.prevent="openModal"
      >
      <font-awesome-icon :icon="['fas', 'plus']" />
        {{ $t("assetManagement.add_sensor") }}
      </button>
    </div>
    <Table
      :columns="tableColumns"
      :dataSource="iotCheckedList"
      :withStyle="false"
    >
      <template #bodyCell="{ record, column, index }">
        <template v-if="column.key === 'index'">{{ index + 1 }}</template
        ><template v-if="column.key === 'operation'">
          <span
            class="text-base text-error cursor-pointer"
            @click.stop.prevent="
              () => deleteItem(record.device_number + record.points)
            "
          >
            <FontAwesomeIcon
              :icon="['fas', 'trash-alt']"
              class="text-xl"
            /> </span></template
      ></template>
    </Table>
  </div>
  <Modal
    id="asset_add_IoT_item"
    :title="t('assetManagement.associated_device')"
    :onCancel="onCancel"
    width="900"
  >
    <template #modalContent>
      <ButtonGroup
        :items="sysTagItems"
        :withLine="true"
        :onclick="
          (e, item) => {
            changeSysActiveBtn(item);
          }
        "
        class="my-3"
      />
      <ButtonGroup
        v-if="selectedSysItems"
        :items="points"
        :withLine="true"
        :onclick="
          (e, item) => {
            changeActivePoint(item);
          }
        "
        class="my-3"
      />
      <Table :columns="modalColumns" :dataSource="iotData" :withStyle="false">
        <template #bodyCell="{ record, column, index }">
          <template v-if="column.key === 'check'">
            <Checkbox
              name="device_number"
              :value="record.device_number + record.points"
              :onChange="onChange"
              :checked="
                currentCheckedList?.some(
                  ({ device_number, points }) =>
                    `${device_number}${points}` ===
                    `${record.device_number}${record.points}`
                )
              "
            ></Checkbox>
          </template>
        </template>
      </Table>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="onCancel"
      >
        {{ $t("button.cancel") }}
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.prevent="onOk"
      >
        {{ $t("button.submit") }}
      </button>
    </template></Modal
  >
</template>

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