<script setup lang="ts">
import { ref, watch, computed } from "vue";
import { QForm, useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useResultDataStore } from "@/modules/07_insignia/storeResult";
import http from "@/plugins/http";
import config from "@/app.config";
import type { DataOption } from "@/modules/04_registry/components/profileType";

const DataStore = useResultDataStore();
const $q = useQuasar();
const myForm = ref<QForm>();
const mixin = useCounterMixin();
const {
  date2Thai,
  dialogConfirm,
  success,
  messageError,
  showLoader,
  hideLoader,
  notifyError,
} = mixin;
const status = ref<string>("");

const Advertise = ref<string>("");
const issue = ref<string>("");
const brand = ref<string>("");
const cardid = ref<string>("");
const fullName = ref<string>("");
const volume = ref<string>("");
const episode = ref<string>("");
const duty = ref<string>("");
const announced = ref<string>("");
const position = ref<string>("");
const payment = ref<string>("");
const addressPayment = ref<string | null>(null);
const affiliationRequest = ref<string>("");
const affiliationReceived = ref<string>("");
const receivedate = ref<Date | null>();
const announceDate = ref<Date | null>();
const invoiceDate = ref<Date | null>(null);

const employeeClass = ref<string>("");
const employeeClassOps = ref<DataOption[]>([
  { id: "officer", name: "ข้าราชการ กทม.สามัญ" },
  { id: "employee", name: "ลูกจ้างประจำ" },
]);

const listPerson = ref<any>([]);

const paymentOp = [
  { label: "จัดส่งทางไปรษณี", value: "จัดส่งทางไปรษณี" },
  { label: "มารับด้วยตัวเอง", value: "มารับด้วยตัวเอง" },
];
const clearDateExam = () => {
  receivedate.value = null;
  announceDate.value = null;
  invoiceDate.value = null;
};
const props = defineProps({
  modal: Boolean,
  save: {
    type: Function,
    default: () => console.log("not function"),
  },
  close: {
    type: Function,
    default: () => console.log("not function"),
  },
  roundId: {
    type: String,
  },
  action: {
    type: String,
  },
  personId: {
    type: String,
  },
  profileType: {
    type: String,
  },
});
watch(props, () => {
  if (props.modal === true) {
    employeeClass.value = "";
    cardid.value = "";
    fullName.value = "";
    position.value = "";
    Advertise.value = "";
    brand.value = "";
    receivedate.value = null;
    issue.value = "";
    affiliationRequest.value = "";
    affiliationReceived.value = "";
    announceDate.value = null;
    volume.value = "";
    episode.value = "";
    duty.value = "";
    announced.value = "";
    invoiceDate.value = null;
    payment.value = "";
    if (props.personId !== undefined) {
      if (props.action === "editData") {
        fectDataByid(props.personId);
      }
    }
  }
});
const disbleStatus = computed(() => {
  if (employeeClass.value !== "") {
    return false;
  } else return true;
});

const selectType = async () => {
  showLoader();
  cardid.value = "";
  fullName.value = "";
  position.value = "";
  Advertise.value = "";
  brand.value = "";
  receivedate.value = null;
  issue.value = "";
  affiliationRequest.value = "";
  affiliationReceived.value = "";
  announceDate.value = null;
  volume.value = "";
  episode.value = "";
  duty.value = "";
  announced.value = "";
  invoiceDate.value = null;
  payment.value = "";
  await fecthlistPerson();
};

const fecthlistPerson = async () => {
  await http
    .get(config.API.profileOrganizRoot)
    .then((res) => {
      const id = res.data.result[0].id;
      if (id !== "") {
        findlist(id);
      }
    })
    .catch((e) => {
      messageError($q, e);
    });
};
const findlist = async (id: string) => {
  let data = [{}];
  if (employeeClass.value === "officer") {
    data = [{ criteriaType: "is_retire", criteriaValue: "false" }];
  } else if (employeeClass.value === "employee") {
    data = [
      { criteriaType: "is_retire", criteriaValue: "false" },
      { criteriaType: "employee_class", criteriaValue: "perm" },
    ];
  }
  await http
    .post(config.API.profileSearchNewOcIdType(id, employeeClass.value), {
      criterias: data,
    })
    .then((res) => {
      listPerson.value = res.data.result;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};
const fectDataByid = async (id: string) => {
  showLoader();
  if (props.profileType !== undefined) {
    employeeClass.value = props.profileType.toString();
  }
  await http
    .get(config.API.noteByid(id))
    .then((res) => {
      let data = res.data.result;
      cardid.value = data.citizenId;
      fullName.value = data.fullName;
      position.value = data.position;
      Advertise.value = data.number;
      brand.value = data.requestInsigniaId;
      receivedate.value = data.dateReceive;
      issue.value = data.issue;
      affiliationRequest.value = data.organizationOrganizationSend;
      affiliationReceived.value = data.organizationOrganizationReceive;
      announceDate.value = data.date;
      volume.value = data.volumeNo;
      episode.value = data.section;
      duty.value = data.page;
      announced.value = data.no;
      invoiceDate.value = data.datePayment;
      payment.value = data.typePayment;
      addressPayment.value = data.address;
      status.value = data.status;
    })
    .catch((err) => {
      console.log(err);
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
};
const clickSave = async () => {
  let body = {
    citizanId: cardid.value, // เลขบัตร
    insigniaId: brand.value, // insigniaID
    number: Advertise.value,
    issue: issue.value,
    dateReceive: receivedate.value, // วันที่ได้รับเครื่องราชฯ
    organizationOrganizationSend: affiliationRequest.value,
    organizationOrganizationReceive: affiliationReceived.value,
    date: announceDate.value, // วันที่กิจนุเบก
    volumeNo: volume.value, // เล่ม
    section: episode.value, //ตอนที่
    page: duty.value, //หน้าที่
    no: announced.value,
    datePayment: invoiceDate.value, //วันที่จ่าย
    typePayment: payment.value, // รูปแบบการจ่าย
    address: addressPayment.value, //ที่อยู่
  };
  await myForm.value!.validate().then((result: boolean) => {
    if (result) {
      dialogConfirm($q, async () => {
        await addNote(body);
      });
    }
  });
};
const addNote = async (body: any) => {
  if (props.roundId !== undefined) {
    await http
      .put(config.API.noteAdd(props.roundId), body)
      .then(() => {
        success($q, "เพิ่มราชชื่อสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        props.close();
      });
  }
};
const searchcardid = () => {
  if (cardid.value.length === 13) {
    let data = listPerson.value.find((e: any) => e.citizenId === cardid.value);
    if (data) {
      fullName.value = data.fullname;
      position.value = data.positionEmployeePosition;
    } else notifyError($q, "ไม่พบข้อมูลเลขบัตรประชาชนนี้");
  }
};
</script>

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="min-width: 900px" class="q-pb-md">
      <q-toolbar class="q-py-md">
        <q-toolbar-title class="text-h6">บันทึกผล </q-toolbar-title>
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="props.close"
          style="color: #ff8080; background-color: #ffdede"
          ><q-tooltip>ปืด</q-tooltip></q-btn
        >
      </q-toolbar>
      <q-separator />

      <q-form ref="myForm">
        <div class="q-pa-md">
          <div
            class="row col-12 items-center q-col-gutter-x-xs q-col-gutter-y-xs"
          >
            <div class="col-4">
              <q-select
                :rules="[
                  (val) => !!val || 'กรุณาเลือก  ขรก.สามัญ/ลูกจ้างประจำ',
                ]"
                hide-bottom-space
                :options="employeeClassOps"
                dense
                borderless
                option-label="name"
                option-value="id"
                emit-value
                map-options
                outlined
                v-model="employeeClass"
                :label="`ขรก.สามัญ/ลูกจ้างประจำ`"
                @update:model-value="selectType"
                :disable="status !== ''"
              />
            </div>
            <div class="col-12 text-weight-bold text-grey">
              รายละเอียดข้อมูล
            </div>
            <div class="col-xs-12 col-sm-4">
              <q-input
                :disable="
                  disbleStatus || status == 'DONE' || status == 'PENDING'
                "
                hide-bottom-space
                outlined
                class="inputgreen"
                v-model="cardid"
                dense
                lazy-rules
                :rules="[
              (val:string) => !!val || `${'กรุณากรอก เลขบัตรประจำตัวประชาชน'}`,
              (val:string) =>
                val.length >= 13 ||
                `${'กรุณากรอกเลขบัตรประจำตัวประชาชนให้ครบ'}`,
            ]"
                label="เลขบัตรประจำตัวประชาชน"
                maxlength="13"
                mask="#############"
                @keyup="searchcardid"
              />
            </div>

            <div class="col-xs-6 col-sm-4">
              <q-input
                disable
                hide-bottom-space
                outlined
                dense
                lazy-rules
                class="inputgreen"
                borderless
                v-model="fullName"
                :label="`${'ชื่อ-นามสกุล'}`"
              />
            </div>

            <div class="col-xs-12 col-sm-4">
              <q-input
                disable
                hide-bottom-space
                outlined
                dense
                lazy-rules
                class="inputgreen"
                borderless
                v-model="position"
                :label="`ตำเเหน่ง`"
              />
            </div>

            <div class="col-6"></div>

            <div class="col-12 q-my-xs"><q-separator size="2px" /></div>
            <div class="col-12 text-weight-bold text-grey">
              รายละเอียดตำเเหน่ง
            </div>
            <div class="col-xs-12 col-sm-6">
              <q-input
                :disable="disbleStatus || status == 'DONE'"
                :rules="[
                  (val) =>
                    !!val ||
                    'กรุณากรอกหมายเลขประกาศนีย์บัตรกำกับเครื่องราชอิสริยาภรณ์',
                ]"
                hide-bottom-space
                dense
                borderless
                outlined
                v-model="Advertise"
                label="หมายเลขประกาศนีย์บัตรกำกับเครื่องราชอิสริยาภรณ์"
              />
            </div>
            <div class="col-xs-12 col-sm-6">
              <q-select
                :disable="disbleStatus || status == 'DONE'"
                v-model="brand"
                dense
                outlined
                lazy-rules
                hide-bottom-space
                :label="`${'ชั้นตราเครื่องราชอิสริยาภรณ์'}`"
                emit-value
                map-options
                option-label="name"
                :options="DataStore.insigniaOp2"
                option-value="id"
                :readonly="false"
                :borderless="false"
                style="min-width: 150px"
                :rules="[
                  (val) => !!val || 'กรุณากรอกชื่อชั้นตราเครื่องราชอิสริยาภรณ์',
                ]"
              />
            </div>
            <div class="col-xs-12 col-sm-6">
              <datepicker
                menu-class-name="modalfix"
                v-model="receivedate"
                :locale="'th'"
                autoApply
                borderless
                :enableTimePicker="false"
                week-start="0"
                :readonly="disbleStatus || status == 'DONE'"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    :disable="disbleStatus || status == 'DONE'"
                    dense
                    borderless
                    outlined
                    :rules="[(val) => !!val || 'กรุณาเลือกวันที่']"
                    hide-bottom-space
                    :model-value="
                      receivedate != null ? date2Thai(receivedate) : undefined
                    "
                    :label="`${'วันที่ได้รับพระราชทานเครื่องราชอิสริยาภรณ์'}`"
                    clearable
                    @clear="clearDateExam"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-12 col-sm-6">
              <q-input
                :disable="disbleStatus || status == 'DONE'"
                :rules="[(val) => !!val || 'กรุณากรอกทะเบียนฐานนันดร']"
                hide-bottom-space
                dense
                borderless
                outlined
                v-model="issue"
                label="ทะเบียนฐานนันดร"
              />
            </div>
            <div class="col-xs-12 col-sm-6">
              <q-input
                :disable="
                  disbleStatus || status == 'DONE' || status == 'PENDING'
                "
                :rules="[(val) => !!val || 'กรุณากรอกสังกัด']"
                hide-bottom-space
                dense
                borderless
                outlined
                v-model="affiliationRequest"
                label="สังกัด ณ วันที่ขอพระราชทานเครื่องราชอิสริยาภรณ์"
              />
            </div>
            <div class="col-xs-12 col-sm-6">
              <q-input
                :disable="
                  disbleStatus || status == 'DONE' || status == 'PENDING'
                "
                :rules="[(val) => !!val || 'กรุณากรอกสังกัด']"
                hide-bottom-space
                dense
                borderless
                outlined
                v-model="affiliationReceived"
                label="สังกัด ณ วันที่ได้รับประกาศนียบัตรกำกับเครื่องราชอิสริยาภรณ์"
              />
            </div>
            <div class="col-12 q-my-xs"><q-separator size="2px" /></div>
            <div class="col-12 text-weight-bold text-grey">
              ประกาศราชกิจจานุเบกษา
            </div>
            <div class="col-xs-12 col-sm-4">
              <datepicker
                menu-class-name="modalfix"
                v-model="announceDate"
                :locale="'th'"
                autoApply
                borderless
                :enableTimePicker="false"
                week-start="0"
                :readonly="disbleStatus || status == 'DONE'"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    :disable="disbleStatus || status == 'DONE'"
                    dense
                    borderless
                    outlined
                    :rules="[(val) => !!val || 'กรุณาเลือกวันที่']"
                    hide-bottom-space
                    :model-value="
                      announceDate != null ? date2Thai(announceDate) : undefined
                    "
                    :label="`${'วันที่'}`"
                    clearable
                    @clear="clearDateExam"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-12 col-sm-4">
              <q-input
                :disable="disbleStatus || status == 'DONE'"
                hide-bottom-space
                outlined
                dense
                lazy-rules
                class="inputgreen"
                borderless
                v-model="volume"
                :label="`เล่มที่`"
                :rules="[(val) => !!val || 'กรุณากรอกเล่มที่']"
              />
            </div>
            <div class="col-xs-12 col-sm-4">
              <q-input
                :disable="disbleStatus || status == 'DONE'"
                hide-bottom-space
                outlined
                dense
                lazy-rules
                class="inputgreen"
                borderless
                v-model="episode"
                :label="`ตอนที่`"
                :rules="[(val) => !!val || 'กรุณากรอกตอนที่']"
              />
            </div>
            <div class="col-xs-12 col-sm-6">
              <q-input
                :disable="disbleStatus || status == 'DONE'"
                hide-bottom-space
                outlined
                dense
                lazy-rules
                class="inputgreen"
                borderless
                v-model="duty"
                :label="`หน้าที่`"
                :rules="[(val) => !!val || 'กรุณากรอกหน้าที่']"
              />
            </div>
            <div class="col-xs-12 col-sm-6">
              <q-input
                :disable="disbleStatus || status == 'DONE'"
                hide-bottom-space
                outlined
                dense
                lazy-rules
                class="inputgreen"
                borderless
                v-model="announced"
                :label="`ลำดับที่`"
                :rules="[(val) => !!val || 'กรุณากรอกลำดับที่']"
              />
            </div>
            <div class="col-12 q-my-xs"><q-separator size="2px" /></div>
            <div class="col-12 text-weight-bold text-grey">
              ผลการจ่ายใบกำกับ
            </div>
            <div class="col-xs-12 col-sm-6">
              <datepicker
                menu-class-name="modalfix"
                v-model="invoiceDate"
                :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
                    :disable="disbleStatus"
                    dense
                    borderless
                    outlined
                    hide-bottom-space
                    :model-value="
                      invoiceDate != null ? date2Thai(invoiceDate) : undefined
                    "
                    :label="`${'วันที่จ่ายใบกำกับ'}`"
                    clearable
                    @clear="clearDateExam"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-12 col-sm-6">
              <q-select
                :disable="disbleStatus"
                hide-bottom-space
                :options="paymentOp"
                class="col-xs-12 col-sm-6"
                dense
                borderless
                option-label="label"
                option-value="value"
                outlined
                emit-value
                map-options
                v-model="payment"
                :label="`เลือกรูปแบบการจ่าย`"
              />
            </div>
            <div v-if="payment === 'จัดส่งทางไปรษณี'" class="col-12">
              <q-input
                :disable="disbleStatus"
                label="ที่อยู่ที่จ่าย"
                class="bg-white"
                dense
                borderless
                outlined
                v-model="addressPayment"
                type="textarea"
              />
            </div>
          </div>
        </div>
      </q-form>

      <q-separator />
      <div class="q-pa-md">
        <div class="row justify-end">
          <q-btn label="บันทึก" @click="clickSave" color="public"
            ><q-tooltip>บันทึก</q-tooltip></q-btn
          >
        </div>
      </div>
    </q-card>
  </q-dialog>
</template>
