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

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

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 mixin = useCounterMixin();
const { dialogConfirm } = mixin;

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

const rows = 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,
  }));
});

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

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

/** คอลัมน์ */
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "center",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    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",
  "name",
  "position",
  "positionLevel",
  "posNo",
  "organization",
  "status",
]);

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

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

/** ฟังก์ชั่นยืนยันและส่งคนไปสร้างคำสั่ง */
function saveOrder() {
  dialogConfirm(
    $q,
    async () => {
      modalCommand.value = true;
      modal.value = false;
    },
    "ยืนยันส่งไปออกคำสั่ง",
    "ต้องการยืนยันส่งไปออกคำสั่งใช่หรือไม่?"
  );
}

/**
 * เมื่อ props.modal เป็น true
 * กำหนดให้  selected เป็นค่าว่างและกำหนด filter ประเภทตำแหน่งตามประเภทการสอบ
 */
watch(
  () => modal.value,
  async () => {
    if (modal.value === true) {
      rows.value = props.rows ? props.rows : [];
      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:any,
                    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
            debounce="300"
            v-model="filterKeyword"
            placeholder="ค้นหา"
            style="width: 200px; max-width: auto"
          >
            <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"
          :filter="filterKeyword.trim()"
          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"
              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"
                  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>
                  {{ 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 : []"
  />
</template>
