<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 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 storeCommand = useCommandMainStore();
const mixin = useCounterMixin();
const {
  showLoader,
  success,
  messageError,
  dialogConfirm,
  hideLoader,
  dialogMessageNotify,
} = mixin;

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

const modalCommand = ref<boolean>(false);
const optionsType = ref<[]>([]);
const idPath = ref<string>(route.params.id as string);
const type = ref<string>("");
const rows = 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,
  }));
});

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

const checkSelected = computed(() => {
  if (selected.value.length === 0) {
    return true;
  }
});

//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(() => {
    commandType.value = val ? "" : commandType.value;
    commandOp.value = listCommand.value.filter(
      (v: any) => v.name.indexOf(val) > -1
    );
  });
}

/**
 * เมื่อ 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")
        : [];

      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 class="q-pt-none">
        <div class="row justify-between">
          <div class="col-5">
            <q-toolbar style="padding: 0">
              <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-toolbar>
          </div>

          <div class="col-5">
            <q-toolbar style="padding: 0">
              <q-input
                borderless
                outlined
                dense
                debounce="300"
                :model-value="filterKeyword2"
                @update:model-value="updateInput"
                placeholder="ค้นหา"
                style="width: 850px; max-width: auto"
              >
                <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"
                class="gt-xs q-ml-sm"
              />
            </q-toolbar>
          </div>
        </div>

        <d-table
          :columns="props.columns"
          :rows="rows"
          :filter="filterKeyword2?.trim()"
          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.toLocaleString() }}
                </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>
