<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 { getAlertLog } from "@/apis/alert";
import {
  getOperationCompanyList,
  getOperationEditRecord,
} from "@/apis/operation";
import { getAccountUserList } from "@/apis/account";
import useBuildingStore from "@/stores/useBuildingStore";

const { searchParams } = useSearchParam();
const store = useBuildingStore();

const tableLoading = ref(false);
const dataSource = ref([]);
const model_data = ref({
  model_userList: [],
  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 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([getModalUserList(), getModalCompanyList()]).then(
    ([users, companies]) => {
      model_data.value.model_userList = users;
      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) {
    const res = await getAlertLog({
      ...searchParams.value,
      isRecovery: Number(searchParams.value.isRecovery),
    });
    dataSource.value = (res.data || []).map((d) => ({ ...d, key: d.id }));
    tableLoading.value = false;
  }
};

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

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

onMounted(() => {
  getAllOptions();
});

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>
