<template>
  <div style="max-height: 68vh; overflow-y: scroll">
    <q-form ref="myForm" class="q-pa-md">
      <div class="row col-12 q-col-gutter-x-lg q-col-gutter-y-md">
        <div class="col-xs-12 col-md-6">
          <selector :class="getClass(true)" outlined dense lazy-rules v-model="typeOrder"
            :rules="[(val: string) => !!val || `${'กรุณาเลือกประเภทคำสั่ง'}`]" hide-bottom-space
            :label="`${'ประเภทคำสั่ง'}`" @update:modelValue="clickEditRow" emit-value map-options option-label="name"
            :options="typeOrderOption" option-value="id" use-input input-debounce="0" />
          <!-- @filter="(inputValue:string,
          doneFn:Function) => filterSelector(inputValue, doneFn,'typeOrderOption'
          ) " -->
        </div>

        <div class="col-xs-12 col-md-6">
          <!-- :readonly="!edit"
                :borderless="!edit" -->
          <q-input :class="getClass(true)" outlined dense lazy-rules v-model="nameOrder"
            :rules="[(val) => !!val || `${'กรุณากรอกคำสั่งเรื่อง'}`]" :label="`${'คำสั่งเรื่อง'}`"
            @update:modelValue="clickEditRow" hide-bottom-space />
        </div>

        <div class="row col-xs-7 col-md-3 q-col-gutter-x-xs">
          <div class="col-6">
            <q-input :class="getClass(true)" outlined dense lazy-rules v-model="command"
              :rules="[(val) => !!val || `${'กรุณากรอกคำสั่ง'}`]" :label="`${'คำสั่ง'}`" @update:modelValue="clickEditRow"
              hide-bottom-space type="number" />
          </div>
          <label class="col-1 flex justify-center items-center text-bold">/</label>
          <div class="col-5">
            <datepicker v-model="dateYear" :locale="'th'" autoApply year-picker :enableTimePicker="false"
              @update:modelValue="clickEditRow">
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input :model-value="dateYear + 543" :rules="[(val) => !!val || `${'กรุณากรอก พ.ศ.'}`]"
                  :label="`${'พ.ศ.'}`" dense outlined>
                </q-input>
              </template>
            </datepicker>
          </div>
        </div>
        <div class="col-xs-5 col-md-3">
          <datepicker menu-class-name="modalfix" v-model="dateCommand" :locale="'th'" autoApply borderless
            :enableTimePicker="false" week-start="0">
            <template #year="{ year }">
              {{ year + 543 }}
            </template>
            <template #year-overlay-value="{ value }">
              {{ parseInt(value + 543) }}
            </template>
            <template #trigger>
              <q-input outlined dense class="full-width datepicker" :model-value="dateCommand != null ? date2Thai(dateCommand) : null
                " :label="`${'วันที่มีผลออกคำสั่ง'}`" :rules="[
    (val) => !!val || `${'กรุณาเลือกวันที่มีผลออกคำสั่ง'}`,
  ]">
                <template v-slot:prepend>
                  <q-icon name="event" class="cursor-pointer" style="color: var(--q-primary)">
                  </q-icon>
                </template>
              </q-input>
            </template>
          </datepicker>
        </div>

        <div class="col-xs-12 col-md-6">
          <selector :class="getClass(true)" outlined dense lazy-rules v-model="byOrder"
            :rules="[(val: string) => !!val || `${'กรุณาเลือกคำสั่งโดย'}`]" hide-bottom-space :label="`${'คำสั่งโดย'}`"
            @update:modelValue="clickEditRow" emit-value map-options option-label="name" :options="byOrderOption"
            option-value="id" use-input input-debounce="0" />
          <!-- @filter="(inputValue:string,
          doneFn:Function) => filterSelector(inputValue, doneFn,'byOrderOption'
          ) " -->
        </div>
        <div class="col-xs-12 col-md-6">
          <!-- :readonly="!edit"
                :borderless="!edit" -->
          <q-input :class="getClass(true)" outlined dense lazy-rules v-model="nameCommand"
            :rules="[(val) => !!val || `${'กรุณากรอกผู้มีอำนาจลงนาม'}`]" :label="`${'ผู้มีอำนาจลงนาม'}`"
            @update:modelValue="clickEditRow" hide-bottom-space />
        </div>
        <div class="col-xs-12 col-md-6">
          <!-- :readonly="!edit"
                :borderless="!edit" -->
          <q-input :class="getClass(true)" outlined dense lazy-rules v-model="positionCommand"
            :rules="[(val) => !!val || `${'กรุณากรอกตำแหน่งผู้มีอำนาจลงนาม'}`]" :label="`${'ตำแหน่งผู้มีอำนาจลงนาม'}`"
            @update:modelValue="clickEditRow" hide-bottom-space />
        </div>
        <div class="col-12">
          <q-separator />
        </div>
        <div class="col-xs-12 col-md-6">
          <selector :class="getClass(true)" outlined dense lazy-rules v-model="examRound"
            :rules="[(val: string) => !!val || `${'กรุณาเลือกรอบการสอบ'}`]" hide-bottom-space :label="`${'รอบการสอบ'}`"
            @update:modelValue="clickEditRow" emit-value map-options option-label="examRoundName"
            :options="examRoundOption" option-value="examRoundValue" use-input input-debounce="0" />
          <!-- @filter="(inputValue:string,
          doneFn:Function) => filterSelector(inputValue, doneFn,'testOption'
          ) " -->
        </div>
        <div class="col-xs-12 col-md-6">
          <!-- <selector :class="getClass(true)" outlined dense lazy-rules v-model="position"
            :rules="[(val: string) => !!val || `${'กรุณาเลือกตำแหน่งรับสมัคร'}`]" hide-bottom-space
            :label="`${'ตำแหน่งรับสมัคร'}`" @update:modelValue="clickEditRow" emit-value map-options option-label="name"
            :options="positionOption" option-value="id" use-input input-debounce="0" /> -->
          <!-- @filter="(inputValue:string, doneFn:Function) =>
          filterSelector(inputValue, doneFn,'positionOption' ) " -->
        </div>
        <div class="col-xs-12 col-md-6">
          <selector :class="getClass(true)" outlined dense lazy-rules v-model="register"
            :rules="[(val: string) => !!val || `${'กรุณาเลือกมติ กก. ครั้งที่ (เรื่อง รับสมัครสอบฯ)'}`]" hide-bottom-space
            :label="`${'มติ กก. ครั้งที่ (เรื่อง รับสมัครสอบฯ)'}`" @update:modelValue="clickEditRow" emit-value
            map-options option-label="name" :options="registerOption" option-value="id" use-input input-debounce="0" />
        </div>
        <!-- @filter="(inputValue:string,
        doneFn:Function) => filterSelector(inputValue, doneFn,'registerOption'
        ) " -->

        <div class="col-xs-12 col-md-6">
          <datepicker menu-class-name="modalfix" v-model="dateRegister" :locale="'th'" autoApply borderless
            :enableTimePicker="false" week-start="0">
            <template #year="{ year }">
              {{ year + 543 }}
            </template>
            <template #year-overlay-value="{ value }">
              {{ parseInt(value + 543) }}
            </template>
            <template #trigger>
              <q-input outlined dense class="full-width datepicker" :model-value="dateRegister != null ? date2Thai(dateRegister) : null
                " :label="`${'ลงวันที่ (เรื่อง รับสมัครสอบฯ)'}`" :rules="[
    (val) =>
      !!val || `${'กรุณาเลือกลงวันที่ (เรื่อง รับสมัครสอบฯ)'}`,
  ]">
                <template v-slot:prepend>
                  <q-icon name="event" class="cursor-pointer" style="color: var(--q-primary)">
                  </q-icon>
                </template>
              </q-input>
            </template>
          </datepicker>
        </div>
        <div class="col-xs-12 col-md-6">
          <selector :class="getClass(true)" outlined dense lazy-rules v-model="announce"
            :rules="[(val: string) => !!val || `${'กรุณาเลือกมติ กก. ครั้งที่ (เรื่อง ผลการสอบแข่งขัน)'}`]"
            hide-bottom-space :label="`${'มติ กก. ครั้งที่ (เรื่อง ผลการสอบแข่งขัน)'}`" @update:modelValue="clickEditRow"
            emit-value map-options option-label="name" :options="announceOption" option-value="id" use-input
            input-debounce="0" />
          <!-- @filter="(inputValue:string,
          doneFn:Function) => filterSelector(inputValue, doneFn,'announceOption'
          ) "  -->
        </div>
        <div class="col-xs-12 col-md-6">
          <datepicker menu-class-name="modalfix" v-model="dateAnnounce" :locale="'th'" autoApply borderless
            :enableTimePicker="false" week-start="0">
            <template #year="{ year }">
              {{ year + 543 }}
            </template>
            <template #year-overlay-value="{ value }">
              {{ parseInt(value + 543) }}
            </template>
            <template #trigger>
              <q-input outlined dense class="full-width datepicker" :model-value="dateAnnounce != null ? date2Thai(dateAnnounce) : null
                " :label="`${'ลงวันที่ (เรื่อง ผลการสอบแข่งขัน)'}`" :rules="[
    (val) =>
      !!val || `${'กรุณาเลือกลงวันที่ (เรื่อง ผลการสอบแข่งขัน)'}`,
  ]">
                <template v-slot:prepend>
                  <q-icon name="event" class="cursor-pointer" style="color: var(--q-primary)">
                  </q-icon>
                </template>
              </q-input>
            </template>
          </datepicker>
        </div>
      </div>
    </q-form>
  </div>
  <q-separator />
  <div class="flex justify-end q-pa-sm q-gutter-sm">
    <q-btn unelevated label="บันทึก" color="public" @click="submit">
      <q-tooltip>บันทึก</q-tooltip>
    </q-btn>
    <!-- <q-btn flat round color="primary" icon="chevron_left" @click="previous">
        <q-tooltip>ย้อนกลับ</q-tooltip>
      </q-btn> -->
    <!-- <q-btn flat round color="primary" icon="chevron_right" @click="next">
        <q-tooltip>ต่อไป</q-tooltip>
      </q-btn> -->
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import type {
  DataOption1,
  DataOption,
} from "@/modules/05_placement/interface/index/Main";
import { useCounterMixin } from "@/stores/mixin";
import type { QForm } from "quasar";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";

const mixin = useCounterMixin();
const { date2Thai, messageError, showLoader, hideLoader, success, dialogMessage } = mixin;
const $q = useQuasar(); //ใช้ noti quasar
const route = useRoute();

const props = defineProps({
  next: {
    type: Function,
    default: () => console.log("not function"),
  },
  previous: {
    type: Function,
    default: () => console.log("not function"),
  },
});
const next = () => props.next();
const previous = () => props.previous();
const orderId = route.params.orderid;

const myForm = ref<QForm>();

const editRow = ref<boolean>(false);

const nameOrder = ref<string>("");
const nameCommand = ref<string>("");
const positionCommand = ref<string>("");
const dateYear = ref<number>(new Date().getFullYear());
const command = ref<number>();
const dateCommand = ref<Date>(new Date());
const dateRegister = ref<Date>(new Date());
const dateAnnounce = ref<Date>(new Date());

const typeOrder = ref<number>();
const typeOrderOption = ref<DataOption1[]>([
  { name: "คำสั่งที่ 1", id: "3fa85f64-5717-4562-b3fc-2c963f66afa6" },
]);
const typeOrderOptionFilter = ref<DataOption1[]>([]);

const byOrder = ref<string>("");
const byOrderOption = ref<DataOption1[]>([
  { name: "นายดด นน", id: "3fa85f64-5717-4562-b3fc-2c963f66afa6" },
]);
const byOrderOptionFilter = ref<DataOption1[]>([]);

const register = ref<string>("");
const registerOption = ref<DataOption1[]>([
  { name: "ครั้งที่ 1", id: "3fa85f64-5717-4562-b3fc-2c963f66afa6" },
]);
const registerOptionFilter = ref<DataOption[]>([]);

const announce = ref<string>("");
const announceOption = ref<DataOption1[]>([
  { name: "ครั้งที่ 1", id: "3fa85f64-5717-4562-b3fc-2c963f66afa6" },
]);
const announceOptionFilter = ref<DataOption[]>([]);

const position = ref<string>("");
const positionOption = ref<DataOption1[]>([
  { name: "ผู้ช่วย", id: "3fa85f64-5717-4562-b3fc-2c963f66afa6" },
]);
const positionOptionFilter = ref<DataOption[]>([]);

const examRound = ref<string>("");
const examRoundOption = ref<DataOption1[]>([]);
const testOptionFilter = ref<DataOption[]>([]);

const clickEditRow = () => (editRow.value = true);

// const filterSelector = (val: any, update: Function, filtername: string) => {
//   switch (filtername) {
//     case "typeOrderOption":
//       update(() => {
//         typeOrderOption.value = typeOrderOptionFilter.value.filter(
//           (v: DataOption) => v.name!.indexOf(val) > -1
//         );
//       });
//       break;
//     case "byOrderOption":
//       update(() => {
//         byOrderOption.value = byOrderOptionFilter.value.filter(
//           (v: DataOption) => v.name!.indexOf(val) > -1
//         );
//       });
//       break;

//     case "registerOption":
//       update(() => {
//         registerOption.value = registerOptionFilter.value.filter(
//           (v: DataOption) => v.name!.indexOf(val) > -1
//         );
//       });
//       break;

//     case "announceOption":
//       update(() => {
//         announceOption.value = announceOptionFilter.value.filter(
//           (v: DataOption) => v.name!.indexOf(val) > -1
//         );
//       });
//       break;

//     case "positionOption":
//       update(() => {
//         positionOption.value = positionOptionFilter.value.filter(
//           (v: DataOption) => v.name!.indexOf(val) > -1
//         );
//       });
//       break;
//     case "testOption":
//       update(() => {
//         testOption.value = testOptionFilter.value.filter(
//           (v: DataOption) => v.name!.indexOf(val) > -1
//         );
//       });
//       break;
//     default:
//       break;
//   }
// };
onMounted(async () => {
  if (orderId) {
    await fetchdetailOrder();
  } else {
    fecthTypeOption();
    fecthExamRoundOption();
  }

  // const data = localStorage.getItem("formData");
  // if (data) {
  //   const parsedData = JSON.parse(data);
  //   typeOrder.value = parsedData.orderTypeValue;
  //   nameOrder.value = parsedData.orderTitle;
  //   command.value = parsedData.orderNo;
  //   dateYear.value = parsedData.orderYear;
  //   dateCommand.value = parsedData.orderDate;
  //   byOrder.value = parsedData.orderBy;
  //   nameCommand.value = parsedData.signatoryBy;
  //   positionCommand.value = parsedData.signatoryPosition;
  //   test.value = parsedData.examRound;
  //   position.value = parsedData.registerPosition;
  //   register.value = parsedData.conclusionRegisterNo;
  //   dateRegister.value = parsedData.conclusionRegisterDate;
  //   announce.value = parsedData.conclusionResultNo;
  //   dateAnnounce.value = parsedData.conclusionResultDate;
  // }
});
const fetchdetailOrder = async () => {
  showLoader();
  // console.log(orderId);
  let orderIdString = orderId.toString();
  await http
    .get(config.API.detailOrder(orderIdString))
    .then((res: any) => {
      const data = res.data.result;
      typeOrder.value = data.orderTypeValue;
      nameOrder.value = data.orderTitle;
      command.value = data.orderNo;
      dateYear.value = Number(data.orderYear);
      dateCommand.value = data.orderDate;
      byOrder.value = data.orderBy;
      nameCommand.value = data.signatoryBy;
      positionCommand.value = data.signatoryPosition;
      examRound.value = data.examRound;
      // position.value = data.registerPosition;
      register.value = data.conclusionRegisterNo;
      dateRegister.value = data.conclusionRegisterDate;
      announce.value = data.conclusionResultNo;
      dateAnnounce.value = data.conclusionResultDate;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
      fecthTypeOption();
      fecthExamRoundOption();
    });
};
const fecthTypeOption = async () => {
  await http
    .get(config.API.typeOrder())
    .then((res) => {
      typeOrderOption.value = res.data.result;
    })
    .catch((e) => {
      messageError($q, e);
    });
};
const fecthExamRoundOption = async () => {
  await http
    .get(config.API.examroundOrder())
    .then((res) => {
      examRoundOption.value = res.data.result;
      console.log(examRoundOption.value);
    })
    .catch((e) => { });
};
const submit = async () => {
  const formdata = {
    orderTypeValue: typeOrder.value,
    orderTitle: nameOrder.value,
    orderNo: Number(command.value),
    orderYear: dateYear.value,
    orderDate: dateCommand.value,
    orderBy: byOrder.value,
    signatoryBy: nameCommand.value,
    signatoryPosition: positionCommand.value,
    examRound: examRound.value,
    registerPosition: position.value,
    conclusionRegisterNo: register.value,
    conclusionRegisterDate: dateRegister.value,
    conclusionResultNo: announce.value.toString(),
    conclusionResultDate: dateAnnounce.value,
  };
  await myForm.value!.validate().then((result: boolean) => {
    if (result) {
      dialogMessage(
        $q,
        "ยืนยันการบันทึกข้อมูล",
        "ต้องการบันทึกข้อมูลนี้ใช่หรือไม่?",
        "info",
        "ตกลง",
        "public",
        () => {
          if (!orderId) {
            createListOrder(formdata);
          } else {
            let orderIdString = orderId.toString();
            updateOrder(formdata, orderIdString);
          }
        },
        undefined
      );
    }
  });
};
const createListOrder = async (formData: Object) => {
  // console.log(formData);
  await http
    .post(config.API.createOrder(), formData)
    .then((res) => {
      const data = res.data.result;
      localStorage.setItem("orderId", data.id);
      next();
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const updateOrder = async (formData: Object, orderId: string) => {
  // console.log(formData);
  await http
    .put(config.API.detailOrder(orderId), formData)
    .then((res) => {
      console.log(res);
      next();
      success($q, "แก้ไขข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

/**
 * class จัดรูปแบบแสดงระหว่างข้อมูลที่แก้ไขหรือแสดงเฉยๆ
 * @param val ข้อมูล input สำหรับแก้ไขหรือไม่
 */
const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
</script>
<style>
.q-field--with-bottom {
  padding-bottom: 0px;
}
</style>
