<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { QForm, useQuasar } from "quasar";

import { useCounterMixin } from "@/stores/mixin";
import { useBrrowDataStore } from "@/modules/07_insignia/storeBrrow";
import http from "@/plugins/http";
import config from "@/app.config";

/** impotrType */
import type { QTableColumn } from "quasar";
import type { DataOption } from "@/modules/07_insignia/interface/index/Main";

/** impotrComponents */
import DialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar();
const DataStore = useBrrowDataStore();
const mixin = useCounterMixin();
const {
  date2Thai,
  dialogConfirm,
  success,
  messageError,
  showLoader,
  hideLoader,
  onSearchDataTable,
  convertDateToAPI,
} = mixin;

/** props*/
const props = defineProps({
  modal: Boolean,
  save: {
    type: Function,
    default: () => console.log("not function"),
  },
  close: {
    type: Function,
    default: () => console.log("not function"),
  },
  closeAndFecth: {
    type: Function,
    default: () => console.log("not function"),
  },
  roundId: {
    type: String,
  },
  action: {
    type: String,
  },
  typeId: {
    type: String,
  },
  selectRoundOption: {
    type: Array,
  },
  filterSelectRoundOption: {
    type: Array,
  },
  profileId: {
    type: String,
    default: "",
  },
  type: {
    type: Array,
  },
});

const brand = ref<string>(""); //เครื่องราชฯ
const roundNo = ref<string | undefined>(""); //รอบการขอเครื่องราชฯ
const cardid = ref<string>(""); //เลขประจำตัวประชาชน
const OrganazationId = ref<string>(""); //
const receivedate = ref<Date | null>(); //วันที่ยืม
const returndate = ref<Date | null>(); //วันที่คืน
const fullName = ref<string>(""); //ชื่อ-นามสกุล
const reason = ref<string>("");
const OrgList = ref<DataOption[]>([]);
const filterOrgList = ref<DataOption[]>([]);
const insigniaNoteProfileId = ref<string>("");
const filterSelectRound = ref<any>();
const selectRound = ref<any>();

const rows = ref<any[]>([]);
const rowsMain = ref<any[]>([]);
const keyword = ref<string>("");
const selected = ref<any[]>([]);
const columns = ref<QTableColumn[]>([
  {
    name: "noNumber",
    align: "left",
    label: "ลำดับ",
    field: "noNumber",
    sortable: false,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    field: "citizenId",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    field: "fullName",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "profileType",
    align: "left",
    label: "ประเภทตำแหน่ง",
    field: "profileType",
    sortable: true,
    format(val, row) {
      return DataStore.profileType(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่งประเภท",
    field: "position",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "requestInsignia",
    align: "left",
    label: "เครื่องราชๆ",
    field: "requestInsignia",
    format(val, row) {
      return `${row.requestInsignia ?? ""}
      ${
        row.requestInsigniaShortName ? `(${row.requestInsigniaShortName})` : ""
      }  `;
    },
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateReceive",
    align: "left",
    label: "วันที่ได้รับพระราชทาน",
    field: "dateReceive",
    sortable: true,
    format(val, row) {
      return date2Thai(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  // {
  //   name: "date",
  //   align: "left",
  //   label: "วันที่ในราชกิจนุเบกษา",
  //   field: "date",
  //   sortable: true,
  //   format(val, row) {
  //     return date2Thai(val);
  //   },
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
  // {
  //   name: "volumeNo",
  //   align: "left",
  //   label: "เล่มที่ในราชกิจนุเบกษา",
  //   field: "volumeNo",
  //   sortable: true,
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
  // {
  //   name: "section",
  //   align: "left",
  //   label: "ตอนที่ในราชกิจนุเบกษา",
  //   field: "section",
  //   sortable: true,
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
  // {
  //   name: "page",
  //   align: "left",
  //   label: "หน้าในราชกิจนุเบกษา",
  //   field: "page",
  //   sortable: true,
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
  // {
  //   name: "no",
  //   align: "left",
  //   label: "ลำดับที่ในราชกิจจานุเบกษา",
  //   field: "no",
  //   sortable: true,
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
  // {
  //   name: "number",
  //   align: "left",
  //   label: "หมายเลขใบกำกับ",
  //   field: "number",
  //   sortable: true,
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
]);
const visibleColumns = ref<string[]>([
  "noNumber",
  "citizenId",
  "fullName",
  "profileType",
  "position",
  "requestInsignia",
  "dateReceive",
  // "date",
  // "volumeNo",
  // "section",
  // "page",
  // "no",
  // "number",
]);

/** function เคลียร์ข้อมูลในฟอร์ม*/
function clearData() {
  receivedate.value = null;
  returndate.value = null;
  OrganazationId.value = "";
  roundNo.value = "";
  cardid.value = "";
  fullName.value = "";
  brand.value = "";
  reason.value = "";
  selected.value = [];
  keyword.value = "";
  rows.value = [];
  rowsMain.value = [];
}

/** function เรียกข้อมูลรายการเครื่องราช*/
async function fecthlistInsignia() {
  if (roundNo.value !== "" && roundNo.value !== null) {
    showLoader();
    let data = {
      insigniaTypeId: props.typeId,
      insigniaNoteId: roundNo.value,
      insigniaId: "",
    };
    await http
      .post(config.API.noteSearchList(), data)
      .then((res) => {
        rowsMain.value = res.data.result;
        rows.value = res.data.result;
        serchDataTable();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

/** function บันทึกการเพิ่มข้อมูล*/
async function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    if (props.action == "addData") {
      await http
        .post(config.API.insigniaManageBorrow(), {
          borrowDate: receivedate.value
            ? convertDateToAPI(receivedate.value)
            : "",
          insigniaNoteProfileId: insigniaNoteProfileId.value,
        })
        .then(async () => {
          await props.closeAndFecth();
          await success($q, "บันทึกข้อมูลสำเร็จ");
          closeDialog();
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    } else {
      await http
        .put(config.API.insigniaManageBorrowReturn(props.profileId), {
          returnDate: returndate.value
            ? convertDateToAPI(returndate.value)
            : "",
          returnOrganizationId: OrganazationId.value,
          returnReason: reason.value,
        })
        .then(async () => {
          await props.closeAndFecth();
          await success($q, "บันทึกข้อมูลสำเร็จ");
          closeDialog();
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    }
  });
}

/** function closePopup*/
function closeDialog() {
  clearData();
  props.close();
}

/** function reset วันที่คืน*/
function clearReturnDate() {
  returndate.value = null;
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 * @param name ชื่อ Selec
 */
function filterSelector(val: string, update: Function, name: string) {
  update(() => {
    const needle = val.toLowerCase();
    if (name === "filterOrgList") {
      OrganazationId.value = val ? "" : OrganazationId.value;
      filterOrgList.value = OrgList.value.filter(
        (v: any) => v.name.toLowerCase().indexOf(needle) > -1
      );
    }
    if (name === "filterSelectRoundOption") {
      roundNo.value = val ? "" : roundNo.value;
      filterSelectRound.value = selectRound.value.filter(
        (v: any) => v.name.toLowerCase().indexOf(needle) > -1
      );
    }
  });
}

function serchDataTable() {
  rows.value = onSearchDataTable(
    keyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

/** function setValue*/
function setValue() {
  filterSelectRound.value = props.filterSelectRoundOption;
  selectRound.value = props.selectRoundOption;
}

/**  function callback  เช็ค props ถ้าเปิด dialog ให้ดึงรายการข้อมูล*/
watch(props, () => {
  if (props.modal == true && props.roundId != "all") {
    roundNo.value = props.roundId;
    if (props.action === "editData") {
    } else {
      fecthlistInsignia();
      setValue();
    }
  }
});

watch(selected, () => {
  if (props.modal) {
    const data = selected.value[0];
    insigniaNoteProfileId.value = data ? data.id : "";
    fullName.value = data ? data.fullName : "";
    cardid.value = data ? data.citizenId : "";
    brand.value = data
      ? `${data.requestInsignia} (${data.requestInsigniaShortName})`
      : "";
  }
});

/** Hook*/
onMounted(() => {
  setValue();
});
</script>

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card
      :style="
        props.action === 'addData' ? 'min-width: 80%' : 'min-width: 900px'
      "
    >
      <q-form
        ref="myForm "
        greedy
        @submit.prevent
        @validation-success="onSubmit"
      >
        <DialogHeader tittle="ยืม-คืนเครื่องราชฯ" :close="closeDialog" />
        <q-separator />
        <q-card-section style="padding: 0px">
          <div
            class="row col-12 items-center q-col-gutter-x-xs q-col-gutter-y-xs"
          >
            <div v-if="props.action === 'addData'" class="row col-12">
              <div class="q-pa-md col-md-8 col-xs-12">
                <div class="col-12">
                  <div class="row col-12 q-col-gutter-sm">
                    <q-space />
                    <div class="row q-col-gutter-sm">
                      <q-input
                        standout
                        dense
                        v-model="keyword"
                        outlined
                        placeholder="ค้นหา"
                        @keydown.enter.prevent="serchDataTable"
                      >
                        <template v-slot:append>
                          <q-icon name="search" />
                        </template>
                      </q-input>

                      <q-select
                        v-model="visibleColumns"
                        multiple
                        outlined
                        dense
                        options-dense
                        :display-value="$q.lang.table.columns"
                        emit-value
                        map-options
                        :options="columns"
                        option-value="name"
                        style="min-width: 140px"
                      />
                    </div>
                  </div>
                </div>
                <div class="col-12 q-pt-sm">
                  <d-table
                    ref="table"
                    :columns="columns"
                    :rows="rows"
                    :visible-columns="visibleColumns"
                    row-key="id"
                    flat
                    bordered
                    :paging="true"
                    dense
                    :rows-per-page-options="[10, 25, 50, 100]"
                    selection="single"
                    v-model:selected="selected"
                  >
                    <template v-slot:header="props">
                      <q-tr :props="props">
                        <q-th auto-width></q-th>
                        <q-th
                          v-for="col in props.cols"
                          :key="col.name"
                          :props="props"
                        >
                          <span class="text-weight-medium">{{
                            col.label
                          }}</span>
                        </q-th>
                      </q-tr>
                    </template>

                    <template v-slot:body="props">
                      <q-tr :props="props" class="cursor-pointer">
                        <q-td>
                          <q-checkbox
                            keep-color
                            color="primary"
                            dense
                            v-model="props.selected"
                          />
                        </q-td>
                        <q-td
                          v-for="col in props.cols"
                          :key="col.name"
                          :props="props"
                        >
                          <div v-if="col.name === 'noNumber'">
                            {{ props.rowIndex + 1 }}
                          </div>
                          <div v-else>
                            {{ col.value ? col.value : "-" }}
                          </div>
                        </q-td>
                      </q-tr>
                    </template>
                  </d-table>
                </div>
              </div>
              <q-separator vertical />
              <div class="q-pa-md col">
                <div class="row q-col-gutter-sm">
                  <div class="col-12">
                    <q-select
                      class="inputgreen"
                      v-model="roundNo"
                      dense
                      outlined
                      lazy-rules
                      hide-bottom-space
                      :label="`${'รอบการขอเครื่องราชฯ'}`"
                      emit-value
                      map-options
                      use-input
                      option-label="name"
                      :options="filterSelectRound"
                      option-value="id"
                      :readonly="false"
                      :borderless="false"
                      style="min-width: 150px"
                      :rules="[(val:string) => !!val || 'กรุณาเลือกรอบการขอเครื่องราชฯ']"
                      @update:model-value="fecthlistInsignia()"
                      @filter="(inputValue:string,
                    doneFn:Function) => filterSelector(inputValue, doneFn,'filterSelectRoundOption'
                    ) "
                    />
                  </div>
                  <div class="col-12 q-mt-md text-weight-bold text-grey-7">
                    ข้อมูลผู้ยืม
                  </div>
                  <div class="col-xs-12 col-sm-6">
                    <q-input
                      :disable="roundNo == ''"
                      hide-bottom-space
                      outlined
                      readonly
                      v-model="cardid"
                      dense
                      lazy-rules
                      :rules="[
                  (val: string) => !!val || `${'กรุณากรอกเลขประจำตัวประชาชน'}`,
                  (val: string) =>
                    val.length >= 13 ||
                    `${'กรุณากรอกเลขประจำตัวประชาชนให้ครบ'}`,
                ]"
                      label="เลขประจำตัวประชาชน"
                      maxlength="13"
                      mask="#############"
                    />
                  </div>
                  <div class="col-xs-6 col-sm-6">
                    <q-input
                      readonly
                      hide-bottom-space
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="fullName"
                      :label="`${'ชื่อ-นามสกุล'}`"
                      :rules="[
                    (val:string) =>
                      !!val ||
                      'ชื่อ-นามสกุลต้องไม่ว่าง กรุณากรอกเลขประจำตัวประชาชนให้ถูกต้อง',
                  ]"
                    />
                  </div>

                  <div class="col-12 q-mt-md text-weight-bold text-grey-7">
                    รายละเอียดการยืมเครื่องราชฯ
                  </div>
                  <div class="col-xs-12 col-sm-6">
                    <q-input
                      :rules="[(val:string) => !!val || 'กรุณาเลือกเครื่องราชฯ']"
                      v-model="brand"
                      readonly
                      dense
                      outlined
                      lazy-rules
                      hide-bottom-space
                      :label="`${'เครื่องราชฯ'}`"
                    />
                  </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"
                    >
                      <template #year="{ year }">
                        {{ year + 543 }}
                      </template>
                      <template #year-overlay-value="{ value }">
                        {{ parseInt(value + 543) }}
                      </template>
                      <template #trigger>
                        <q-input
                          class="inputgreen"
                          dense
                          borderless
                          outlined
                          :rules="[(val:string) => !!val || 'กรุณาเลือกวันที่']"
                          hide-bottom-space
                          :model-value="
                            receivedate != null
                              ? date2Thai(receivedate)
                              : undefined
                          "
                          :label="`${'วันที่ยืม'}`"
                        >
                          <template v-if="receivedate" v-slot:append>
                            <q-icon
                              name="cancel"
                              @click.stop.prevent="receivedate = null"
                              class="cursor-pointer"
                            />
                          </template>
                        </q-input>
                      </template>
                    </datepicker>
                  </div>
                </div>
              </div>
            </div>

            <div
              class="row col-12 q-col-gutter-xs q-pa-md"
              v-if="props.action === 'editData'"
            >
              <div class="col-12 text-weight-bold text-grey-7">
                รายละเอียดการคืนเครื่องราชฯ
              </div>
              <div class="col-xs-12 col-sm-6">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="returndate"
                  :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
                      dense
                      borderless
                      outlined
                      :rules="[(val:string) => !!val || 'กรุณาเลือกวันที่คืน']"
                      hide-bottom-space
                      :model-value="
                        returndate != null ? date2Thai(returndate) : undefined
                      "
                      :label="`${'วันที่คืน'}`"
                      clearable
                      class="inputgreen"
                      @clear="clearReturnDate"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          color="primary"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <div class="col-12">
                <q-input
                  class="inputgreen"
                  type="textarea"
                  hide-bottom-space
                  dense
                  borderless
                  option-label="name"
                  option-value="id"
                  emit-value
                  map-options
                  lazy-rules
                  outlined
                  v-model="reason"
                  :label="`สาเหตุที่ส่งคืนเครื่องราชอิสริยาภรณ์`"
                />
              </div>
            </div>
          </div>
        </q-card-section>

        <q-separator />

        <q-card-actions align="right">
          <q-btn
            label="บันทึก"
            type="submit"
            color="public"
            :disable="selected.length === 0 && props.action === 'addData'"
          >
            <q-tooltip>บันทึก</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
