<script setup>
import AlertSearch from "./AlertSearch.vue";
import AlertTable from "./AlertTable.vue";
import AlertTableModal from "./AlertTableModal.vue";
import { ref, provide, onMounted, watch } 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";

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) => {
    const formattedKey = d.device_number
      .replace(/-/g, '_')  
      .split('_')          
      .slice(0, 8)
      .join('_'); 

    return { ...d, key: formattedKey };
  });
};

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 () => {
  if (Object.keys(searchParams.value).length !== 0) {
    tableLoading.value = true;
    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);
  }
};

watch(
  () => ({
    isAck: searchParams.value.isAck,
    isRecover: searchParams.value.isRecover,
    Start_date: searchParams.value.start_created_at,
    End_date: searchParams.value.end_created_at,
    system_tag: searchParams.value.system_tag,
  }),
  (val) => {
    // 判斷所有必要欄位都已經有值
    if (
      val.isAck !== undefined &&
      val.isRecover !== undefined &&
      val.Start_date &&
      val.End_date &&
      val.system_tag
    ) {
      search();
    }
  },
  { immediate: true, deep: true }
);

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>
