<script setup>
import { ref, onMounted, watch, computed, inject } from "vue";
import {
  getAssetMainList,
  getAssetSubList,
  getIOTSchema,
  getDeviceItem,
  deleteDeviceItem,
} from "@/apis/asset";
import useActiveBtn from "@/hooks/useActiveBtn";
import MQTTListAddModal from "./MQTTListAddModal.vue";
import PointListAddModal from "./PointListAddModal.vue";
import { useI18n } from "vue-i18n";
import useBuildingStore from "@/stores/useBuildingStore";
const store = useBuildingStore();
const { t } = useI18n();
const { openToast, cancelToastOpen } = inject("app_toast");
const MQTTDataSource = ref([]);
const MQTTloading = ref(false);
const PointsDataSource = ref([]);
const Pointsloading = ref(false);
const variable_id = ref(null);
const editRecord = ref(null);
// 系統類別
const {
  items: mainSysItems,
  changeActiveBtn: changeMainSysActiveBtn,
  setItems: setMainSysItems,
  selectedBtn: selectedMainSysItems,
} = useActiveBtn();
// 設備類別
const {
  items: subSysItems,
  changeActiveBtn: changeSubSysActiveBtn,
  setItems: setSubSysItems,
  selectedBtn: selectedSubSysItems,
} = useActiveBtn();

const getMainSystems = async () => {
  const res = await getAssetMainList(store.selectedBuilding.building_guid);
  const cate = res.data.map((d, index) => ({
    ...d,
    title: d.system_key,
    key: d.id,
    active: index === 0,
  }));
  setMainSysItems(cate);
};

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

const MQTTColumns = computed(() => [
  {
    title: t("setting.schema"),
    key: "schema_name",
  },
  {
    title: t("setting.point"),
    key: "pointOrg",
    filter: true,
  },
  {
    title: t("setting.description"),
    key: "description",
  },
]);

const PointsColumns = computed(() => [
  {
    title: t("setting.IoT_point_name"),
    key: "full_name",
  },
  {
    title: t("setting.IoT_point_code"),
    key: "points",
  },
  {
    title: t("setting.number_of_decimal_places"),
    key: "decimals",
  },
  {
    title: t("setting.boolean_value"),
    key: "is_bool",
  },
  {
    title: t("setting.hide_point"),
    key: "is_link",
  },
  {
    title: t("setting.hide_switch"),
    key: "show_event_switch_btn",
  },
  {
    title: t("assetManagement.operation"),
    key: "operation",
  },
]);

const getDataSource = async (id) => {
  MQTTloading.value = true;
  const res = await getIOTSchema(id);
  MQTTDataSource.value = res.data.flatMap((d) =>
    d.details.map((detail) => ({
      key: `${d.id}-${detail.pointOrg}`,
      schema_name: d.name,
      pointOrg: detail.pointOrg,
      description: detail.describe,
    }))
  );
  MQTTloading.value = false;
};

const getPointsData = async (id) => {
  Pointsloading.value = true;
  const res = await getDeviceItem(id);
  PointsDataSource.value = res.data.map((d) => ({
    ...d,
    key: d.id,
  }));
  Pointsloading.value = false;
};

const remove = async (id) => {
  openToast("warning", t("msg.sure_to_delete"), "body", async () => {
    await cancelToastOpen();
    const res = await deleteDeviceItem(id);
    if (res.isSuccess) {
      getPointsData(variable_id.value);
      openToast("success", t("msg.delete_success"));
    } else {
      openToast("error", res.msg);
    }
  });
};

const openModal = (record) => {
  if (record?.id) {
    editRecord.value = record;
  } else {
    editRecord.value = {
      id: 0,
      variable_id: variable_id.value,
      full_name: "",
      points: "",
      decimals: 0,
      is_bool: 0,
      is_link: 0,
    };
  }
  point_list_item.showModal();
};

watch(
  selectedMainSysItems,
  (newValue) => {
    if (newValue && newValue.key) {
      getSubSystems(parseInt(newValue.key));
    }
  },
  {
    deep: true,
  }
);

watch(
  selectedSubSysItems,
  (newValue) => {
    if (newValue && newValue.key) {
      getDataSource(parseInt(newValue.key));
      getPointsData(parseInt(newValue.key));
      variable_id.value = parseInt(newValue.key);
    }
  },
  {
    deep: true,
  }
);

watch(
  () => store.selectedBuilding,
  (newBuilding) => {
    if (newBuilding) {
      getMainSystems();
    }
  },
  { immediate: true }
);
</script>

<template>
  <div class="">
    <div class="flex items-center gap-4 mb-4">
      <h2 class="text-lg font-bold whitespace-nowrap">
        {{ $t("history.system_category") }} :
      </h2>
      <ButtonGroup
        :items="mainSysItems"
        :withLine="true"
        :onclick="
          (e, item) => {
            changeMainSysActiveBtn(item);
          }
        "
      />
    </div>
    <div class="flex items-center gap-4 mb-4">
      <h2 class="text-lg font-bold whitespace-nowrap">
        {{ $t("history.device_category") }} :
      </h2>
      <ButtonGroup
        :items="subSysItems"
        :withLine="true"
        :onclick="
          (e, item) => {
            changeSubSysActiveBtn(item);
          }
        "
      />
    </div>
    <div class="flex justify-start items-center mt-5 mb-2">
      <h3 class="text-xl mr-5">{{ $t("setting.MQTT_parse") }} :</h3>
      <MQTTListAddModal
        :getData="getDataSource"
        :pointsData="PointsDataSource"
        :variable_id="variable_id"
      />
    </div>
    <Table
      :columns="MQTTColumns"
      :dataSource="MQTTDataSource"
      :loading="MQTTloading"
    >
    </Table>
    <div class="flex justify-start items-center mt-5 mb-2">
      <h3 class="text-xl mr-5">{{ $t("setting.point") }} :</h3>
      <PointListAddModal
        :getData="getPointsData"
        :variable_id="variable_id"
        :editRecord="editRecord"
        :openModal="openModal"
      />
    </div>
    <Table
      :columns="PointsColumns"
      :dataSource="PointsDataSource"
      :loading="Pointsloading"
      ><template #bodyCell="{ record, column, index }">
        <template v-if="column.key === 'is_bool'">
          {{ record.is_bool === 1 ? t("alert.yes") : t("alert.no") }}
        </template>
        <template v-else-if="column.key === 'is_link'">
          {{ record.is_link === 1 ? t("alert.yes") : t("alert.no") }}
        </template>
        <template v-else-if="column.key === 'show_event_switch_btn'">
          {{ record.show_event_switch_btn === true ? t("alert.yes") : t("alert.no") }}
        </template>
        <template v-else-if="column.key === 'operation'">
          <button
            class="btn btn-sm btn-success text-white mr-2"
            @click.stop.prevent="() => openModal(record)"
          >
            {{ $t("button.edit") }}
          </button>
          <button
            class="btn btn-sm btn-error text-white"
            @click.stop.prevent="() => remove(record.id)"
          >
            {{ $t("button.delete") }}
          </button>
        </template>
      </template>
    </Table>
  </div>
</template>

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