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

import { checkPermission } from "@/utils/permissions";
import { useInsigniaDataStore } from "@/modules/07_insignia/store";
import { useCounterMixin } from "@/stores/mixin";

/** import Type*/
import type { QTableProps } from "quasar";
import type { OptionData } from "@/modules/07_insignia/interface/index/Main";

/** import components*/
import DialogInformation from "@/components/Dialogs/Information.vue";
import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";

const mixin = useCounterMixin();
const { onSearchDataTable } = mixin;
/** useStore*/
const DataStore = useInsigniaDataStore();

const props = defineProps({
  tab: {
    type: String,
  },
  roundId: {
    type: String,
  },
  fecthInsigniaAll: {
    type: Function,
  },
  fecthInsigniaByOc: {
    type: Function,
  },
});

const typeinsigniaOptions = ref<OptionData[]>(DataStore.typeinsigniaOptions); //ประเภทเครื่องราย
const employeeClassOps = ref<OptionData[]>(DataStore.employeeClassOps); //ประเภทข้ารายกาช
const filterOrganizationOP = ref<OptionData[]>([]); // //หน่วยงาน
const organization = ref<string>("1");
const isDeputy = ref<boolean>(false); //เลือกสำนักปลัดหรือไม่

/** หัวตาราง*/
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  // {
  //   name: "employeeType",
  //   align: "left",
  //   label: "ประเภทตำแหน่ง",
  //   sortable: true,
  //   field: "employeeType",
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "level",
    align: "left",
    label: "ประเภท/ระดับ",
    sortable: true,
    field: "level",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "salary",
    align: "left",
    label: "เงินเดือน",
    sortable: true,
    field: "salary",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "insigniaType",
    align: "left",
    label: "ชั้นตราเครื่องราชฯ ปัจจุบัน",
    sortable: true,
    field: "insigniaType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "insigniaSend",
    align: "left",
    label: "ชั้นตราเครื่องราชฯ ที่ยื่นขอ",
    sortable: true,
    field: "insigniaSend",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "insigniaLevel",
    align: "left",
    label: "ชั้นเครื่องราชฯ",
    sortable: true,
    field: "insigniaLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateSend",
    align: "left",
    label: "วันที่ยื่นขอ",
    sortable: true,
    field: "dateSend",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "citizenId",
  "name",
  "employeeType",
  "position",
  "level",
  "salary",
  "insigniaType",
  "insigniaSend",
  "insigniaLevel",
  // "dateSend",
]);

/** function เลือกหน่วยงาน */
async function changtypeOc() {
  if (props.fecthInsigniaByOc) {
    isDeputy.value = await (DataStore.optionsTypeOc.findIndex(
      (v: OptionData) => v.id === organization.value && v.isDeputy === true
    ) > -1);

    props.fecthInsigniaByOc(
      props.roundId,
      organization.value,
      "officer",
      props.tab,
      isDeputy.value
    );
  }
  DataStore.typeOc = organization.value;
}

const modalPersonal = ref<boolean>(false);
const personId = ref<string>("");
const profileType = ref<string>("");
/**
 *  function redirect ทะเบียนประวัติิ
 * @param id profileId
 */
function nextPage(id: string, type: string) {
  modalPersonal.value = true;
  personId.value = id;
  profileType.value = type;
}

function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}

/** ข้อมูล Table*/
const filterKeyword = ref<string>("");
const filterRef = ref<any>(null);

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

/** หมายเหตุ*/
const dialogNote = ref<boolean>(false);
const note = ref<string>("");
const noteTitle = ref<string>("");

/**
 * function openPopup แสดง หมายเหตุ
 * @param row รายละเอียดข้อมูล
 */
function showNote(row: any) {
  note.value = row.requestNote;
  noteTitle.value = "เหตุผลการขาดคุณสมบัติ " + " " + row.name;
  dialogNote.value = true;
}

/** function closePopup หมายเหตุ*/
function closeReson() {
  dialogNote.value = false;
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update funtion
 * @param name ชื่อ selec
 */
function filterSelector(val: string, update: Function, name: string) {
  update(() => {
    const needle = val.toLowerCase();
    if (name === "typeinsigniaOptions") {
      typeinsigniaOptions.value = DataStore.typeinsigniaOptions.filter(
        (v: OptionData) => v.name.toLowerCase().indexOf(needle) > -1
      );
    } else if (name === "employeeClassOps") {
      employeeClassOps.value = DataStore.employeeClassOps.filter(
        (v: OptionData) => v.name.toLowerCase().indexOf(needle) > -1
      );
    } else if (name === "filterOrganizationOP") {
      filterOrganizationOP.value = DataStore.optionsTypeOc.filter(
        (v: OptionData) => v.name.toLowerCase().indexOf(needle) > -1
      );
    }
  });
}

/**
 * function clearfilter เครื่องราช
 * @param name ชื่อ selec
 */
function clearInsigniaFilters(name: string) {
  if (name === "typeinsigniaOptions") {
    DataStore.typeinsignia = "all";
    typeinsigniaOptions.value = DataStore.typeinsigniaOptions;
  }
  // else if (name === "employeeClassOps") {
  //   DataStore.employeeClass = "all";
  //   employeeClassOps.value = DataStore.employeeClassOps;
  // }
}

function onSearch() {
  DataStore.rows = onSearchDataTable(
    filterKeyword.value,
    DataStore.rowsData,
    columns.value ? columns.value : []
  );
}

watch(
  () => DataStore.typeOc,
  async () => {
    filterOrganizationOP.value = DataStore.optionsTypeOc;
    organization.value = DataStore.typeOc;
    DataStore.selectOrganization = DataStore.typeOc;
  }
);

/** Hook*/
onMounted(async () => {
  filterOrganizationOP.value = DataStore.optionsTypeOc;
  organization.value = DataStore.typeOc;
  DataStore.selectOrganization = DataStore.typeOc;
  if (organization.value !== "" || organization.value !== undefined) {
    if (props.fecthInsigniaByOc) {
      isDeputy.value = await (DataStore.optionsTypeOc.findIndex(
        (v: OptionData) => v.id === organization.value && v.isDeputy === true
      ) > -1);

      props.fecthInsigniaByOc(
        props.roundId,
        organization.value,
        "officer",
        props.tab,
        isDeputy.value
      );
      DataStore.mainTab = props.tab;
    }
  }
});
</script>

<template>
  <div class="col-12 row q-pa-md">
    <div class="row col-12">
      <div class="row col-12 q-col-gutter-sm">
        <q-select
          v-if="DataStore.isOfficer"
          v-model="organization"
          label="หน่วยงาน"
          dense
          emit-value
          map-options
          :options="filterOrganizationOP"
          option-value="id"
          option-label="name"
          lazy-rules
          use-input
          hide-bottom-space
          :readonly="false"
          :borderless="false"
          :outlined="true"
          :hide-dropdown-icon="false"
          style="width: 400px"
          @update:model-value="changtypeOc"
          @filter="(inputValue: string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'filterOrganizationOP'
                      ) "
        />
        <q-space />

        <q-input
          standout
          dense
          v-model="filterKeyword"
          ref="filterRef"
          outlined
          placeholder="ค้นหา"
          @keydown.enter.prevent="onSearch"
        >
          <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>
      <q-card bordered class="q-pa-sm col-12 bg-grey-1 q-mt-sm">
        <div class="row col-12 q-col-gutter-sm">
          <q-select
            v-model="DataStore.typeinsignia"
            label="ประเภทเครื่องราชฯ ที่ยืนขอ"
            dense
            emit-value
            map-options
            :options="typeinsigniaOptions"
            option-value="id"
            option-label="name"
            lazy-rules
            hide-bottom-space
            use-input
            :readonly="false"
            :borderless="false"
            :outlined="true"
            :hide-dropdown-icon="false"
            style="min-width: 320px"
            @update:model-value="
              DataStore.searchDataTable(
                DataStore.typeinsignia,
                DataStore.employeeClass
              )
            "
            @filter="(inputValue: string,
                        doneFn:Function) => filterSelector(inputValue, doneFn,'typeinsigniaOptions'
                        ) "
          >
            <template v-if="DataStore.typeinsignia !== 'all'" v-slot:append>
              <q-icon
                name="cancel"
                @click.stop.prevent="
                  clearInsigniaFilters('typeinsigniaOptions'),
                    DataStore.searchDataTable(
                      DataStore.typeinsignia,
                      DataStore.employeeClass
                    )
                "
                class="cursor-pointer"
              />
            </template>
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
              </q-item>
            </template>
          </q-select>
          <!-- <q-select
            v-model="DataStore.employeeClass"
            dense
            outlined
            lazy-rules
            hide-bottom-space
            :label="`${'ประเภทตำแหน่ง'}`"
            emit-value
            use-input
            map-options
            option-label="name"
            :options="employeeClassOps"
            option-value="id"
            :readonly="false"
            :borderless="false"
            style="width: 300px"
            @update:model-value="
              DataStore.searchDataTable(
                DataStore.typeinsignia,
                DataStore.employeeClass
              )
            "
            @filter="(inputValue: string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'employeeClassOps'
                      ) "
          >
            <template v-if="DataStore.employeeClass !== 'all'" v-slot:append>
              <q-icon
                name="cancel"
                @click.stop.prevent="
                  clearInsigniaFilters('employeeClassOps'),
                    DataStore.searchDataTable(
                      DataStore.typeinsignia,
                      DataStore.employeeClass
                    )
                "
                class="cursor-pointer"
              />
            </template>
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
              </q-item>
            </template>
          </q-select> -->
        </div>
      </q-card>
      <div class="col-12 q-pt-sm">
        <d-table
          ref="table"
          :columns="columns"
          :rows="DataStore.rows"
          row-key="name"
          flat
          bordered
          :paging="true"
          dense
          class="custom-header-table"
          :visible-columns="visibleColumns"
          v-model:pagination="pagination"
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th auto-width />
              <q-th v-for="col in props.cols" :key="col.name" :props="props">
                <span class="text-weight-medium">{{ col.label }}</span>
              </q-th>
              <q-th auto-width />
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td auto-width>
                <q-btn
                  v-if="checkPermission($route)?.attrIsGet"
                  dense
                  flat
                  round
                  color="info"
                  @click="
                    nextPage(props.row.profileId, props.row.employeeClass)
                  "
                  icon="mdi-eye"
                >
                  <q-tooltip>ดูข้อมูลทะเบียนประวัติ</q-tooltip>
                </q-btn>
              </q-td>
              <q-td key="no" :props="props">
                {{ props.rowIndex + 1 }}
              </q-td>
              <q-td key="citizenId" :props="props">
                {{ props.row.citizenId }}
              </q-td>
              <q-td key="name" :props="props">
                {{ props.row.name }}
              </q-td>
              <q-td key="employeeType" :props="props">
                {{ props.row.employeeType }}
              </q-td>
              <q-td key="position" :props="props">
                {{ props.row.position }}
              </q-td>
              <q-td key="level" :props="props">
                {{ props.row.level }}
              </q-td>
              <q-td key="salary" :props="props">
                {{ Number(props.row.salary).toLocaleString() }}
              </q-td>

              <q-td key="insigniaType" :props="props">
                {{ props.row.insigniaType }}
              </q-td>
              <q-td key="insigniaSend" :props="props">
                {{ props.row.insigniaSend }}
              </q-td>
              <q-td key="insigniaLevel" :props="props">
                {{ props.row.insigniaLevel }}
              </q-td>
              <q-td auto-width>
                <q-btn
                  v-if="
                    props.row.requestNote != null &&
                    checkPermission($route)?.attrIsGet
                  "
                  dense
                  flat
                  round
                  color="blue"
                  @click.stop="showNote(props.row)"
                  icon="mdi-information-outline"
                >
                  <q-tooltip>เหตุผลการขาดคุณสมบัติ</q-tooltip>
                </q-btn>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </div>
    </div>
  </div>

  <DialogInformation
    :modal="dialogNote"
    :title="noteTitle"
    :desc="note"
    :click-close="closeReson"
  />

  <PopupPersonal
    :modal="modalPersonal"
    :id="personId"
    :type="profileType"
    @update:modal="updatemodalPersonal"
  />
</template>
