<script setup>
import OperationSearch from "./components/OperationSearch.vue";
import OperationTable from "./components/OperationTable.vue";
import OperationTableModal from "./components/OperationTableModal.vue";
import { ref, provide } from "vue";
import {
  getOperationDeviceList,
  getOperationFormId,
  getOperationCompanyList,
  getOperationRecord,
} from "@/apis/operation";
import { getAccountUserList } from "@/apis/account";
import useBuildingStore from "@/stores/useBuildingStore";
import dayjs from "dayjs";

import useSearchParam from "@/hooks/useSearchParam";
const { searchParams } = useSearchParam();
const store = useBuildingStore();

const dataSource = ref([]);
const updateDataSource = (data) => {
  dataSource.value = (data || []).map((d) => ({
    ...d,
    key: d.id,
    start_time: d?.start_time ? dayjs(d?.start_time).format("YYYY-MM-DD") : "",
    finish_time: d?.finish_time
      ? dayjs(d?.finish_time).format("YYYY-MM-DD")
      : "",
    updated_at: d?.updated_at
      ? dayjs(d?.updated_at).format("YYYY-MM-DD")
      : "",
  }));
};

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

// TODO: 等確定可否移除layer subsystem 跟 mainsystem 後再進行編輯api作業
const editRecord = ref(null);
const updateEditRecord = (data) => {
  console.log("operation", data);
  if (data) {
    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;
  }
};
const getModalDevList = async () => {
  const res = await getOperationDeviceList({
    list_sub_system_tag: searchParams.value.sub_system_tag,
    device_building_tag: store.buildings[0].building_tag,
    device_area_tag: "NTPC",
  });
  return res.data.map((d) => ({ ...d, key: d.main_id }));
};
const getNewFormId = async (id = "") => {
  if (!id) {
    const res = await getOperationFormId();
    updateEditRecord({
      id: "",
      formId: res.data,
      lorf: [],
      start_time: dayjs(),
      status: 0,
    });
  }
};
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,
  }));
};

// TODO: 建立一個 promise.all 等待所有資料回傳在結束loading
const getAllOptions = async (id = "") => {
  Promise.all([
    getNewFormId(id),
    getModalDevList(),
    getModalUserList(),
    getModalCompanyList(),
  ]).then(([formId, devices, users, companies]) => {
    model_data.value.model_userList = users;
    model_data.value.model_devList = devices;
    model_data.value.model_companyList = companies;
  });
};

const openModal = async (id = "") => {
  console.log("open modal", id);
  if(searchParams.value?.work_type < 3){
    getAllOptions(id);
  }
  operation_action_item.showModal();
};

const tableLoading = ref(false);
const search = async () => {
  tableLoading.value = true;
  let res;
  if (searchParams.value?.work_type < 3) {
    res = await getOperationRecord(searchParams.value);
  } else {
    res = await getOperationCompanyList();
  }
  updateDataSource(res.data);
  tableLoading.value = false;
};

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

<template>
  <h1 class="text-2xl font-extrabold mb-2">運維管理</h1>
  <OperationTableModal :editRecord="editRecord" />
  <div>
    <OperationSearch />
    <OperationTable />
  </div>
</template>

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