<script setup lang="ts">
import { ref, useAttrs, watch } from "vue";

import { useInvestigateDisStore } from "@/modules/11_discipline/store/InvestigateDisStore";
import { checkPermission } from "@/utils/permissions";

const total = defineModel<number>("total", { required: true });
const totalList = defineModel<number>("totalList", { required: true });
const pagination = defineModel<any>("pagination", { required: true });

const dataInvestigateDis = useInvestigateDisStore();
const table = ref<any>(null);
const filterRef = ref<any>(null);
const attrs = ref<any>(useAttrs());
const paging = ref<boolean>(true);
const currentPage = ref<number>(1);
const statusFilter = ref<string>("NEW");
const option = ref<any[]>(dataInvestigateDis.statusOptions);
/** รับ props มาจากหน้าหลัก */
const props = defineProps({
  count: Number,
  pass: Number,
  notpass: Number,
  inputfilter: String,
  name: String,
  icon: String,
  inputvisible: Array,
  editvisible: Boolean,
  getSearch: Function,
  validate: {
    type: Function,
    default: () => console.log("not function"),
  },
  openEdit: {
    type: Function,
    default: () => console.log("not function"),
  },
  openDetail: {
    type: Function,
    default: () => console.log("not function"),
  },
  fetchListDisciplinary: {
    type: Function,
    default: () => console.log("not function"),
  },
  filterStatus: {
    type: Function,
    default: () => console.log("not function"),
  },
  nornmalData: {
    type: Boolean,
    defualt: true,
  },
  conclude: {
    type: Boolean,
    defualt: false,
  },
  filterTable: {
    type: String,
    default: "",
  },
  maxPage: {
    type: Number,
    require: true,
  },
  rowsPerPage: {
    type: Number,
    require: true,
  },
  page: {
    type: Number,
    require: true,
  },
  totalList: {
    type: Number,
    require: true,
  },
});

const emit = defineEmits([
  "update:inputfilter",
  "update:inputvisible",
  "update:editvisible",
  "update:pagination",
]);

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

function updateInput(value: string | number | null) {
  emit("update:inputfilter", value);
}

function updateVisible(value: []) {
  emit("update:inputvisible", value);
}

function resetFilter() {
  // reset ค่าที่ค้นหาเมื่อกดปุ่ม X ในกล่องค้นหา
  emit("update:inputfilter", "");
  filterRef.value.focus();
  props.fetchListDisciplinary?.();
}

function updateProp(newPagination: any, page: number) {
  // ส่ง event ไปยัง parent component เพื่ออัพเดทค่า props
  emit("update:pagination", newPagination, page);
}

function dataUpdate() {
  props.filterStatus(statusFilter.value);
}

function filterFn() {
  props.getSearch?.();
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 */
function filterOptionFn(val: string, update: Function) {
  update(() => {
    option.value = dataInvestigateDis.statusOptions.filter(
      (e: any) => e.name.search(val) !== -1
    );
  });
}

function updatePagination(newPagination: any) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}
</script>

<template>
  <div class="q-pb-sm row q-col-gutter-sm">
    <div class="col-xs-12 col-sm-4 col-md-4">
      <q-select
        v-model="statusFilter"
        label="สถานะ"
        dense
        outlined
        emit-value
        hide-selected
        fill-input
        map-options
        option-label="name"
        option-value="id"
        :options="option"
        @update:model-value="dataUpdate"
        use-input
        @filter="filterOptionFn"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
          </q-item>
        </template>
        <template v-if="statusFilter !== 'ALL'" v-slot:append>
          <q-icon
            name="cancel"
            @click.stop.prevent="
              (option = dataInvestigateDis.statusOptions),
                (statusFilter = 'ALL'),
                dataUpdate()
            "
            class="cursor-pointer"
          />
        </template>
      </q-select>
    </div>
    <q-space />
    <!-- ค้นหาข้อความใน table -->
    <q-input
      standout
      dense
      :model-value="inputfilter"
      ref="filterRef"
      @update:model-value="updateInput"
      outlined
      placeholder="ค้นหา"
      style="max-width: 200px"
      class="col-xs-12 col-sm-3 col-md-2"
      @keydown.enter.prevent="filterFn"
    >
      <template v-slot:append>
        <q-icon name="search" />
      </template>
    </q-input>
    <!-- แสดงคอลัมน์ใน table -->
    <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
      class="col-xs-12 col-sm-3 col-md-2 gt-xs"
      style="min-width: 140px"
    >
    </q-select>
  </div>
  <d-table
    ref="table"
    flat
    v-bind="attrs"
    virtual-scroll
    :virtual-scroll-sticky-size-start="48"
    dense
    :rows-per-page-options="[10, 25, 50, 100]"
    @update:pagination="updatePagination"
  >
    <template v-slot:pagination="scope">
      ทั้งหมด {{ total }} รายการ
      <q-pagination
        v-model="pagination.page"
        active-color="primary"
        color="dark"
        :max="Number(totalList)"
        size="sm"
        boundary-links
        direction-links
        :max-pages="5"
        @update:model-value="props.fetchListDisciplinary?.()"
      ></q-pagination>
    </template>
    <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" v-html="col.label" />
        </q-th>
      </q-tr>
    </template>
    <template v-slot:body="props">
      <q-tr :props="props">
        <q-td auto-width>
          <q-btn
            v-if="checkPermission($route)?.attrIsGet"
            flat
            dense
            round
            icon="mdi-eye"
            color="info"
            @click="openDetail(props.row.id)"
          >
            <q-tooltip>รายละเอียด</q-tooltip>
          </q-btn>
          <q-btn
            v-if="
              checkPermission($route)?.attrIsUpdate &&
              checkPermission($route)?.attrIsGet
            "
            flat
            dense
            round
            icon="edit"
            color="edit"
            @click="openEdit(props.row.id)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
        <q-td v-for="col in props.cols" :key="col.name" :props="props">
          <div v-if="col.name == 'no'">
            {{
              (currentPage - 1) * Number(pagination.rowsPerPage) +
              props.rowIndex +
              1
            }}
          </div>
          <div v-else-if="col.name === 'title'" class="table_ellipsis">
            {{ props.row.title }}
          </div>
          <div v-else>
            {{ col.value }}
          </div>
        </q-td>
      </q-tr>
    </template>
  </d-table>
</template>

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

.custom-table2 {
  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;
  }

  .q-table td:nth-of-type(2) {
    z-index: 3 !important;
  }

  .q-table th:nth-of-type(2),
  .q-table td:nth-of-type(2) {
    position: sticky;
    left: 0;
    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>
