<script setup>
import { defineProps, onMounted, onUnmounted, ref } from "vue";
import { getAssetSingle, getAssetFloorList } from "@/apis/asset";
import { getOperationCompanyList } from "@/apis/operation";
import dayjs from "dayjs";

const tableData = ref({});
const floors = ref([]);
const companyOptions = ref([]);

const props = defineProps({
  data: Object,
});

const getFloors = async () => {
  const res = await getAssetFloorList();
  floors.value = res.data[0]?.floors.map((d) => ({ ...d, key: d.floor_guid }));
};

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

const getCurrentData = async (value) => {
  if (value.main_id) {
    const res = await getAssetSingle(value.main_id);
    if (res.isSuccess) {
      tableData.value = {
        ...res.data,
        key: res.data.id,
        floor: floors.value.find(
          ({ floor_guid }) => res.data.floor_guid === floor_guid
        )?.full_name,
        company: companyOptions.value.find(
          ({ id }) => res.data.operation_id === id
        )?.name,
        contact_person: companyOptions.value.find(
          ({ id }) => res.data.operation_id === id
        )?.contact_person,
        buying_date: res.data?.buying_date
          ? dayjs(res.data.buying_date).format("YYYY-MM-DD")
          : "",
        created_at: res.data?.created_at
          ? dayjs(res.data.created_at).format("YYYY-MM-DD")
          : "",
      };
    }
  }
};

onMounted(async () => {
  console.log("Initial data:", props.data.value);
  await getFloors();
  await getCompany();
  getCurrentData(props.data.value); 
});

onUnmounted(() => {
  tableData.value = {};
});
</script>

<template>
  <table class="table">
    <tbody>
      <tr>
        <td>設備編號</td>
        <td>{{ tableData.device_number }}</td>
      </tr>
      <tr>
        <td>設備名稱</td>
        <td>{{ tableData.full_name }}</td>
      </tr>
      <tr>
        <td>資產編號</td>
        <td>{{ tableData.asset_number }}</td>
      </tr>
      <tr>
        <td>設備位置</td>
        <td>{{ tableData.floor }}</td>
      </tr>
      <tr>
        <td>圖面標識</td>
        <td>{{ tableData.device_coordinate }}</td>
      </tr>
      <tr>
        <td>品牌 / 型號</td>
        <td>{{ tableData.brand }} / {{ tableData.device_model }}</td>
      </tr>
      <tr>
        <td>廠商 / 聯絡人</td>
        <td>
          {{ tableData.company }} /
          {{ tableData.contact_person }}
        </td>
      </tr>
      <tr>
        <td>購買日期</td>
        <td>{{ tableData.buying_date }}</td>
      </tr>
      <tr>
        <td>建立時間</td>
        <td>{{ tableData.created_at }}</td>
      </tr>
    </tbody>
  </table>
</template>

<style lang="scss" scoped>
td {
  border: 1px solid #ddd
}

td:first-child {
  font-weight: bold; 
}
</style>
