<template>
  <!-- <div class="flex">
    <router-link :to="`/Dispatch/Index`" class="flex">返回</router-link>
  </div> -->
  <!-- <div class="flex items-center justify-start w-full ">
    <span class="ml-2 text-3xl font-bold text-black dark:text-white">
      派工設定
    </span>
  </div> -->
  <h2 class="flex items-center text-xl sm:text-3xl px-3 pb-2 font-semibold text-black dark:text-white border-b-4 border-zinc-200">
    <div class="text-sm mr-2">:::</div>
    新增每日巡檢
  </h2>

  
  <div class="sm:p-4 md:p-6 mt-4 sm:mt-0">
    <!-- 表格容器 -->
    <div class="flex flex-col gap-3 font-semibold">
        <div
            class="flex flex-col sm:flex-row border border-gray-300 rounded shadow-md"
            v-for="(item, index) in dailyDetails"
            :key="index"
        >
            <!-- 左側資訊欄 -->
            <div class="flex flex-col w-full sm:w-2/4 p-4 gap-2">

                <!-- 備註欄  -->
                <div class="flex items-start space-x-2">
                    <span class="font-semibold w-20 text-right pt-1">事由</span>
                    <textarea v-model="item.remark" 
                    class="text-sm w-full border rounded-md px-1 py-1 focus:outline-none focus:ring-2 h-28 resize-none"
                    ></textarea>
                </div>
            </div>

            <!-- 右側圖片區 -->
            <div class="flex flex-row w-full sm:w-2/4 p-3 gap-6 items-center justify-center">
                <div v-for="(photo, index) in photos" :key="index" class="relative w-32 h-32">
                    <template v-if="photo && (isFileInstance(photo) || photo.file_path)">
                        <img :src="getPhotoSrc(photo)" @click="openPreview(photo)" 
                        class="w-24 h-24 md:w-full md:h-full object-cover rounded border " />
                        <button
                            class="absolute top-0 right-0 bg-black bg-opacity-50 text-white rounded-bl px-1"
                            @click.stop="removePhoto(photo,index)"
                        >✕
                        </button>
                    </template>
                    <template v-else>
                      <button
                        @click="handleUpload(photo, index)"
                        :disabled="isPhotoDisabled(photo,index)"
                        :class="[
                        'w-24 h-24 md:w-full md:h-full border rounded flex items-center justify-center',
                        isPhotoDisabled(photo,index)
                        ? 'bg-gray-100 text-gray-400 border-gray-300 cursor-not-allowed'
                        : 'bg-gray-200 text-gray-500 border-gray-400'
                        ]"
                       
                      >
                        <CameraIcon class="h-14 w-14 text-black dark:text-white" />
                      </button>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- 儲存檢核表、返回-->    
    <div class="flex flex-col sm:flex-row sm:justify-between my-6 font-semibold gap-2">
      <!-- 返回按鈕靠左 -->
      <div class="flex-1 flex justify-end">
        <button class="flex mx-0  px-2 py-2 bg-red-600 text-white w-full rounded sm:w-auto sm:mx-2 ">
        <router-link :to="`/Daily/Index`" class="flex w-full justify-center">
            <ArrowUturnLeftIcon class="w-6 h-6 mr-1"/>取消
          </router-link>
        </button>
      </div>
      <!-- 儲存按鈕置中 -->
      <!-- <div class="flex-1 flex justify-center" v-if="listData.state !== 0">
        <button
          class="flex px-2 py-2 bg-green-500 text-white rounded w-full sm:w-auto"
          @click="save"
          :disabled="ishandle"
        >
          <DocumentCheckIcon class="w-6 h-6 mr-1"/>儲存檢核表
        </button>
      </div> -->
      <!-- 提交按鈕靠右 -->
      <div class="flex-1 flex justify-start">
        <button
          class="flex px-2 py-2 bg-emerald-500 text-white rounded w-full sm:w-auto justify-center"
          @click="save"
        >
          <DocumentCheckIcon class="w-6 h-6 mr-1"/>儲存
        </button>
      </div>
    </div>
  </div>
  
    <!-- 預覽圖片 Modal -->
    <div
    v-if="isPreviewOpen"
    class="fixed inset-0 z-50 bg-black bg-opacity-70 flex items-center justify-center"
    @click.self="closePreview"
    >
        <div class="relative max-w-full max-h-full">
            <img :src="previewPhoto" class="max-w-[90vw] max-h-[90vh] 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>

</template>

<script setup>
import { ref, onMounted, computed, reactive, watch } from 'vue'
import { DocumentCheckIcon , ArrowUturnLeftIcon , CameraIcon} from '@heroicons/vue/24/solid'
import { useSwal } from '@/global/swal'
import { useRouter } from 'vue-router'
import { api } from "@/global/axios";
import CustomTable from '@/components/CustomTable.vue';

const router = useRouter()

// 巡檢單題目
const dailyDetails = ref([
  {remark: '' }
])

const ishandle = ref(false)
const save = async () => {
  if (ishandle.value) return
  ishandle.value = true

  try {
    const formData = new FormData()

    // 加入文字資料（需要序列化 JSON）
    formData.append('details', JSON.stringify(dailyDetails.value))

    // 加入圖片資料
    photos.value.forEach((photo, index) => {
      if (photo instanceof File) {
        formData.append(`photos_${index}`, photo)
      }
    })

    await api.post('/api/daily', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    await useSwal.success('儲存成功')
    router.push('/Daily/Index')
  } catch (error) {
    console.error(error)
    await useSwal.error('儲存失敗')
  } finally {
    ishandle.value = false
  }
}



const photos = ref([
  null ,null ,null
])

function handleUpload(photo, index) {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    input.onchange = (event) => {
        const file = event.target.files[0]
        if (file) {
        // 直接把 File 放進 photos 陣列
          photos.value[index] = file
        }
    }
    input.click()
}

function isFileInstance(obj) {
  return typeof File !== 'undefined' && obj instanceof File
}

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;
}

const removePhoto = async (photo, index) => {
    let deleteFlag = true
    if(photo instanceof File){
        deleteFlag = false
    }

    if (confirm('確認刪除？')) {
        // if(deleteFlag){
        //     await api.post(`/api/check-bank-detail/${item.id}/${photo.id}`)
        // }
        photos.value[index] = null
        await useSwal.success('刪除成功')
    }
}

const isPhotoDisabled = (photo, index) => {
    const currentPhotos = photos.value
    if (index === 1 && !currentPhotos[0]) return true
    if (index === 2 && (!currentPhotos[0] || !currentPhotos[1])) return true
    return false
}

</script>
