<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { checkPermission } from "@/utils/permissions";

/** import Type*/
import type { QTableProps } from "quasar";

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

/** import Stores */
import { useInsigniaDataStore } from "@/modules/07_insignia/store";
import { useroleUserDataStore } from "@/stores/roleUser";
/** useStore*/
const roleDataStore = useroleUserDataStore();
const DataStore = useInsigniaDataStore();

const router = useRouter();

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

const organization = ref<string>("1");
const organizationOptions = ref<any>([{ id: "1", name: "ทั้งหมด" }]);
const filterOrganizationOP = ref<any>([]);
const typeinsigniaOptions = ref<any>(DataStore.typeinsigniaOptions);
const employeeClassOps = ref<any>(DataStore.employeeClassOps);

/** หัวตาราง*/
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",
]);

/** function เลือกหน่วยงาน */
function changtypeOc() {
  if (organization.value !== null) {
    props.fecthInsigniaByOc?.(
      props.roundId,
      organization.value,
      "officer",
      props.tab
    );
  }
  DataStore.typeOc = organization.value;
}

const modalPersonal = ref<boolean>(false);
const personId = ref<string>("");

/**
 *  function redirect ทะเบียนประวัติิ
 * @param id profileId
 */
function nextPage(id: string) {
  modalPersonal.value = true;
  personId.value = id;
  // router.push(`/registry-officer/${id}`);
}

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

/** filter table*/
const filterKeyword = ref<string>("");
const filterRef = ref<any>(null);
const resetFilter = () => {
  filterKeyword.value = "";
  filterRef.value.focus();
};
const pagination = ref({
  sortBy: "name",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

/** หมายเหตุ*/
const dialogNote = ref<boolean>(false);
const dialogTitle = ref<string>("");
const dialogDesc = ref<string>("");
/**
 * function openPopup แสดง หมายเหตุ
 * @param name ชื่อ
 * @param requestNote หมายเหตุ
 */
function showReson(name: string, requestNote: string) {
  dialogTitle.value = "เหตุผลการไม่ยื่นขอ " + name;
  dialogDesc.value = requestNote;
  dialogNote.value = true;
}

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

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

/*** Hook*/
onMounted(async () => {
  organizationOptions.value = await DataStore.optionsTypeOc;
  organization.value = await DataStore.typeOc;
  if (organization.value !== "" || organization.value !== undefined) {
    if (props.fecthInsigniaByOc) {
      await props.fecthInsigniaByOc(
        props.roundId,
        organization.value,
        "officer",
        props.tab
      );
      DataStore.mainTab = props.tab;
    }
  }
  filterOrganizationOP.value = organizationOptions.value;
});
</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="roleDataStore.adminRole"
          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:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'filterOrganizationOP'
                      ) "
        />
        <q-space />

        <q-input
          class="col-xs-12 col-sm-3 col-md-2"
          standout
          dense
          v-model="filterKeyword"
          ref="filterRef"
          outlined
          debounce="300"
          placeholder="ค้นหา"
        >
          <template v-slot:append>
            <q-icon v-if="filterKeyword == ''" name="search" />
            <q-icon
              v-if="filterKeyword !== ''"
              name="clear"
              class="cursor-pointer"
              @click="resetFilter"
            />
          </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"
          options-cover
          style="min-width: 150px"
          class="col-xs-12 col-sm-3 col-md-2"
        />
      </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:any,
                      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:any,
                    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"
          :filter="filterKeyword"
          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)"
                  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.pervent="
                    showReson(props.row.name, props.row.requestNote)
                  "
                  icon="mdi-information-outline"
                >
                  <q-tooltip>เหตุผลการไม่ยื่นขอ</q-tooltip>
                </q-btn>
              </q-td>
            </q-tr>
          </template>
        </d-table>

        <DialogInformation
          :modal="dialogNote"
          :title="dialogTitle"
          :desc="dialogDesc"
          :click-close="closeReson"
        />
      </div>
    </div>
  </div>

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