<style>
:deep(.p-datatable .p-datatable-tbody > tr.p-highlight) {
  background-color: #e5e7eb !important;
  color: #1f2937 !important;
}
:deep(.p-datatable .p-sortable-column.p-highlight) {
  background-color: #f3f4f6 !important;
  color: #1f2937 !important;
}
</style>
<template>
  <div class=" border-gray-200 rounded ">
    <!-- 桌面版 -->
    <div class="overflow-x-auto hidden md:block  ">
      <DataTable
        :value="items"
        v-model:selection="selected"
        selectionMode="multiple"
        dataKey="id"
        stripedRows
        headerCell="bg-gray-100 text-gray-800 "
        class="min-w-full text-sm text-left  "
        :paginator="true"
        :rows="rows"
        :first="first"
        @update:first="first = $event"
        :pt="{
          paginator: {
            root: 'py-1 px-2 text-xs',
            pageButton: 'w-6 h-6 text-xs',
            currentPageButton: 'bg-blue-100 text-blue-600',
            prevPageButton: 'w-6 h-6',
            nextPageButton: 'w-6 h-6',
            rowsPerPageDropdown: 'text-xs'
          }
        }"
      >
        <Column
          v-if="selectable"
          selectionMode="multiple"
          headerClass="w-12 bg-[#ebeef3] dark:bg-[#191919] dark:text-white dark:border-gray-700"
        />

        <Column
          header="序號"
          headerClass="w-20 bg-[#ebeef3] dark:bg-[#191919] dark:text-white dark:border-gray-700 dark:hover:bg-[#222222]"
        >
          <template #body="slotProps">
            {{ first + slotProps.index + 1 }}
          </template>
        </Column>

        <Column
          headerClass="bg-[#ebeef3] dark:bg-[#191919] dark:text-white dark:border-gray-700 dark:hover:bg-[#222222]"
          v-for="col in columns"
          :key="col.field"
          :field="col.field"
          :header="col.label"
          :sortable="col.sortable ?? true"
        >
          <template #body="slotProps">
            <!-- slot 優先，否則顯示預設值 -->
            <slot :name="`column-${col.field}`" :data="slotProps.data">
              {{ resolveField(slotProps.data, col.field) }}
            </slot>
          </template>
        </Column>

        <Column
          header="操作"
          v-if="$slots.action"
          headerClass=" bg-[#ebeef3] text-center dark:bg-[#191919] dark:text-white dark:border-gray-700"
          bodyClass="text-center space-x-2"
          :pt="{ columnHeaderContent: 'flex justify-center' }"
        >
          <template #body="slotProps">
            <slot name="action" :data="slotProps.data" />
          </template>
        </Column>

      </DataTable>
    </div>

    <!-- 手機版 -->
    <div class="block md:hidden divide-y divide-gray-200">
      <div
        v-for="(item, index) in pagedItems"
        :key="item.id"
        class="bg-white rounded shadow m-2 p-4 text-sm"
      >
        <div class="flex justify-between items-center py-1 border-b pb-1 mb-2">
          <span class="font-semibold">選取：</span>
          <Checkbox :inputId="'mobile-checkbox-' + item.id" :value="item" v-model="selected" :binary="false" />
        </div>

        <div class="flex justify-between py-1">
          <span class="font-semibold">#：</span>
          <span>{{ first + index + 1 }}</span>
        </div>

        <div v-for="col in columns" :key="col.field" class="flex justify-between py-1">
          <span class="font-semibold">{{ col.label }}：</span>

          <!-- 每日巡檢 圖片 -->
          <div v-if="col.field === 'photos'" class="flex gap-2 flex-wrap">
            <img 
              v-for="(photo, index) in item.photos"
              :key="index"
              :src="getPhotoSrc(photo)"
              class="w-10 h-10 object-cover rounded shadow border"
              @click="openPreview(photo)"
            />
          </div>
          <!-- 派工range -->
          <span v-else-if="col.field === 'rangeDisplay'">
            {{
              item.range && item.range2 ? `${item.range} ~ ${item.range2}` :
              item.range ? `> ${item.range}` :
              item.range2 ? `< ${item.range2}` :
              ''
            }}
          </span>
          <span v-else>{{ getField(item, col.field) }}</span>
        </div>

        <div class="flex justify-between items-center pt-2 border-t mt-2" v-if="$slots.action">
          <span class="font-semibold">操作：</span>
          <div class="space-x-2">
            <slot name="action" :data="item" />
          </div>
        </div>
      </div>

      <!-- 分頁器 -->
      <div class="py-4 px-2">
        <Paginator
          :rows="rows"
          :totalRecords="items.length"
          :first="first"
          @update:first="first = $event"
          class="justify-center"
          template="PrevPageLink PageLinks NextPageLink"
        />
      </div>

      <!-- 預覽圖片 Modal -->
      <div v-if="isPreviewOpen" class="fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50" >
        <div class="relative">
          <img :src="previewPhoto" class="max-w-[90vw] max-h-[80vh] rounded shadow-lg" />
              <button
              class="absolute top-0 right-0 m-2 text-white bg-black bg-opacity-50 rounded px-3 py-1 text-xl"
              @click="closePreview"
              >✕</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Checkbox from 'primevue/checkbox'
import Paginator from 'primevue/paginator'

const props = defineProps({
  items: { type: Array, required: true },
  columns: { type: Array, required: true },
  rows: { type: Number, default: 10 },
  selectable: { type: Boolean, default: true },
})

const selected = defineModel('selection', { type: Array, default: [] })
const first = ref(0)

const pagedItems = computed(() =>
  props.items.slice(first.value, first.value + props.rows)
)

const getField = (item, field) => {
  return field.split('.').reduce((val, key) => val?.[key], item) ?? ''
}

function resolveField(obj, fieldPath) {
  return fieldPath.split('.').reduce((acc, key) => acc?.[key], obj)
}

const ASSET_URL = import.meta.env.VITE_ASSET_URL
function getPhotoSrc(photo) {
    if (photo instanceof File) {
        return URL.createObjectURL(photo)
    }

    if (photo?.file_path) {
        return  ASSET_URL + photo.file_path; 
    }
}


const previewPhoto = ref(null) // 預覽圖片的 URL
const isPreviewOpen = ref(false)

function openPreview(photo) {
    const src = getPhotoSrc(photo);
    if (src) {
        previewPhoto.value = src;
        isPreviewOpen.value = true;
    }
}

function closePreview() {
    if (previewPhoto.value && previewPhoto.value.startsWith('blob:')) {
        URL.revokeObjectURL(previewPhoto.value);
    }
    isPreviewOpen.value = false;
    previewPhoto.value = null;
}

</script>

