<style scoped>
  @keyframes fade-in {
    from {
      opacity: 0;
      transform: scale(0.95);
    }
    to {
      opacity: 1;
      transform: scale(1);
    }
  }
  .animate-fade-in {
    animation: fade-in 0.2s ease-out;
  }
</style>
<template>
  <div
    v-if="show"
    class="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center"
  >
    <div
      class="bg-white rounded-xl shadow-xl w-full max-w-md animate-fade-in"
    >
      <div class=" bg-slate-600 rounded-t-xl text-white">
        <div class="text-2xl font-semibold p-4 text-center">
          快速生成檢核表
        </div>
      </div>


      <div class="space-y-4 p-6">
        <div class="flex flex-row text-nowrap items-center gap-2 mx-2">
          <label class="block text-base font-bold text-gray-700"
            >設備類別</label
          >
          <select
            v-model="form.eq_cat_id"
            class="text-sm w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400"
          >
            <option disabled value="">請選擇</option>
            <option v-for="cat in categories" :key="cat.id" :value="cat.id">
              {{ cat.name }}
            </option>
          </select>
        </div>
        <div v-if="DetailWarnings" class="text-right text-red-500 text-xs">
          {{ message }}
        </div>
        <table class="text-sm w-full border border-gray-300 table-fixed">
          <thead>
              <tr class="bg-gray-100 text-center">
                <th class="py-2 w-12">
                <input
                 type="checkbox"
                 v-model="selectAll"
                 @change="toggleSelectAll"
                 class=" w-4 h-4"
                />
                </th>
                <th class="py-2 text-left w-[calc(100%-4rem)]">設備名稱</th>
              </tr>
          </thead>
          <tbody>
            <tr v-if="eq.length === 0">
              <td class="py-2 text-center text-gray-500" colspan="2">
                無設備資料
              </td>
            </tr>
            <tr v-for="eqs in eq" :key="eqs.id" class="border-t">
              <td class="text-center">
                <input type="checkbox" :value="eqs.id" v-model="form.name" class="w-4 h-4" />
              </td>
              <td class="py-2 truncate"> {{ eqs.name }}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="flex justify-center gap-2 p-4 border-t-4 shadow font-semibold">
        <button
          @click="emit('update:show', false)"
          class="w-20 h-10 px-4 py-2 text-base bg-red-600 hover:bg-red-500 text-white rounded"
        >
          取消
        </button>
        <button
          @click="save"
          class="w-20 h-10 px-4 py-2 text-base bg-blue-800 hover:bg-blue-700 text-white rounded"
        >
          儲存
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, reactive, onMounted } from 'vue'
import { api } from "@/global/axios";
import { useSwal } from '@/global/swal'

const props = defineProps({
  show: Boolean,
  bank: Object
})
const emit = defineEmits(['update:show', 'saved'])

const categories = ref([])
const selectAll = ref(false)
const form = reactive({
  eq_cat_id: '',
  name: [],
})
const eq = ref([])

const toggleSelectAll = () => {
  if (selectAll.value) {
    form.name = eq.value.map(item => item.id)
  } else {
    form.name = []
  }
}


watch(() => props.bank, (val) => {
  if (val) Object.assign(form, val)
  else Object.assign(form, { eq_cat_id: '', name: [] })
})

// 設備類別
const DetailWarnings = ref(false)
const message = ref('')
watch(() => form.eq_cat_id, async(eq_cat_id) => {
  form.name = []
  if(eq_cat_id){
    try{
      const res = await api.get(`/api/eqipment/getEquipment?categoryId=${eq_cat_id}`)
      const data = res.data.data
      // 檢查資料是否錯誤，並給予相對應訊息
      if(!data.length){
        DetailWarnings.value = true
        message.value = '※ 此設備類別尚未建置設備，請建置後再試。'
        eq.value = []
      }else if (data[0].category.banks.length === 0) {
        DetailWarnings.value = true
        message.value = '※ 該設備類別尚未建置檢核項目，請於設備->檢查項目確認後再試。'
        eq.value = []
      } else {
        DetailWarnings.value = false
        message.value = ''
        eq.value = data
      }
    }catch (e){
      console.error('設備載入失敗', e);
      eq.value = []
    }
  }else{
    eq.value = [],
    form.name = [],
    DetailWarnings.value = false
  }
})

onMounted(async () => {
  try {
    const res = await api.get('/api/equipment-categories')
    categories.value = res.data.data
  } catch (e) {
    console.error('載入設備類別失敗', e)
  }
})

const save = async () => {
  if (!form.eq_cat_id) {
    await useSwal.error('請選擇「設備類別」', '資料未填寫完整')
    return
  }
  if (!form.name || form.name.length === 0){
    await useSwal.error('請確認已勾選「設備名稱」','資料未填寫完整')
    return
  }
  try {
    await api.post('/api/bank-list', form)
    await useSwal.success('設備新增成功')

    emit('saved')
    emit('update:show', false)
  } catch (e) {
    await useSwal.error('請稍後再試，或聯絡管理員', '儲存失敗')
  }
}
</script>
