<script setup lang="ts">
import { onMounted, 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 { useCommandListStore } from "@/modules/18_command/store/ListStore";

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

import DialogFormCommand from "@/modules/18_command/components/Main/DialogFormCommand.vue";

const $q = useQuasar();
const router = useRouter();

const store = useCommandListStore();
const {
  showLoader,
  hideLoader,
  success,
  messageError,
  date2Thai,
  dialogRemove,
  dialogConfirm,
} = useCounterMixin();

const page = defineModel<number>("page", { required: true });
const pageSize = defineModel<number>("pageSize", { required: true });

const props = defineProps({
  fetchList: { type: Function, required: true },
});

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: "commandExcecuteDate",
    align: "left",
    label: "วันที่ลงนาม",
    sortable: false,
    field: "commandExcecuteDate",
    format(val) {
      return val ? date2Thai(val) : "-";
    },
    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: "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",
  },
]);

const modalCopy = ref<boolean>(false);
const isCheckPageSize = ref<boolean>(false);
const commandId = ref<string>("");

async function fetchListCommand() {
  await props.fetchList?.();
}

function onRedirectToDetail(type: string, id: string) {
  router.push(`/command/${type}/${id}`);
}

function onCopy(id: string) {
  commandId.value = id;
  modalCopy.value = true;
}

function onCancel(id: string) {
  dialogRemove(
    $q,
    async () => {
      showLoader();
      await http
        .put(config.API.commandAction(id, "cancel"))
        .then(async () => {
          await fetchListCommand();
          success($q, "ยกเลิกรายการสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการยกเลิกการออกคำสั่ง",
    "ต้องการยืนยันการยกเลิกการออกคำสั่งนี้ใช่หรือไม่ ?"
  );
}

function onReCommand(id: string) {
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      await http
        .put(config.API.commandAction(id, "resume"))
        .then(async () => {
          await fetchListCommand();
          success($q, "ดึงไปทำคำสั่งใหม่สำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการดึงไปทำคำสั่งใหม่",
    "ต้องการยืนยืนยันการดึงไปทำคำสั่งใหม่ใช่หรือไม่ ?"
  );
}
function onDeleteCommand(id: string) {
  dialogRemove(
    $q,
    async () => {
      showLoader();
      await http
        .delete(config.API.command + `/${id}`)
        .then(async () => {
          await fetchListCommand();
          success($q, "ลบรายการสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการลบคำสั่ง",
    "ต้องการยืนยืนยันการลบคำสั่งนี้ใช่หรือไม่ ?"
  );
}

/**
 * function updatePagination
 * @param newPagination ข้อมูล Pagination ใหม่
 */
function updatePagination(newPagination: Pagination) {
  page.value = 1;
  pageSize.value = newPagination.rowsPerPage;
}

watch(pageSize, () => {
  isCheckPageSize.value = true;
  fetchListCommand();
});

onMounted(() => {
  !isCheckPageSize.value && fetchListCommand();
});
</script>

<template>
  <d-table
    ref="table"
    :columns="columns"
    :rows="store.rows"
    row-key="id"
    flat
    dense
    bordered
    :paging="true"
    :rows-per-page-options="[10, 25, 50, 100]"
    @update:pagination="updatePagination"
  >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th auto-width />
        <q-th v-for="col in props.cols" :key="col.name" :props="props">
          <span class="text-weight-medium">{{ col.label }}</span>
        </q-th>
      </q-tr>
    </template>
    <template v-slot:body="props">
      <q-tr :props="props">
        <q-td auto-width>
          <q-btn
            flat
            dense
            round
            color="secondary"
            icon="mdi-dots-horizontal-circle-outline"
          >
            <q-menu>
              <q-list dense style="min-width: 200px">
                <!-- แก้ไขข้อมูล ไม่แสดง Tabs ยกเลิก -->
                <q-item
                  clickable
                  v-close-popup
                  v-if="store.tabsMain !== 'CANCEL'"
                  @click.pervent="onRedirectToDetail('edit', props.row.id)"
                >
                  <q-item-section>
                    <div class="row items-center">
                      <q-icon
                        color="edit"
                        size="xs"
                        name="edit
                      "
                      />
                      <div class="q-pl-md">แก้ไขข้อมูล</div>
                    </div>
                  </q-item-section>
                </q-item>

                <!-- รายละเอียด -->
                <q-item
                  clickable
                  v-close-popup
                  @click.pervent="onRedirectToDetail('view', props.row.id)"
                >
                  <q-item-section>
                    <div class="row items-center">
                      <q-icon
                        color="info"
                        size="xs"
                        name="mdi-eye
                      "
                      />
                      <div class="q-pl-md">รายละเอียด</div>
                    </div>
                  </q-item-section>
                </q-item>

                <!-- ทำสำเนาคำสั่ง -->
                <q-item
                  clickable
                  v-close-popup
                  @click.pervent="onCopy(props.row.id)"
                >
                  <q-item-section>
                    <div class="row items-center">
                      <q-icon
                        color="blue-6"
                        size="xs"
                        name="mdi-content-copy"
                      />
                      <div class="q-pl-md">ทำสำเนาคำสั่ง</div>
                    </div>
                  </q-item-section>
                </q-item>

                <!-- ยกเลิก ไม่แสดง Tabs ยกเลิก -->
                <q-item
                  clickable
                  v-close-popup
                  v-if="store.tabsMain !== 'CANCEL'"
                  @click.pervent="onCancel(props.row.id)"
                >
                  <q-item-section>
                    <div class="row items-center">
                      <q-icon
                        color="red"
                        size="xs"
                        name="close
                      "
                      />
                      <div class="q-pl-md">ยกเลิก</div>
                    </div>
                  </q-item-section>
                </q-item>

                <!-- ดึงไปทำคำสั่งใหม่ แสดงแค่ Tabs ยกเลิก -->
                <q-item
                  clickable
                  v-close-popup
                  v-if="store.tabsMain === 'CANCEL'"
                  @click.pervent="onReCommand(props.row.id)"
                >
                  <q-item-section>
                    <div class="row items-center">
                      <q-icon color="amber-5" size="xs" name="mdi-replay" />
                      <div class="q-pl-md">ดึงไปทำคำสั่งใหม่</div>
                    </div>
                  </q-item-section>
                </q-item>

                <q-item
                  clickable
                  v-close-popup
                  v-if="store.tabsMain === 'CANCEL'"
                  @click.pervent="onDeleteCommand(props.row.id)"
                >
                  <q-item-section>
                    <div class="row items-center">
                      <q-icon color="red" size="xs" name="mdi-delete" />
                      <div class="q-pl-md">ลบคำสั่ง</div>
                    </div>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-menu>
          </q-btn>
        </q-td>
        <q-td v-for="col in props.cols" :key="col.name" :props="props">
          <div>
            {{ col.value ?? "-" }}
          </div>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:pagination="scope">
      ทั้งหมด {{ store.total }} รายการ
      <q-pagination
        v-model="page"
        active-color="primary"
        color="dark"
        :max="Number(store.maxPage)"
        size="sm"
        boundary-links
        direction-links
        :max-pages="5"
        @update:model-value="fetchListCommand"
      ></q-pagination>
    </template>
  </d-table>

  <DialogFormCommand
    v-model:modal="modalCopy"
    :is-copy="true"
    :command-id="commandId"
  />
</template>

<style scoped></style>
