<script setup lang="ts">
import { ref, useAttrs } from "vue";
import { QTooltip, useQuasar } from "quasar";
import {
  checkPermission,
  checkPermissionList,
  checkPermissionCreate,
} from "@/utils/permissions";

import type { PropType } from "vue";
import type { optionData } from "@/modules/05_placement/interface/index/Main";

const $q = useQuasar();
const attrs = ref<any>(useAttrs());
const paging = ref<boolean>(true);
const table = ref<any>(null);
const filterRef = ref<any>(null);

const bmaOfficer = ref<string>("");
const bmaOfficerOption = ref<optionData[]>([
  { id: "", name: "ทั้งหมด" },
  { id: "OFFICER", name: "ขรก.กทม. สามัญ" },
  { id: "EXTERNAL", name: "บุคคลภายนอก" },
]);

const positionCandidate = ref<string>("");

const props = defineProps({
  inputfilter: String,
  inputvisible: Array,
  inputvisibleFilter: String,
  editvisible: Boolean,
  titleText: String,
  modaladdlist: Boolean,
  displayAdd: Boolean,
  optionsFilter: {
    type: Array,
    defualt: [],
  },
  boss: {
    type: Boolean,
    defualt: false,
  },
  positionCandidateData: {
    type: Array as PropType<optionData[]>,
    defualt: [],
  },
  saveNoDraft: {
    type: Boolean,
    defualt: false,
  },
  history: {
    type: Boolean,
    defualt: false,
  },
  paging: {
    type: Boolean,
    defualt: false,
  },
  nornmalData: {
    type: Boolean,
    defualt: false,
  },
  nextPageVisible: {
    type: Boolean,
    defualt: false,
  },
  publicData: {
    type: Boolean,
    defualt: true,
    required: false,
  },
  updateData: {
    type: Boolean,
    defualt: true,
    required: false,
  },
  publicNoBtn: {
    type: Boolean,
    defualt: false,
  },
  refreshBtn: {
    type: Boolean,
    defualt: false,
  },
  add: {
    type: Function,
    default: () => console.log("not function"),
  },
  onSearch: {
    type: Function,
    default: () => console.log("not function"),
  },
  edit: {
    type: Function,
    default: () => console.log("not function"),
  },
  save: {
    type: Function,
    default: () => console.log("not function"),
  },
  deleted: {
    type: Function,
    default: () => console.log("not function"),
  },
  cancel: {
    type: Function,
    default: () => console.log("not function"),
  },
  publish: {
    type: Function,
    default: () => console.log("not function"),
  },
  validate: {
    type: Function,
    default: () => console.log("not function"),
  },
  refresh: {
    type: Function,
    default: () => console.log("not function"),
  },
  containStatus: Boolean,
  roleAdmin: Boolean,
});

const positionCandidateOptions = ref<optionData[]>(
  props?.positionCandidateData || []
);

const pagination = ref({
  sortBy: "examNumber",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

/** ส่งค่า*/
const emit = defineEmits([
  "update:inputfilter",
  "update:inputvisible",
  "update:editvisible",
  "update:titleText",
  "update:inputvisibleFilter",
  "update:containfilter",
  "update-modaladdlist",
  "update-modaladdSendPerson",
  "update-newRows",
]);

function paginationLabel(start: string, end: string, total: string) {
  if (paging.value == true) return " " + start + "-" + end + " ใน " + total;
  else return start + "-" + end + " ใน " + total;
}

/**.value
 * update ค่าที่ค้นหา
 * @param value string
 */
function updateInput(value: any) {
  emit("update:inputfilter", value);
}

/** update ข้อมูลที่ เเสดง */
function updateVisible(value: any) {
  emit("update:inputvisible", value);
}

/**
 * แสดงสถานะบรรจุแล้ว
 * @param value true/false
 */
function updateContain(value: any) {
  emit("update:containfilter", value);
  onUpdateNewRows();
}

/** ส่งรายชื่อไปยังหน่วยงาน */
function updateModaladdlist() {
  emit("update-modaladdlist", true);
}

/** ส่งรายชื่อไปยังหน่วยงาน */
function openModalOrder() {
  emit("update-modaladdSendPerson", true);
}

/** ส่งรายชื่อไปยังหน่วยงาน */
function onUpdateNewRows() {
  emit("update-newRows", bmaOfficer.value, positionCandidate.value);
}

/**
 * ฟังชั่นฟิลเตอร์ input
 * @param val input
 * @param update Function quasar
 */
function filterSelector(val: string, update: Function) {
  update(() => {
    positionCandidateOptions.value =
      props?.positionCandidateData?.filter(
        (v: optionData) => v.name.indexOf(val) > -1
      ) || [];
  });
}
</script>

<template>
  <div class="q-pa-md q-gutter-sm row">
    <div class="col-12">
      <div class="row q-col-gutter-sm items-end">
        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-5">
          <div class="row q-col-gutter-sm">
            <div class="col-xs-12 col-sm-3 col-md-4 col-lg-4">
              <q-select
                outlined
                dense
                v-model="bmaOfficer"
                :options="bmaOfficerOption"
                emit-value
                map-options
                option-value="id"
                option-label="name"
                label="สถานภาพ"
                :clearable="bmaOfficer !== ''"
                @update:model-value="onUpdateNewRows"
                @clear="bmaOfficer = ''"
              >
              </q-select>
            </div>
            <div class="col-xs-12 col-sm-5 col-md-4 col-lg-6">
              <q-select
                outlined
                dense
                v-model="positionCandidate"
                :options="positionCandidateOptions"
                emit-value
                map-options
                option-value="id"
                option-label="name"
                label="ตำแหน่งที่สอบ"
                hide-selected
                fill-input
                use-input
                :clearable="positionCandidate !== ''"
                @clear="
                  (positionCandidate = ''),
                    (positionCandidateOptions = positionCandidateData || []),
                    onUpdateNewRows()
                "
                @update:model-value="onUpdateNewRows"
                @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn
                      ) "
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
            </div>
            <div class="col-xs-12 col-sm-3 col-md-4 col-lg-2">
              <div class="row q-col-gutter-sm">
                <div
                  class="col"
                  v-if="displayAdd && checkPermission($route)?.attrIsUpdate"
                >
                  <q-btn
                    flat
                    round
                    color="blue"
                    icon="mdi-account-arrow-right"
                    @click="updateModaladdlist"
                  >
                    <q-tooltip>ส่งรายชื่อไปยังหน่วยงาน</q-tooltip>
                  </q-btn>
                </div>
                <div
                  class="col"
                  v-if="
                    checkPermission($route)?.attrIsUpdate &&
                    checkPermissionList(['COMMAND']) &&
                    checkPermissionCreate('COMMAND')
                  "
                >
                  <q-btn
                    flat
                    round
                    color="primary"
                    icon="mdi-account-arrow-right"
                    @click="openModalOrder()"
                  >
                    <q-tooltip>ส่งไปออกคำสั่ง</q-tooltip>
                  </q-btn>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="col-xs-0 col-sm-0 col-md-0 col-lg-2"></div>

        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-5">
          <div class="row q-col-gutter-sm">
            <div class="col-xs-12 col-sm-4 col-md-4">
              <q-toggle
                class="toggle-expired-account"
                :model-value="containStatus"
                color="blue"
                label="แสดงสถานะบรรจุแล้ว"
                @update:model-value="updateContain"
              />
            </div>
            <div class="col-xs-12 col-sm-5 col-md-5">
              <q-input
                standout
                dense
                :model-value="inputfilter"
                ref="filterRef"
                @update:model-value="updateInput"
                outlined
                placeholder="ค้นหา"
                @keydown.enter.prevent="onUpdateNewRows"
              >
                <template v-slot:append> </template>
              </q-input>
            </div>
            <div class="col-xs-12 col-sm-3 col-md-3">
              <q-select
                :model-value="inputvisible"
                @update:model-value="updateVisible"
                :display-value="$q.lang.table.columns"
                multiple
                outlined
                dense
                :options="attrs.columns"
                options-dense
                option-value="name"
                map-options
                emit-value
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-12">
      <q-table
        ref="table"
        flat
        bordered
        class="custom-header-table"
        v-bind="attrs"
        virtual-scroll
        :virtual-scroll-sticky-size-start="48"
        dense
        :pagination-label="paginationLabel"
        v-model:pagination="pagination"
      >
        <template v-slot:pagination="scope">
          ทั้งหมด {{ attrs.rows.length.toLocaleString() }} รายการ
          <q-pagination
            v-model="pagination.page"
            active-color="primary"
            color="dark"
            :max="scope.pagesNumber"
            :max-pages="5"
            size="sm"
            boundary-links
            direction-links
          ></q-pagination>
        </template>
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th auto-width v-if="history == true" />
            <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 #body="props">
          <slot v-bind="props" name="columns"></slot>
        </template>
      </q-table>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.icon-color {
  color: #4154b3;
}

.custom-header-table {
  max-height: 64vh;

  .q-table tr:nth-child(odd) td {
    background: white;
  }

  .q-table tr:nth-child(even) td {
    background: #f8f8f8;
  }

  .q-table thead tr {
    background: #ecebeb;
  }

  .q-table thead tr th {
    position: sticky;
    z-index: 1;
  }

  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }

  .q-table thead tr:first-child th {
    top: 0;
  }
}
</style>
