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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useRoute } from "vue-router";
import { useCommandMainStore } from "@/modules/18_command/store/Main";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/Main";

import type { ListCommand } from "@/modules/18_command/interface/index/Main";
import type { ResponseData } from "@/modules/05_placement/interface/response/Transfer";
import type { OpType } from "@/modules/05_placement/interface/response/Main";
import type { DataPerson } from "@/modules/11_discipline/interface/index/Main";

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

const $q = useQuasar();
const route = useRoute();
const mainStore = useDisciplineMainStore();

const storeCommand = useCommandMainStore();
const mixin = useCounterMixin();
const {
  showLoader,
  success,
  messageError,
  dialogConfirm,
  hideLoader,
  onSearchDataTable,
} = mixin;

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

const modalCommand = ref<boolean>(false);
const idPath = ref<string>(route.params.id as string);
const type = ref<string>("");
const rows = ref<DataPerson[]>([]);
const rowsMain = ref<DataPerson[]>([]);
const selected = ref<ResponseData[]>([]);
const dataMapToSend = computed(() => {
  return selected.value.map((i: any) => ({
    id: i.id,
    profileId: i.personId,
    prefix: i.prefix,
    firstName: i.firstName,
    lastName: i.lastName,
    citizenId: i.idcard,
    position: i.position,
    posType: i.posTypeName,
    posLevel: i.posLevelName,
  }));
});

const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  data: {
    type: Object,
    require: true,
    default: [],
  },
  columns: {
    type: Array,
    default: [],
  },
  visibleColumns: {
    type: Array,
    default: [],
  },
  closeModal: Function,
  getData: Function,
  rows2: Array,
  filterKeyword2: String,
  title: String,
});

//popup ยืนยันส่งัว
function saveOrder() {
  dialogConfirm(
    $q,
    async () => {
      modalCommand.value = true;
      modal.value = false;
    },
    "ยืนยันส่งไปออกคำสั่ง",
    "ต้องการยืนยันส่งไปออกคำสั่งใช่หรือไม่?"
  );
}
//ส่งไปออกคำสั่ง
async function Ordersave() {
  const persons = selected.value.map((r) => r.id);

  // if (props.title == "ส่งไปออกคำสั่งลงโทษทางวินัย") {
  const body = {
    persons,
  };
  showLoader();
  await http
    .put(config.API.reportresult(idPath.value, type.value as string), body)
    .then((res: any) => {
      success($q, `${props.title}สำเร็จ`);
      props.closeModal?.();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      props.getData?.();
      hideLoader();
    });
}

const emit = defineEmits([
  "update:filterKeyword2",
  "update:selected",
  "update:type",
]);

const updateInput = (value: any) => {
  emit("update:filterKeyword2", value);
};

//รีเซ็ตค่าในช่องค้นหา
function Reset() {
  emit("update:filterKeyword2", "");
}

/**
 * ฟิลเตอร์ คำสั่ง
 * @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 serchDataTable() {
  rows.value = onSearchDataTable(
    props?.filterKeyword2 ? props?.filterKeyword2 : "",
    rowsMain.value,
    props.columns ? props.columns : []
  );
}

/**
 * เมื่อ props.modal เป็น true
 * กำหนดให้  selected เป็นค่าว่างและกำหนด filter ประเภทตำแหน่งตามประเภทการสอบ
 */
watch(
  () => modal.value,
  async () => {
    if (modal.value === true) {
      selected.value = [];
      commandType.value = "";
      rows.value = props.data.persons
        ? props.data.persons.filter((item: any) => item.status == "NEW")
        : [];

      rowsMain.value = rows.value;

      const data = await storeCommand.getCommandTypes();
      listCommand.value = data.filter(
        (v: any) =>
          v.code == "C-PM-19" ||
          v.code == "C-PM-20" ||
          v.code == "C-PM-27" ||
          v.code == "C-PM-28" ||
          v.code == "C-PM-29" ||
          v.code == "C-PM-30" ||
          v.code == "C-PM-31"
      );
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 1200px; max-width: 80vw">
      <DialogHeader :tittle="props.title" :close="closeModal" />
      <q-separator />
      <q-card-section>
        <div class="q-pb-sm row q-col-gutter-sm">
          <q-select
            v-model="commandType"
            dense
            outlined
            label="ประเภทคำสั่ง"
            :options="commandOp"
            option-label="name"
            option-value="code"
            emit-value
            map-options
            hide-selected
            fill-input
            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
            :model-value="filterKeyword2"
            @update:model-value="updateInput"
            placeholder="ค้นหา"
            @keydown.enter.pervent="serchDataTable"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
          <q-select
            v-model="props.visibleColumns"
            multiple
            outlined
            dense
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="props.columns"
            option-value="name"
            style="min-width: 140px"
          />
        </div>

        <d-table
          :columns="props.columns"
          :rows="rows"
          row-key="id"
          :visible-columns="props.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" class="cursor-pointer">
              <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-if="col.name === 'organization'"
                  class="table_ellipsis"
                >
                  {{ props.row.organization }}
                </div>
                <div v-else-if="col.name === 'salary'">
                  {{
                    props.row.salary ? props.row.salary.toLocaleString() : "-"
                  }}
                </div>
                <div v-else-if="col.name === 'profileType'">
                  {{
                    props.row.profileType
                      ? mainStore.convertType(props.row.profileType)
                      : "-"
                  }}
                </div>
                <div v-else>
                  {{ col.value ?? "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn
          :label="props.title"
          @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>
