<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="text-xl sm:text-3xl px-3 pb-2 font-semibold text-black dark:text-white border-b-4 border-zinc-200">派工設定 - 派工排程</h2>
  <div class="sm:p-4 md:p-6 font-semibold mt-4 sm:mt-0">
    <!-- 標題與新增按鈕 -->

    <!-- 表格一 -->
    <div class="flex flex-col border-2 border-slate-300 shadow-md rounded px-3 py-2">
      <div class="flex px-1 py-2">
        <span class="text-left">檢核表單：</span>
        <select class="border rounded flex-shrink min-w-0" v-model="dispatch.bank_id">
          <option disabled value="">請選擇檢核表單</option>
          <option v-for="form in forms" :key="form.id" :value="form.id">
            {{ form?.name }}
          </option>
        </select>
      </div>
      <div class="flex items-center px-1 py-2">
        <span class="mr-2">週期：</span>
        <label class="flex items-center mr-2">
          <input type="radio" value="daily"  v-model="dispatch.cycle" name="cycle" />日
        </label>
        <label class="flex items-center mr-2">
          <input type="radio" value="week"   v-model="dispatch.cycle" name="cycle" />週
        </label>
        <label class="flex items-center mr-2">
          <input type="radio" value="month"  v-model="dispatch.cycle" name="cycle" />月
        </label>
        <label class="flex items-center mr-2">
          <input type="radio" value="season" v-model="dispatch.cycle" name="cycle" />季
        </label>
        <label class="flex items-center">
          <input type="radio" value="year"   v-model="dispatch.cycle" name="cycle" />年
        </label>
      </div>
      <div class="flex px-1 py-2">
        <span class="text-left">巡檢人員：</span>
          <select class="border rounded flex-shrink min-w-0" v-model="dispatch.checker_id">
          <option disabled value="">請選擇巡檢人員</option>
          <option v-for="user in users" :key="user.id" :value="user.id">
            {{ user.name }}
          </option>
        </select>
      </div>
      <div class="flex px-1 py-2">
        <span class="text-left">起始日期：</span>
        <input type="date" v-model="dispatch.startdate" />
      </div>
    </div>
    <!-- 表格二 -->
    <div class="overflow-x-auto border border-gray-200 rounded shadow mt-4 p-3">
      <div class="flex text-xl mx-2 mb-2">{{ dispatch.name || '' }}</div>

      <CustomTable
        :items="dispatchData"
        :columns="[
          { label: '檢核項目', field: 'item' },
          { label: '管理值', field: 'rangeDisplay' }
        ]"
        :rows="7"
        :selectable="false"
      >
        <template #column-rangeDisplay="{ data }">
          {{
            data.range && data.range2 ? `${data.range} ~ ${data.range2}` :
            data.range ? `> ${data.range}` :
            data.range2 ? `< ${data.range2}` :
            ''
          }}
        </template>
      </CustomTable>
    </div>

    <!-- 儲存檢核表、返回-->
    <div class="flex flex-col sm:flex-row mb-6 font-semibold mt-2 sm:justify-center gap-4">
      <button
        class="flex px-2 py-2 bg-red-500 text-white rounded sm:w-auto mb-2 justify-center"
      >
        <router-link :to="`/Dispatch/Index`" class="flex w-full justify-center">
          <ArrowUturnLeftIcon class="w-6 h-6"/>
          取消
        </router-link>
      </button>
      <button
        class="flex px-2 py-2 bg-green-500 text-white rounded sm:w-auto mb-2 justify-center"
        @click="save"
      >
        <DocumentCheckIcon class="w-6 h-6"/>儲存
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive , watch} from 'vue'
import { DocumentCheckIcon , ArrowUturnLeftIcon} 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 dispatchData = ref([])
const dispatch = reactive({ bank_id: '' , checker_id : '' , cycle: 'daily' , startdate: ''})

// 載入檢核表單資料
watch(() => dispatch.bank_id , async(id) => {
  if (!id) {
    dispatchData.value=[]
    return
  }

  const selected = forms.value.find(f => f.id === id)
  if(selected){
    dispatch.name = selected.equipment?.name
  }

  try {
    const res = await api.get(`/api/dispatchSet/getDispatch?dispatchId=${id}`)
    dispatchData.value = res.data.data
  } catch (e) {
    console.error('載入檢核表單基本資料失敗', e)
  }
})

const users = ref([])
const forms = ref([])
// 載入檢核表單、巡檢人員資料
const getForm = async () => {
  const res = await api.get('/api/dispatchSet/getForm')
  users.value = res.data.userData
  forms.value = res.data.bankData
}

const save = async () => {
  if (!dispatch.bank_id) {
    await useSwal.error('請選擇「檢核表單」', '資料未填寫完整')
    return
  }
  if (!dispatch.cycle){
    await useSwal.error('請確認已勾選「週期」','資料未填寫完整')
    return
  }
  if (!dispatch.checker_id){
    await useSwal.error('請確認已勾選「巡檢人員」','資料未填寫完整')
    return
  }
  if (!dispatch.startdate){
    await useSwal.error('請選擇「起始日期」','資料未填寫完整')
    return
  }
  if(dispatchData.value.length === 0){
    await useSwal.error('該檢核表單尚未建立檢查項目，新增失敗')
    return
  }
  try {
    await api.post('/api/dispatch' , dispatch)
    await useSwal.success('派工單新增成功')
    router.push('/dispatch/Index')
  } catch (e) {
    await useSwal.error('請稍後再試，或聯絡管理員', '儲存失敗')
  }
}

onMounted(() => 
  getForm() ,
)

</script>
