<script setup>
import { getAssetList, getAssetSingle, deleteAssetItem } from "@/apis/asset";
import { onMounted, ref, watch, inject, provide, computed } from "vue";
import useSearchParam from "@/hooks/useSearchParam";
import AssetTableAddModal from "./AssetTableAddModal.vue";
import { getOperationCompanyList } from "@/apis/operation";
import { getAssetFloorList } from "@/apis/asset";
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { openToast } = inject("app_toast");

const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;
const { searchParams, changeParams } = useSearchParam();

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

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

const tableData = ref([]);
const getAssetData = async () => {
  totalCoordinates.value = {}; // 在獲取新數據之前清空 totalCoordinates
  const res = await getAssetList(searchParams.value?.subSys_id);
  if (res.isSuccess) {
    // 將 device_coordinate 推入對應樓層的座標陣列
    res.data.forEach(d => {
      const floorGuid = d.floor_guid;
      if (!totalCoordinates.value[floorGuid]) {
        totalCoordinates.value[floorGuid] = [];
      }
      totalCoordinates.value[floorGuid].push(d.device_coordinate);
    });

    tableData.value = res.data.map((d) => ({
      ...d,
      key: d.id,
      floor: floors.value.find(({ floor_guid }) => d.floor_guid === floor_guid)
        ?.full_name,
      company: companyOptions.value.find(({ id }) => d.operation_id === id),
      buying_date: d?.buying_date
        ? dayjs(d?.buying_date).format("YYYY-MM-DD")
        : "",
      created_at: d?.created_at
        ? dayjs(d?.created_at).format("YYYY-MM-DD")
        : "",
    }));
  }
};

onMounted(async () => {
  await getCompany();
  await getFloors();
  getAssetData();
});

const columns = computed(() => [
  {
    title: t("assetManagement.device_number"),
    key: "device_number",
    class: "break-all",
  },
  {
    title: t("assetManagement.device_name"),
    key: "full_name",
    filter: true,
    class: "break-all",
  },
  {
    title: t("assetManagement.asset_number"),
    key: "asset_number",
  },
  {
    title: t("assetManagement.floor"),
    key: "floor",
    filter: true,
    sort: true,
  },
  {
    title: t("assetManagement.device_coordinate"),
    key: "device_coordinate",
  },
  {
    title: t("assetManagement.brand_and_modal"),
    key: "brandAndModal",
  },
  {
    title: t("assetManagement.company_and_contact"),
    key: "companyAndContact",
  },
  {
    title: t("assetManagement.buying_date"),
    key: "buying_date",
    sort: true,
  },
  // {
  //   title: t("assetManagement.oriFile"),
  //   key: "oriFile",
  // },
  {
    title: t("assetManagement.created_at"),
    key: "created_at",
    sort: true,
  },
  {
    title: t("assetManagement.operation"),
    key: "operation",
    width: 200,
  },
]);

watch(
  () => searchParams,
  (newValue) => {
    if (newValue.value?.subSys_id) {
      getAssetData();
    }
  },
  {
    deep: true,
  }
);

// modal
const editRecord = ref(null);
const openModal = () => {
  asset_add_table_item.showModal();
};

const onCancel = () => {
  editRecord.value = null;
  asset_add_table_item.close();
};
const edit = async (id) => {
  // changeParams({ ...searchParams.value, main_id: record.id });
  const res = await getAssetSingle(id);
  if (res.isSuccess) {
    res.data.oriFile = res.data.oriFile.map((file, index) => ({
      ...file,
      key: index,
      src: file.file_url,
      name: file.orgName,
      ext: file.saveName.split(".")[file.saveName.split(".").length - 1],
    }));
    res.data.sub_device = res.data.sub_device?.map(
      ({ device_number, points }) => ({
        device_number,
        points,
      })
    );
    editRecord.value = res.data;
    openModal();
  } else {
    openToast("error", res.msg);
  }
};

const remove = async (id) => {
  const res = await deleteAssetItem(id);
  if (res.isSuccess) {
    getAssetData();
  }
};

provide("asset_table_data", {
  totalCoordinates,
});
</script>

<template>
  <div class="flex justify-start items-center mt-10">
    <h3 class="text-xl mr-5">{{ $t("assetManagement.device_list") }}</h3>
    <AssetTableAddModal
      :openModal="openModal"
      :onCancel="onCancel"
      :editRecord="editRecord"
      :getData="getAssetData"
    />
  </div>
  <Table :columns="columns" :dataSource="tableData" class="mt-3">
    <template #bodyCell="{ record, column, index }">
      <template v-if="column.key === 'companyAndContact'">
        {{ record.company?.name }} /
        {{ record.company?.contact_person }}
      </template>
      <template v-else-if="column.key === 'brandAndModal'">
        {{ record.brand }} / {{ record.device_model }}
      </template>
      <template v-else-if="column.key === 'oriFile'">
        <span v-if="record.oriFile.length === 0"></span>
        <template v-else>
          <span class="flex">
            <a
              v-for="file in record.oriFile"
              :href="`${FILE_BASEURL}/${file?.file_url}`"
              target="_blank"
              class="mx-1"
            >
              <img
                v-if="
                  file.saveName
                    .split('.')
                    [file.saveName.split('.').length - 1]?.match(
                      /png|jpg|jpeg|gif|bmp|svg/g
                    )
                "
                :src="`${FILE_BASEURL}/${file?.file_url}`"
                class="w-14 h-14"
              />
              <font-awesome-icon
                v-else
                class="mx-auto mb-2 text-4xl text-white"
                :icon="['fas', 'file-word']"
              />
            </a>
          </span>
        </template>
      </template>
      <template v-else-if="column.key === 'operation'">
        <button
          class="btn btn-sm btn-success text-white mr-2"
          @click.stop.prevent="() => edit(record.main_id)"
        >
          {{ $t("button.edit") }}
        </button>
        <button
          class="btn btn-sm btn-error text-white"
          @click.stop.prevent="() => remove(record.main_id)"
        >
          {{ $t("button.delete") }}
        </button>
      </template>
      <template v-else>
        {{ record[column.key] }}
      </template>
    </template>
  </Table>
</template>

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