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

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

import type { QTableProps } from "quasar";
import type { DataListCommand } from "@/modules/18_command/interface/response/Main";
import type { ListCommand } from "@/modules/18_command/interface/index/Main";

import DialogHeader from "@/components/DialogHeader.vue";

const storeCommand = useCommandMainStore();
const router = useRouter();
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  showLoader,
  success,
  messageError,
  dialogConfirm,
  hideLoader,
  date2Thai,
} = mixin;

const modal = defineModel<boolean>("modal", { required: true });

const props = defineProps({
  commandTypeCode: String, // ไอดีประเภทคำสั่ง
  persons: Array, // ไอดีคนที่เลือกออกคำสั่งส่งมาเป็น array
});

const commandOp = ref<ListCommand[]>([]); // ประเภทคำสั่ง
const commandType = ref<string>(""); //ประเภทคำสั่ง
const commandNo = ref<string>("");
const commandYear = ref<number>(new Date().getFullYear());

const rows = ref<DataListCommand[]>([]); // รายการคำสั่ง
const selected = ref<any[]>([]); // id คำสั่งที่เลือก
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 visibleColumns = ref<string[]>([
  "commandNo",
  "issue",
  "commandExcecuteDate",
  "commandAffectDate",
  "createdFullName",
  "assignFullName",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "commandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: false,
    field: "commandNo",
    format(val, row) {
      return val ? `${val} / ${row.commandYear + 543}` : "-";
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "issue",
    align: "left",
    label: "ชื่อคำสั่ง",
    sortable: true,
    field: "issue",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "commandAffectDate",
    align: "left",
    label: "วันที่ลงนาม",
    sortable: false,
    field: "commandAffectDate",
    format(val) {
      return val ? date2Thai(val) : "-";
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "commandExcecuteDate",
    align: "left",
    label: "วันที่คำสั่งมีผล",
    sortable: false,
    field: "commandExcecuteDate",
    format(val) {
      return val ? date2Thai(val) : "-";
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createdFullName",
    align: "left",
    label: "ผู้สร้าง",
    sortable: false,
    field: "createdFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "assignFullName",
    align: "left",
    label: "ผู้ลงนาม",
    sortable: false,
    field: "assignFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/**
 * ฟังก์ชันสร้างคำสั่งใหม่
 */
function createCommand(isRedirect: boolean) {
  dialogConfirm($q, async () => {
    showLoader();
    const data = await props?.persons?.map((e: any) => ({
      refId: e.id,
      prefix: e.prefix,
      firstName: e.firstName,
      lastName: e.lastName,
      citizenId: e.citizenId,
    }));
    const body = {
      commandYear: commandYear.value,
      commandNo: commandNo.value,
      commandTypeId: commandType.value,
      persons: data,
    };
    await http
      .post(config.API.command + `/person`, body)
      .then(async (res) => {
        const id = await res.data.result;
        modal.value = false;
        if (isRedirect) {
          router.push(`/command/edit/${id}`);
        } else {
          // modal.value = false;
          clearValue();
        }
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * ฟังก์ชันเพิ่มคนเข้าไปในคำสั่งที่เป็นแบบร่าง
 */
function addPersonalToCommand(isRedirect: boolean) {
  dialogConfirm($q, async () => {
    const data = props?.persons?.map((e: any) => ({
      refId: e.id,
      prefix: e.prefix,
      firstName: e.firstName,
      lastName: e.lastName,
      citizenId: e.citizenId,
    }));
    const body = {
      commandId: selected.value[0].id,
      persons: data,
    };
    showLoader();
    await http
      .post(config.API.command + `/person`, body)
      .then(async (res) => {
        const id = await res.data.result;
        modal.value = false;
        if (isRedirect) {
          router.push(`/command/edit/${id}`);
        } else {
          modal.value = false;
          clearValue();
        }
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function onSubmit(isRedirect: boolean) {
  if (selectCreate.value === "NEW") {
    createCommand(isRedirect);
  } else {
    addPersonalToCommand(isRedirect);
  }
}

/** ปิด popup */
function closeModal() {
  modal.value = false;
  clearValue();
}

function clearValue() {
  commandNo.value = "";
  commandYear.value = new Date().getFullYear();

  selectCreate.value = "NEW";
  selected.value = [];
  filter.value = "";
}

const selectCreate = ref<string | null>("NEW");

async function getListCommandDraf() {
  showLoader();
  await http
    .get(
      config.API.commandList +
        `?page=${pagination.value.page}&pageSize=${pagination.value.rowsPerPage}&year=${commandYear.value}&keyword=${filter.value}&status=DRAFT&commandTypeId=${commandType.value}`
    )
    .then(async (res) => {
      totalList.value = Math.ceil(
        res.data.result.total / pagination.value.rowsPerPage
      );
      total.value = res.data.result.total;
      rows.value = res.data.result.data;
      console.log("🚀 ~ .then ~ rows.value:", rows.value);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ดึงข้อมูลคำสั่ง */
async function fetchCommandType() {
  const data = await storeCommand.getCommandTypes(); // ยิงไป get ที่ store
  // filter เฉพาะ code ของคำสั่งที่เลือก
  commandOp.value = await data.filter(
    (v: any) => v.code == props.commandTypeCode
  );
  commandType.value = commandOp.value[0].id;
}

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

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

watch(modal, () => {
  if (modal.value && props.persons?.length !== 0) {
    fetchCommandType();
  }
});

watch(
  () => selectCreate.value,
  async () => {
    if (selectCreate.value == "DRAF") {
      getListCommandDraf();
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 50vw">
      <DialogHeader :tittle="'สร้าง/เลือกคำสั่ง'" :close="closeModal" />

      <q-separator />
      <q-card-section style="max-height: 50vh" class="scroll">
        <div class="row q-mb-md">
          <div class="col-12 q-gutter-md">
            <q-btn-toggle
              v-model="selectCreate"
              toggle-color="primary"
              color="white"
              text-color="black"
              no-caps
              :options="[
                { label: 'สร้างคำสั่งใหม่', value: 'NEW' },
                { label: 'เลือกคำสั่งที่เป็นแบบร่าง', value: 'DRAF' },
              ]"
            />
          </div>
        </div>

        <q-separator />
        <div v-if="selectCreate == 'NEW'" class="row q-mt-sm q-col-gutter-sm">
          <div class="col-12">
            <q-select
              class="inputgreen"
              v-model="commandType"
              :label="`${'ประเภทคำสั่ง'}`"
              option-label="name"
              :options="commandOp"
              option-value="id"
              dense
              emit-value
              map-options
              lazy-rules
              use-input
              hide-bottom-space
              outlined
              readonly
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div class="col-6">
            <q-input
              class="inputgreen"
              outlined
              dense
              v-model="commandNo"
              :label="`${'คำสั่งเลขที่'}`"
            />
          </div>
          <label class="col-1 flex justify-center items-center text-bold"
            >/</label
          >

          <div class="col-5">
            <datepicker
              menu-class-name="modalfix"
              v-model="commandYear"
              :locale="'th'"
              autoApply
              year-picker
              :enableTimePicker="false"
              class="inputgreen"
            >
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input
                  dense
                  outlined
                  hide-bottom-space
                  :model-value="commandYear == null ? null : commandYear + 543"
                  :label="`${'พ.ศ.'}`"
                  :rules="[(val:string) => !!val || `${'กรุณากรอก พ.ศ.'}`]"
                >
                  <template v-slot:prepend>
                    <q-icon
                      name="event"
                      class="cursor-pointer"
                      style="color: var(--q-primary)"
                    >
                    </q-icon>
                  </template>
                </q-input>
              </template>
            </datepicker>
          </div>
        </div>

        <div v-else class="row q-mt-sm">
          <q-toolbar style="padding: 0">
            <datepicker
              menu-class-name="modalfix"
              v-model="commandYear"
              :locale="'th'"
              autoApply
              year-picker
              :enableTimePicker="false"
              class="inputgreen"
              @update:model-value="getListCommandDraf()"
            >
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input
                  dense
                  outlined
                  hide-bottom-space
                  :model-value="commandYear == null ? null : commandYear + 543"
                  :label="`${'พ.ศ.'}`"
                  :rules="[(val:string) => !!val || `${'กรุณากรอก พ.ศ.'}`]"
                >
                  <template v-slot:prepend>
                    <q-icon
                      name="event"
                      class="cursor-pointer"
                      style="color: var(--q-primary)"
                    >
                    </q-icon>
                  </template>
                </q-input>
              </template>
            </datepicker>
            <q-space />
            <q-input
              borderless
              outlined
              dense
              debounce="300"
              v-model="filter"
              placeholder="ค้นหา"
              style="width: 200px; max-width: auto"
              @keydown.enter.prevent="getListCommandDraf()"
            >
              <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"
            />
          </q-toolbar>
          <div class="col-12">
            <d-table
              :columns="columns"
              :rows="rows"
              row-key="id"
              :visible-columns="visibleColumns"
              selection="single"
              v-model:selected="selected"
              :rows-per-page-options="[10, 25, 50, 100]"
              @update:pagination="updatePagination"
            >
              <template v-slot:pagination="scope">
                ทั้งหมด {{ total }} รายการ
                <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="getListCommandDraf"
                ></q-pagination>
              </template>

              <template v-slot:body="props">
                <q-tr :props="props" class="cursor-pointer">
                  <q-td>
                    <q-checkbox
                      keep-color
                      color="primary"
                      dense
                      v-model="props.selected"
                    />
                  </q-td>
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    <div>
                      {{ col.value ?? "-" }}
                    </div>
                  </q-td>
                </q-tr>
              </template>
            </d-table>
          </div>
        </div>
      </q-card-section>

      <q-separator />

      <q-card-actions align="right">
        <q-btn
          label="บันทึกและเลือกรายชื่อต่อ"
          @click="() => onSubmit(false)"
          :disable="
            selectCreate == 'NEW' ? commandType == '' : selected.length == 0
          "
          color="blue"
        >
          <q-tooltip>บันทึกและเลือกรายชื่อต่อ</q-tooltip>
        </q-btn>
        <q-btn
          label="บันทึกและไปยังหน้าคำสั่ง"
          @click="() => onSubmit(true)"
          :disable="
            selectCreate == 'NEW' ? commandType == '' : selected.length == 0
          "
          color="public"
        >
          <q-tooltip>บันทึกและไปยังหน้าคำสั่ง</q-tooltip>
        </q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
