<script setup>
import AlertSearch from "./AlertSearch.vue";
import AlertTable from "./AlertTable.vue";
import AlertTableModal from "./AlertTableModal.vue";
import { ref, provide, onMounted } from "vue";
import useSearchParam from "@/hooks/useSearchParam";
import useAlarmData from "@/hooks/baja/useAlarmData";
import { getAlertFormId } from "@/apis/alert";
import {
  getOperationDeviceList,
  getOperationCompanyList,
  getOperationEditRecord,
} from "@/apis/operation";
import { getAccountUserList } from "@/apis/account";
import useBuildingStore from "@/stores/useBuildingStore";
import useAlarmStore from "@/stores/useAlarmStore";
const storeAlarm = useAlarmStore();

const { searchParams } = useSearchParam();
const { getAlarmByBaja, alarmData } = useAlarmData();
const store = useBuildingStore();

const tableLoading = ref(false);
const dataSource = ref([]);
const model_data = ref({
  model_userList: [],
  model_devList: [],
  model_companyList: [],
});

const editRecord = ref(null);

const updateEditRecord = (data) => {
  if (data?.lorf) {
    editRecord.value = {
      ...data,
      lorf: data?.lorf?.map((file) => ({
        ...file,
        src: `${file.save_file_name}.${file.ori_file_name.split(".")[1]}`,
        name: file.ori_file_name,
        ext: file.ori_file_name.split(".")[1],
      })),
    };
  } else {
    editRecord.value = {
      ...data,
      lorf: [],
    };
  }
};

const getFormId = async (uuid) => {
  const res = await getAlertFormId(uuid);
  return res.data;
};

const getModalDevList = async () => {
  const sub_system_tags = searchParams.value.system_tag.map(
    (tag) => tag.split("_")[1]
  );
  const res = await getOperationDeviceList({
    list_sub_system_tag: sub_system_tags,
    device_building_tag: store.buildings[0].building_tag,
    device_area_tag: "NTPC",
  });
  return res.data.map((d) => ({ ...d, key: d.device_number }));
};

const getModalUserList = async () => {
  const res = await getAccountUserList({});
  return res.data.map((d) => ({ ...d, key: d.userinfo_guid }));
};

const getModalCompanyList = async () => {
  const res = await getOperationCompanyList();
  return res.data.map((d) => ({ ...d, key: d.id }));
};

const getAllOptions = async () => {
  Promise.all([
    getModalDevList(),
    getModalUserList(),
    getModalCompanyList(),
  ]).then(([devices, users, companies]) => {
    model_data.value.model_userList = users;
    model_data.value.model_devList = devices;
    model_data.value.model_companyList = companies;
  });
};

const updateDataSource = (data) => {
  dataSource.value = data.map((d) => ({ ...d, key: d.uuid }));
};

const search = async () => {
  tableLoading.value = true;
  if (Object.keys(searchParams.value).length !== 0) {
    storeAlarm.getAlarmDataFromBaja();
    updateDataSource(storeAlarm.alarmData);
    tableLoading.value = false;
    /*
    await getAlarmByBaja(
      searchParams.value.start_created_at,
      searchParams.value.end_created_at,
      searchParams.value.isRecover,
      searchParams.value.isAck,
      searchParams.value.system_tag,
      async (result) => {
        alarmData.value = result.data;
        // 確保所有 alarm 都包含 formId
        alarmData.value = alarmData.value.map((alarm) => ({
          ...alarm,
          formId: null, // 初始設置 formId 為 null
        }));

        const uuids = alarmData.value.map((alarm) => ({ uuid: alarm.uuid }));
        const formIds = await getFormId(uuids);

        if (Array.isArray(formIds)) {
          formIds.forEach((form) => {
            if (form && form.uuid) {
              const index = alarmData.value.findIndex(
                (alarm) => alarm.uuid === form.uuid
              );
              if (index !== -1) {
                alarmData.value[index].formId = form.formId || null;
              }
            }
          });
        }

        updateDataSource(alarmData.value);
        tableLoading.value = false;
      }
    );
    */
  }
};

const openModal = async (record) => {
  try {
    if (record.formId) {
      const res = await getOperationEditRecord(record.formId);
      updateEditRecord({ ...res.data, uuid: record.uuid });
    } else {
      updateEditRecord(record);
    }
    await getAllOptions();
    alert_action_item.showModal();
  } catch (error) {
    console.error("Error opening modal:", error);
  }
};

onMounted(() => {
  if (Object.keys(searchParams.value).length !== 0) {
    search();
  }
});

provide("alert_modal", { model_data, search, updateEditRecord });
provide("alert_table", {
  openModal,
  updateEditRecord,
  dataSource,
  search,
  tableLoading,
});
</script>

<template>
  <AlertTableModal :editRecord="editRecord" />
  <div>
    <AlertSearch />
    <AlertTable />
  </div>
</template>

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