<script setup lang="ts">
import { ref, watch, reactive } from "vue";
import Header from "@/components/DialogHeader.vue";
import type {
  DataOption,
  FormFilter,
  NewPagination,
} from "@/modules/15_development/interface/index/Main";
import { useDevelopmentDataStoreHistory } from "@/modules/15_development/store/developmentStoreHistory";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";

const props = defineProps({
  upDate: { type: Function },
});

const year = ref<string>("");
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  dialogConfirm,
  messageError,
  dialogMessageNotify,
  showLoader,
  hideLoader,
} = mixin;
const store = useDevelopmentDataStoreHistory();

const modal = defineModel<boolean>("modal", { required: true });

const maxPage = ref<number>(1);
const pagination = ref({
  page: 1,
  rowsPerPage: 20,
});

const formFilter = reactive<FormFilter>({
  page: 1,
  pageSize: 20,
  keyword: "",
  type: "",
  year: new Date().getFullYear(),
  posType: "",
  posLevel: "",
  retireYear: "",
  rangeYear: { min: 0, max: 60 },
  isShowRetire: null,
  isProbation: null,
});

const selected = ref<any[]>([]);
const search = ref<string>("projectName");
const inputSearch = ref<string>("");

const projectOp = ref<DataOption[]>([
  {
    id: "projectName",
    name: "ชื่อโครงการ",
  },
  {
    id: "year",
    name: "ปีงบประมาณ",
  },
  // {
  //   id: "ID3",
  //   name: "ชื่อหน่วยงานที่รับผิดชอบ",
  // },
]);

/** save ข้อมูล */
function onSubmit() {
  if (selected.value?.length == 0) {
    dialogMessageNotify($q, `กรุณาเลือก 1 รายการ`);
  } else {
    dialogConfirm($q, () => {
      const data = selected.value[0];
      const body = {
        id:data.id,
        year:data.year,
        project:data.project,
        dateStart:data.dateStart,
        dateEnd:data.dateEnd,
        totalDate:data.totalDate,
        addressAcademic:data.addressAcademic,
        topicAcademic:data.topicAcademic,
      };
      props.upDate?.(body)
      closeDialog();
    });
  }
}

/** ปิด dialog */
function closeDialog() {
  modal.value = false;
  store.rows = [];
  selected.value = [];
}

/** class */
function getClass() {
  return "inputgreen";
}
function searchFilter() {
  let queryParams: any = {
    page: formFilter.page,
    pageSize: formFilter.pageSize,
    searchField: search.value,
    searchKeyword: search.value == "year" ? year.value : inputSearch.value,
  };
  showLoader();
  http
    .get(config.API.developmentProjectSearch(), { params: queryParams })
    .then((res) => {
      const data = res.data.result.data;
      maxPage.value = Math.ceil(res.data.result.total / formFilter.pageSize);
      store.rows = data.map((item: any) => ({
        id: item.id ? item.id : null,
        year: item.year ? item.year : null,
        project: item.projectName ? item.projectName : null,
        dateStart: item.dateStart ? item.dateStart : null,
        dateEnd: item.dateEnd ? item.dateEnd : null,
        totalDate: item.totalDate ? item.totalDate : null,
        addressAcademic: item.addressAcademic ? item.addressAcademic : null,
        topicAcademic: item.topicAcademic ? item.topicAcademic : null,
      }));
    })
    .catch((e) => {
      messageError($q, e``);
    })
    .finally(() => {
      hideLoader();
    });
}

function updatePage(val:number){
  formFilter.page = val;
  searchFilter();
}

function updatePageSize(newPagination: NewPagination) {
  formFilter.page = 1;
  formFilter.pageSize = newPagination.rowsPerPage;
}

watch(
  () => formFilter.pageSize,
  () => {
    searchFilter();
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 60%">
      <Header :tittle="'เลือกโครงการ'" :close="closeDialog" />
      <q-separator />

      <q-card-section>
        <div class="row q-col-gutter-x-sm">
          <div class="col-2">
            <q-select
              dense
              outlined
              label="ค้นหาจาก"
              v-model="search"
              option-label="name"
              option-value="id"
              :options="projectOp"
              map-options
              emit-value
              :class="getClass()"
            />
          </div>
          <div v-if="search == 'year'" class="col-3">
            <datepicker
              menu-class-name="modalfix"
              v-model="year"
              class="col-2"
              :locale="'th'"
              autoApply
              year-picker
              :enableTimePicker="false"
            >
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input
                  dense
                  lazy-rules
                  outlined
                  :model-value="year === '' ? null : Number(year) + 543"
                  :label="`${'ปีงบประมาณ'}`"
                >
                  <template v-if="year" v-slot:append>
                    <q-icon
                      name="cancel"
                      @click.stop.prevent="year = ''"
                      class="cursor-pointer"
                    />
                  </template>
                  <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 v-else class="col-8">
            <q-input
              dense
              outlined
              label="ค้นหา"
              v-model="inputSearch"
              :class="getClass()"
            />
          </div>
          <q-space v-if="search == 'year'" />
          <div class="col-2">
            <q-btn
              label="ค้นหา"
              class="full-width"
              unelevated
              color="teal"
              @click="searchFilter()"
            >
            </q-btn>
          </div>
        </div>
        <div class="q-mt-sm">
          <d-table
            selection="single"
            v-model:selected="selected"
            for="table"
            ref="table"
            :columns="store.columns"
            :rows="store.rows"
            row-key="id"
            flat
            bordered
            dense
            class="custom-header-table"
            :visible-columns="store.visibleColumns"
            v-model:pagination="pagination"
            :rows-per-page-options="[20, 25, 50, 100]"
            @update:pagination="updatePageSize"
          >
            <template v-slot:pagination="scope">
              <q-pagination
                v-model="formFilter.page"
                active-color="primary"
                color="dark"
                :max="Number(maxPage)"
                :max-pages="5"
                size="sm"
                boundary-links
                direction-links
                @update:model-value="updatePage"
              ></q-pagination>
            </template>
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th class="text-center"> </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 class="text-center">
                  <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 == 'year'">
                    {{ col.value ? col.value + 543 : "-" }}
                  </div>
                  <div v-else class="table_ellipsis">
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </q-card-section>
      <q-separator />

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn
          label="บันทึก"
          color="secondary"
          type="submit"
          @click="onSubmit()"
          ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
        >
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
