<script setup>
import { getAssetList, getAssetSingle, deleteAssetItem } from "@/apis/asset";
import { onMounted, ref, watch, inject } 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";

const { openToast, cancelToastOpen } = 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 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 () => {
  const res = await getAssetList(searchParams.value?.subSys_id);
  if (res.isSuccess) {
    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 = [
  {
    title: "設備編號",
    key: "device_number",
  },
  {
    title: "設備名稱",
    key: "full_name",
    filter: true,
  },
  {
    title: "資產編號",
    key: "asset_number",
  },
  {
    title: "設備位置",
    key: "floor",
    filter: true,
    sort: true,
  },
  {
    title: "圖面標識",
    key: "device_coordinate",
  },
  {
    title: "品牌 / 型號",
    key: "brandAndModal",
  },
  {
    title: "廠商 / 聯絡人",
    key: "companyAndContact",
  },
  {
    title: "建置時間",
    key: "buying_date",
    sort: true,
  },
  {
    title: "檔案上傳",
    key: "oriFile",
  },
  {
    title: "建立時間",
    key: "created_at",
    sort: true,
  },
  {
    title: "功能",
    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_guid }) => device_guid
    );
    editRecord.value = res.data;
    openModal();
  } else {
    openToast("error", res.msg);
  }
};

const remove = async (id) => {
  openToast("warning", "是否確認刪除該項目?", "body", async () => {
    await cancelToastOpen();
    const res = await deleteAssetItem(id);
    if (res.isSuccess) {
      getAssetData();
      openToast("success", "刪除成功");
    } else {
      openToast("error", res.msg);
    }
  });
};
</script>

<template>
  <div class="flex justify-start items-center mt-10">
    <h3 class="text-xl mr-5">設備列表</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 flex-wrap gap-1">
            <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)"
        >
          修改
        </button>
        <button
          class="btn btn-sm btn-error text-white"
          @click.stop.prevent="() => remove(record.main_id)"
        >
          刪除
        </button>
      </template>
      <template v-else>
        {{ record[column.key] }}
      </template>
    </template>
  </Table>
</template>

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