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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useCommandMainStore } from "@/modules/18_command/store/Main";
import { usePlacementDataStore } from "@/modules/05_placement/store";
import { useTransferDataStore } 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 type { FormMainProbation } from "@/modules/05_placement/interface/request/Main";

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

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

const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  fetchData: {
    type: Function,
    default: () => {
      console.warn("fetchData function is not ");
    },
  },
});

const examId = route.params.examId;
const rows = ref<FormMainProbation[]>([]);
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 total = ref<number>(0);
const totalList = ref<number>(1);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

const dataMapToSend = computed(() => {
  return selected.value.map((i: any) => ({
    id: i.personal_id,
    profileId: i.personal_id,
    prefix: i.prefixName,
    firstName: i.firstName,
    lastName: i.lastName,
    citizenId: i.idcard,
    position: i.positionOld,
    posType: i.positionTypeOld,
    posLevel: i.positionLevelOld,
  }));
});

/** ข้อมูลที่เเสดง */
const visibleColumns = ref<string[]>([
  "no",
  "name",
  "position_line",
  "position_level",
  "organization",
  "probation_no",
  "order_number",
  "probation_status",
]);

/** หัวตาราง */
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: false,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position_line",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    sortable: false,
    field: "position_line",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position_level",
    align: "left",
    label: "ระดับ",
    sortable: false,
    field: "position_level",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organization",
    align: "left",
    label: "สังกัด",
    sortable: false,
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px ",
    classes: "table_ellipsis",
  },
  {
    name: "probation_no",
    align: "center",
    label: "ครั้งที่ทดลองปฏิบัติหน้าที่ราชการ",
    sortable: false,
    field: "probation_no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.probation_no ? row.probation_no : "-";
    },
  },
  {
    name: "order_number",
    align: "center",
    label: "เลขที่คําสั่งบรรจุแต่งตั้ง",
    sortable: false,
    field: "order_number",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.order_number ? row.order_number : "-";
    },
  },
  {
    name: "probation_status",
    align: "left",
    label: "สถานะ",
    sortable: false,
    field: "probation_status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/**
 * ฟิลเตอร์ คำสั่ง
 * @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() {
  // dialogConfirm(
  //   $q,
  //   async () => {
  modalCommand.value = true;
  modal.value = false;
  //   },
  //   "ยืนยันส่งไปออกคำสั่ง",
  //   "ต้องการยืนยันส่งไปออกคำสั่งใช่หรือไม่?"
  // );
}

/** ปิด Modal และล้างค่าที่เลือก */
function closeModal() {
  modal.value = false;
  commandType.value = "";
}

/** ดึงข้อมูลคน */
async function getList() {
  showLoader();
  await http
    .get(
      config.API.probationPersonalList() +
        `?status=${
          commandType.value ? (commandType.value == "C-PM-11" ? 2 : 3) : ""
        }&page=${pagination.value.page}&pageSize=${
          pagination.value.rowsPerPage
        }&keyword=${filter.value.trim()}`
    )
    .then(async (res) => {
      const data = await res.data.result.data;
      const resTotal = await res.data.result.total;
      rows.value = data;
      totalList.value = Math.ceil(resTotal / pagination.value.rowsPerPage);
      total.value = resTotal;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function updatePagination(newPagination: any) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}

watch(
  () => pagination.value.rowsPerPage,
  async () => {
    await getList();
  }
);

/**
 * เมื่อ props.modal เป็น true
 * กำหนดให้  selected เป็นค่าว่างและกำหนด filter ประเภทตำแหน่งตามประเภทการสอบ
 */
watch(
  () => modal.value,
  async () => {
    if (modal.value === true) {
      rows.value = [];
      selected.value = [];
      commandType.value = "";
      filter.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) => v.code === "C-PM-11" || v.code === "C-PM-12"
        );
        console.log(listCommand.value);
      }
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 85%">
      <DialogHeader :tittle="'ส่งไปออกคำสั่ง'" :close="closeModal" />
      <q-separator />
      <q-card-section>
        <div class="row col-12 q-col-gutter-sm">
          <div class="row col-12 q-col-gutter-sm">
            <q-select
              v-model="commandType"
              dense
              outlined
              label="ประเภทคำสั่ง"
              :options="commandOp"
              option-label="name"
              option-value="code"
              emit-value
              map-options
              use-input
              hide-selected
              fill-input
              style="width: 620px; max-width: auto"
              @update:model-value="(pagination.page = 1), getList()"
              @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
              v-model="filter"
              placeholder="ค้นหา"
              style="width: 200px; max-width: auto"
              @keydown.enter.prevent="(pagination.page = 1), getList()"
            >
              <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>

          <div class="col-12">
            <d-table
              :columns="columns"
              :rows="rows"
              row-key="personal_id"
              :visible-columns="visibleColumns"
              selection="single"
              v-model:selected="selected"
              :rows-per-page-options="[10, 25, 50, 100]"
              @update:pagination="updatePagination"
            >
              <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'">
                      {{
                        (pagination.page - 1) * pagination.rowsPerPage +
                        props.rowIndex +
                        1
                      }}
                    </div>
                    <div v-else-if="col.name == 'order_number'">
                      {{
                        props.row.order_number
                          ? props.row.order_number != "xx/2566"
                            ? props.row.order_number
                            : "-"
                          : "-"
                      }}
                    </div>
                    <div v-else-if="col.name == 'probation_status'">
                      {{
                        props.row.probation_status
                          ? store.statusProbationMain(
                              props.row.probation_status
                            )
                          : "-"
                      }}
                    </div>

                    <div v-else>
                      {{ col.value ? col.value : "-" }}
                    </div>
                  </q-td>
                </q-tr>
              </template>
              <template v-slot:pagination="scope">
                ทั้งหมด {{ total.toLocaleString() }} รายการ
                <q-pagination
                  v-model="pagination.page"
                  active-color="primary"
                  color="dark"
                  :max="Number(totalList)"
                  size="sm"
                  boundary-links
                  direction-links
                  :max-pages="5"
                  @update:model-value="getList"
                ></q-pagination>
              </template>
            </d-table>
          </div>
        </div>
      </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="selected ? dataMapToSend : []"
    :fetch-data="props.fetchData"
  />
</template>
