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

import avatar from "@/assets/avatar_user.jpg";

import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useCommandMainStore } from "@/modules/18_command/store/Main";
import { usePlacementDataStore } from "@/modules/05_placement/store";

import type { QTableProps } from "quasar";
import type { ResponseData } from "@/modules/05_placement/interface/response/Transfer";
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";
import { options } from "@fullcalendar/core/preact";

const $q = useQuasar();
const mixin = useCounterMixin();
const route = useRoute();
const DataStore = usePlacementDataStore();
const storeCommand = useCommandMainStore();
const { dialogConfirm, dateText } = mixin;

const modal = defineModel<boolean>("modal", { required: true });
/** props */
const props = defineProps({
  fetchData: Function,
  rows: Array,
});

const examId = route.params.examId;
const rows = ref<any[]>([]);
const commandType = ref<string>("");
const commandOp = ref<ListCommand[]>([]);
const listCommand = ref<ListCommand[]>([]); // เก็บคำสั่งทั้งหมด
const modalCommand = ref<boolean>(false); //เปิด-ปิด modal สร้างคำสั่ง

//Table
const selected = ref<ResponseData[]>([]); //รายชื่อที่เลือก
const filter = ref<string>(""); //คำค้นหา
const visibleColumns = ref<string[]>([
  "no",
  "fullName",
  "examNumber",
  "organizationName",
  "positionCandidate",
  "reportingDate",
  "bmaOfficer",
  "draft",
  "statusName",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "center",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px,",
  },
  {
    name: "examNumber",
    align: "center",
    label: "ลำดับที่สอบได้",
    sortable: true,
    field: "examNumber",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organizationName",
    align: "left",
    label: "หน่วยงานที่รับการบรรจุ",
    sortable: true,
    field: "organizationName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionCandidate",
    align: "left",
    label: "ตำแหน่งที่สอบ",
    sortable: true,
    field: "positionCandidate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "reportingDate",
    align: "left",
    label: "วันที่รายงานตัว",
    sortable: true,
    field: "reportingDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "bmaOfficer",
    align: "left",
    label: "สถานภาพ",
    sortable: true,
    field: "bmaOfficer",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "draft",
    align: "left",
    label: "สถานะการส่งรายชื่อ",
    sortable: true,
    field: "draft",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "statusName",
    align: "left",
    label: "สถานะการบรรจุ",
    sortable: true,
    field: "statusName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

/**
 * ฟิลเตอร์ คำสั่ง
 * @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;
    },
    "ยืนยันส่งไปออกคำสั่ง",
    "ต้องการยืนยันส่งไปออกคำสั่งใช่หรือไม่?"
  );
}

/** ฟังก์ชั่นสำหรับ filter รายการข้อมูลคนตามประเภทคำสั่งที่เลือก */
function filterSelectOrder() {
  const data = props.rows ? props.rows : [];
  selected.value = [];
  rows.value = data.filter((v: any) => {
    switch (commandType.value) {
      case "C-PM-01":
      case "C-PM-02":
        return v.typeCommand === "APPOINTED" && v.bmaOfficerCheck === null;

      case "C-PM-03":
        return v.typeCommand === "APPOINT" && v.bmaOfficerCheck !== null;

      case "C-PM-04":
        return v.typeCommand === "MOVE" && v.bmaOfficerCheck !== null;

      case "C-PM-06":
        return v.typeCommand === "SLIP" && v.bmaOfficerCheck !== null;

      default:
        return [];
    }
  });
}

/** ปิด Modal และล้างค่าที่เลือก */
function closeModal() {
  modal.value = false;
  commandType.value = "";
}
/**
 * เมื่อ props.modal เป็น true
 * กำหนดให้  selected เป็นค่าว่างและกำหนด filter ประเภทตำแหน่งตามประเภทการสอบ
 */
watch(
  () => modal.value,
  async () => {
    if (modal.value === true) {
      rows.value = props.rows ? props.rows : [];
      selected.value = [];
      const status = DataStore.DataMainOrig.find((x: any) => x.id == examId);
      if (status?.examTypeName !== "") {
        const data = await storeCommand.getCommandTypes();

        listCommand.value = data.filter(
          (v: any) =>
            (status?.examTypeName === "สอบแข่งขัน" &&
              (v.code === "C-PM-01" ||
                v.code === "C-PM-03" ||
                v.code === "C-PM-04" ||
                v.code === "C-PM-06")) ||
            ((status?.examTypeName === "สอบคัดเลือก" ||
              status?.examTypeName === "คัดเลือกคนพิการ") &&
              (v.code === "C-PM-02" ||
                v.code === "C-PM-03" ||
                v.code === "C-PM-04" ||
                v.code === "C-PM-06"))
        );
      }
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal">
    <q-card style="width: 1200px; max-width: 80vw">
      <DialogHeader :tittle="'ส่งไปออกคำสั่ง'" :close="closeModal" />
      <q-separator />
      <q-card-section>
        <div class="row q-mb-sm" style="padding: 0">
          <q-select
            v-model="commandType"
            dense
            outlined
            label="ประเภทคำสั่ง"
            :options="commandOp"
            option-label="name"
            option-value="code"
            emit-value
            map-options
            use-input
            style="width: 350px; max-width: auto"
            @update:model-value="filterSelectOrder"
            @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="filter"
            placeholder="ค้นหา"
            style="width: 200px; max-width: auto"
          >
            <template v-slot:append>
              <q-icon v-if="filter == ''" name="search" />
              <q-icon
                v-if="filter !== ''"
                name="clear"
                class="cursor-pointer"
                @click="filter = ''"
              />
            </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="gt-xs q-ml-sm"
          />
        </div>

        <d-table
          :columns="columns"
          :rows="rows"
          :filter="filter"
          row-key="personalId"
          :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"
                class="cursor-pointer"
              >
                <template v-if="col.name === 'no'">
                  {{ props.rowIndex + 1 }}
                </template>
                <template
                  v-else-if="col.name === 'fullName'"
                  class="table_ellipsis"
                >
                  <q-item v-ripple style="padding: 0">
                    <q-item-section avatar>
                      <q-avatar size="30px" color="grey-4">
                        <q-img
                          :src="props.row.avatar"
                          class="photo-profile"
                          v-if="props.row.avatar"
                        />
                        <q-img :src="avatar" class="photo-profile" v-else"/>
                      </q-avatar>
                    </q-item-section>

                    <q-item-section>
                      <div class="text-weight-medium">{{ props.row.name }}</div>
                      <div class="text-weight-light">
                        {{ props.row.idCard }}
                      </div>
                    </q-item-section>
                  </q-item>
                </template>
                <template v-else-if="col.name === 'examNumber'">
                  <div class="text-weight-medium">
                    {{
                      props.row.examNumber !== null ? props.row.examNumber : "-"
                    }}
                  </div>
                </template>

                <template v-else-if="col.name === 'organizationName'">
                  <div
                    v-if="
                      props.row.orgName !== null ||
                      props.row.positionPath !== null
                    "
                  >
                    <div class="col-4">
                      <div class="text-weight-medium">
                        {{ props.row.root !== null ? props.row.root : "-" }}
                        {{
                          props.row.rootShortName !== null
                            ? `(${props.row.rootShortName})`
                            : ""
                        }}
                      </div>
                      <div class="text-weight-light">
                        {{
                          props.row.nodeName !== null ? props.row.nodeName : ""
                        }}
                        {{
                          props.row.nodeShortName !== null
                            ? `(${props.row.nodeShortName}${props.row.posMasterNo})`
                            : ""
                        }}
                      </div>
                    </div>
                  </div>

                  <div v-else>
                    <div class="col-4">
                      <div class="text-weight-medium">-</div>
                    </div>
                  </div>
                </template>
                <template v-else-if="col.name === 'positionCandidate'">
                  <div
                    class="text-weight-medium"
                    v-if="props.row.positionCandidate == null"
                  >
                    -
                  </div>
                  <div class="text-weight-medium" v-else>
                    {{ props.row.positionCandidate }}
                  </div>
                </template>
                <template v-else-if="col.name === 'reportingDate'">
                  <div class="text-weight-medium">
                    {{
                      props.row.reportingDate !== null
                        ? dateText(props.row.reportingDate)
                        : "-"
                    }}
                  </div>
                </template>
                <template v-else-if="col.name === 'bmaOfficer'">
                  <div class="text-weight-medium">
                    {{ props.row.bmaOfficer }}
                  </div>
                </template>
                <template v-else-if="col.name === 'draft'">
                  <div class="text-weight-medium">
                    {{ props.row.draft }}
                  </div>
                </template>
                <template v-else-if="col.name === 'statusName'">
                  <div class="text-weight-medium">
                    {{ props.row.statusName }}
                  </div>
                </template>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn
          label="ส่งไปออกคำสั่ง"
          @click="saveOrder"
          :disable="selected.length === 0"
          color="public"
          ><q-tooltip>ส่งไปออกคำสั่ง</q-tooltip></q-btn
        >
      </q-card-actions>
    </q-card>
  </q-dialog>

  <!-- dialog สร้างคำสั่ง -->
  <DialogCreateCommand
    v-model:modal="modalCommand"
    :command-type-code="commandType"
    :persons-id="selected.map((r) => r.id)"
  />
</template>
