<template>
  <!-- 標題 -->
  <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 sm:flex-row sm:justify-end sm:items-center mb-5 gap-3 sm:gap-0">
      <div class="flex flex-col sm:flex-row gap-3 w-full sm:w-auto justify-between">
        <div class="relative w-full sm:w-64">
        <MagnifyingGlassIcon class="absolute left-2 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400"/>
        <input
          v-model="keyword"
          type="text"
          placeholder="搜尋"
          class="border rounded px-3 py-2 text-sm w-full sm:w-64 pl-8"
        />
        </div>
      <!-- <select v-model="selectedState" class="border rounded px-3 py-2 text-sm">
        <option value="">全部狀態</option>
        <option value="0">已查核</option>
        <option value="1">待查核</option>
        <option value="2">查核中</option>
      </select> -->
      </div>
    </div>

    <!-- 表格容器 -->
    <CustomTable
      :items="filteredList"
      :columns="[
        { label: '設備名稱', field: 'equipment.name' },
        { label: '法定名稱', field: 'equipment.category.name' },
        { label: '廠區', field: 'equipment.factory.name' },
        { label: '部門', field: 'equipment.department' },
        { label: '週期', field: 'cycleLabel' },
        { label: '上傳日期', field: 'updated_at' },
        { label: '巡檢人員', field: 'user.name' },
        { label: '狀態', field: 'stateLabel' },
      ]"
      v-model="checkData"
      :rows="7"
      :selectable="false"
    >
    <template #column-stateLabel="{ data }">
      <span :class="data.stateClass">
        {{ data.stateLabel }}
      </span>
    </template>
    <template #action="{ data }">
          <button class="font-semibold text-sm rounded border bg-sky-500 text-white px-1 py-2 ">
            <router-link :to="`/CheckDetail/${data.id}/index`" class="flex text-sm ">
              <PencilIcon class="w-5 h-5 "/>查看詳細
            </router-link>
        </button>
    </template>
    </CustomTable>

  </div>
</template>

<script setup>
import { MagnifyingGlassIcon ,PencilIcon  } from '@heroicons/vue/24/solid'
import { ref, onMounted, computed, reactive } from 'vue'
import { useSwal } from "@/global/swal"
import { api } from "@/global/axios";
import CustomTable from '@/components/CustomTable.vue';

const checkData = ref([])
const cycleMap = {
  daily : '日',
  week  : '週',
  month : '月',
  season: '季',
  year  : '年',
}

const selectedState = ref('')
const stateMap = {
  0 : {label: '已查核', class: 'text-green-600'},
  1 : {label: '待查核', class: 'text-red-600' },
  2 : {label: '查核中', class: 'text-blue-600'},
}

// 載入資料
const loadData = async () => {
  try {
    const res = await api.get('/api/check-list')
    checkData.value = res.data?.data
    checkData.value.forEach(element => {
      element.updated_at = formatDate(element.updated_at)
    });
    checkData.value = res.data.data.map(item => ({
      ...item,
      cycleLabel: cycleMap[item.cycle] || item.cycle,
      stateLabel: stateMap[item.state]?.label || item.state,
      stateClass: stateMap[item.state]?.class || '',
    }))

  } catch (error) {
    await useSwal.error(error, '載入失敗')
  }
}

onMounted(() => {
  loadData()
})

// 搜尋列過濾
const keyword = ref('')
const filteredList = computed(() => {
  if (!keyword.value.trim()) return checkData.value
  const lowerKeyword = keyword.value.toLowerCase()
  return checkData.value.filter(item => {
    const searchString = [
      item.equipment?.name,
      item.equipment?.category?.name,
      item.equipment?.factory?.name,
      item.equipment?.department,
      cycleMap[item.cycle],
      item.cycle,
      formatDate(item.updated_at),
      item.user?.name,
      item.stateLabel // 狀態中文
    ]
      .map(v => (v || '').toString().toLowerCase())
      .join(' ')

    return searchString.includes(lowerKeyword)
  })
})

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    return [year, month, day].join('-');
}

</script>
