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

import { useCounterMixin } from "@/stores/mixin";
import { useCommandMainStore } from "@/modules/18_command/store/Main";
import { useDisciplineSuspendStore } from "@/modules/11_discipline/store/SuspendStore";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableProps } from "quasar";
import type { dataType } from "@/modules/11_discipline/interface/response/suspend";
import type { ListCommand } from "@/modules/18_command/interface/index/Main";

import DialogHeader from "@/components/DialogHeader.vue";
import DialogCreateCommand from "@/modules/18_command/components/DialogCreateCommand.vue";

/** use */
const $q = useQuasar();
const storeCommand = useCommandMainStore();
const storeSuspend = useDisciplineSuspendStore();
const { onSearchDataTable, showLoader, hideLoader, messageError, date2Thai } =
  useCounterMixin();

const modal = defineModel<boolean>("modal", { required: true });
const modalCommand = ref<boolean>(false); // ตัวแปร popup สร้างคำสั่ง

const rows = ref<dataType[]>([]);
const rowsMain = ref<dataType[]>([]);
const selected = ref<dataType[]>([]);
const dataMapToSend = computed(() => {
  return selected.value.map((i: any) => ({
    id: i.id,
    profileId: i.profileId,
    prefix: i.prefix,
    firstName: i.firstName,
    lastName: i.lastName,
    citizenId: i.citizenId,
    position: i.position,
    posType: i.positionType,
    posLevel: i.positionLevel,
  }));
});

const commandType = ref<string>(""); //ตัวแปรเก็บคำสั่งที่เลือก
const commandOp = ref<ListCommand[]>([]);
const listCommand = ref<ListCommand[]>([]); // เก็บคำสั่งทั้งหมด

const filterKeyword = ref<string>("");
/** props*/
const props = defineProps<{
  rows: dataType[];
  fetchData: Function;
  employeeClass: string;
}>();

/** คอลัมน์ */
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "center",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "profileType",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: true,
    field: "profileType",
    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: "position",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionLevel",
    align: "left",
    label: "ระดับ",
    sortable: true,
    field: "positionLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organization",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "status",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/** คอลัมน์ที่แสดง */
const visibleColumns = ref<string[]>([
  "no",
  "profileType",
  "name",
  "position",
  "positionLevel",
  "posNo",
  "organization",
  "status",
]);

async function fetchListData() {
  showLoader();
  const paramsNew = {
    keyword: filterKeyword.value.trim(),
    profileType: props.employeeClass,
    status: "PENDING",
  };

  await http
    .get(config.API.suspendMain, { params: paramsNew })
    .then(async (res) => {
      const result = await res.data.result.data;
      const mapData = result.map((item: dataType) => {
        return {
          id: item.id,
          profileId: item.profileId,
          citizenId: item.citizenId,
          name: `${item.prefix}${item.firstName} ${item.lastName}`,
          prefix: item.prefix,
          firstName: item.firstName,
          profileType: item.profileType,
          lastName: item.lastName,
          organization: item.organization,
          position: item.position,
          posNo: item.posNo,
          positionType: item.positionType,
          positionLevel: item.positionLevel,
          salary: item.salary,
          status: storeSuspend.statusTothai(item.status),
          statusEn: item.status,
          descriptionSuspend: item.descriptionSuspend,
          dateTotal:
            item.startDateSuspend && item.endDateSuspend
              ? `${date2Thai(item.startDateSuspend)} - ${date2Thai(
                  item.endDateSuspend
                )}`
              : "-",
          startDateSuspend: item.startDateSuspend,
          endDateSuspend: item.endDateSuspend,
          title: item.title,
          offenseDetails: item.offenseDetails,
          disciplinaryFaultLevel: item.disciplinaryFaultLevel,
          disciplinaryCaseFault: item.disciplinaryCaseFault,
        };
      });
      rows.value = mapData;
      rowsMain.value = mapData;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function closeModal() {
  modal.value = false;
  commandType.value = "";
  filterKeyword.value = "";
}

/**
 * ฟิลเตอร์ คำสั่ง
 * @param val ค่าจาก Input
 * @param update Funtion quasar
 */
function filterSelector(val: string, update: Function) {
  update(() => {
    commandOp.value = listCommand.value.filter(
      (v: any) => v.name.indexOf(val) > -1
    );
  });
}

/** ฟังก์ชั่นยืนยันและส่งคนไปสร้างคำสั่ง */
function saveOrder() {
  modalCommand.value = true;
  modal.value = false;
}

function serchDataTable() {
  rows.value = onSearchDataTable(
    filterKeyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

function convertType(val: string) {
  switch (val) {
    case "OFFICER":
      return "ข้าราชการ กทม. สามัญ";
    case "EMPLOYEE":
      return "ลูกจ้างประจำ กทม.";
  }
}

/**
 * เมื่อ props.modal เป็น true
 * กำหนดให้  selected เป็นค่าว่างและกำหนด filter ประเภทตำแหน่งตามประเภทการสอบ
 */
watch(
  () => modal.value,
  async () => {
    if (modal.value === true) {
      await fetchListData();
      selected.value = [];
      const data = await storeCommand.getCommandTypes();
      listCommand.value = data.filter(
        (v: any) => v.code == "C-PM-25" || v.code == "C-PM-26"
      );
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 1200px; max-width: 80vw">
      <DialogHeader tittle="ส่งไปออกคำสั่ง" :close="closeModal" />
      <q-separator />
      <q-card-section class="q-pa-md">
        <div class="row q-mb-sm">
          <q-select
            v-model="commandType"
            dense
            outlined
            label="ประเภทคำสั่ง"
            :options="commandOp"
            option-label="name"
            option-value="code"
            emit-value
            hide-selected
            fill-input
            map-options
            use-input
            style="width: 350px; max-width: auto"
            @update:model-value="selected = []"
            @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
          >
          <q-space />

          <q-input
            borderless
            outlined
            dense
            v-model="filterKeyword"
            placeholder="ค้นหา"
            style="width: 200px; max-width: auto"
            @keydown.enter.prevent="serchDataTable"
          >
            <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"
            class="gt-xs q-ml-sm"
          />
        </div>

        <d-table
          :columns="columns"
          :rows="rows"
          row-key="id"
          :visible-columns="visibleColumns"
          selection="multiple"
          v-model:selected="selected"
        >
          <template v-slot:header-selection="scope">
            <q-checkbox
              keep-color
              color="primary"
              dense
              :disable="commandType ? false : true"
              v-model="scope.selected"
            />
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td>
                <q-checkbox
                  keep-color
                  color="primary"
                  dense
                  :disable="commandType ? false : true"
                  v-model="props.selected"
                />
              </q-td>
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                <div v-if="col.name == 'no'">
                  {{ props.rowIndex + 1 }}
                </div>
                <div v-else-if="col.name === 'profileType'">
                  {{
                    props.row.profileType
                      ? convertType(props.row.profileType.toUpperCase())
                      : "-"
                  }}
                </div>
                <div
                  v-else-if="col.name == 'organization'"
                  class="text-html"
                  style="width: 200px"
                >
                  {{ props.row ? col.value : "-" }}
                </div>
                <div v-else>
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn
          label="ส่งไปออกคำสั่ง"
          @click="saveOrder"
          :disable="selected.length === 0"
          color="public"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <!-- dialog สร้างคำสั่ง -->
  <DialogCreateCommand
    v-model:modal="modalCommand"
    :command-type-code="commandType"
    :persons="selected ? dataMapToSend : []"
    :fetch-data="props.fetchData"
  />
</template>
