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

import { useRouter } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useCommandListStore } from "@/modules/18_command/store/ListStore";
import http from "@/plugins/http";
import config from "@/app.config";

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

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

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

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

const pagination = defineModel<Pagination>("pagination", { required: true });
const props = defineProps({
  fetchList: { type: Function, required: true },
  onRequest: { type: Function, required: true },
  checkAndUpdatePage: { type: Function, required: true },
});

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

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 props.checkAndUpdatePage(store.rows.length);
          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 props.checkAndUpdatePage(store.rows.length);
          await fetchListCommand();
          success($q, "ลบรายการสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการลบคำสั่งออกจากระบบ",
    "หากคุณกดยืนยันคำสั่งจะถูกลบออกจากระบบทันที ต้องการยืนยืนยันการลบคำสั่งนี้ใช่หรือไม่?"
  );
}

function onAssignCommand(id: string) {
  commandId.value = id;
  modalAssign.value = true;
}

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

<template>
  <p-table
    ref="table"
    :columns="store.columns"
    :visible-columns="store.visibleColumns"
    :rows="store.rows"
    row-key="id"
    flat
    dense
    bordered
    :paging="true"
    :rows-per-page-options="[10, 25, 50, 100]"
    @request="onRequest"
    v-model:pagination="pagination"
  >
    <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"
            v-if="
              store.tabsMain === 'DRAFT' || store.tabsMain === 'PENDING'
                ? checkPermission($route)?.attrIsGet ||
                  checkPermission($route)?.attrIsCreate ||
                  checkPermission($route)?.attrIsDelete ||
                  checkPermission($route)?.attrIsUpdate
                : store.tabsMain === 'WAITING' || store.tabsMain === 'REPORTED'
                ? checkPermission($route)?.attrIsGet ||
                  checkPermission($route)?.attrIsCreate
                : store.tabsMain === 'CANCEL'
                ? checkPermission($route)?.attrIsGet ||
                  checkPermission($route)?.attrIsCreate ||
                  checkPermission($route)?.attrIsDelete
                : ''
            "
          >
            <q-menu>
              <q-list dense style="min-width: 200px">
                <!-- แก้ไขข้อมูล ไม่แสดง Tabs ยกเลิก -->
                <q-item
                  v-if="
                    store.tabsMain !== 'WAITING' &&
                    store.tabsMain !== 'CANCEL' &&
                    store.tabsMain !== 'REPORTED' &&
                    checkPermission($route)?.attrIsGet &&
                    checkPermission($route)?.attrIsUpdate
                  "
                  clickable
                  v-close-popup
                  @click.prevent="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
                  v-if="checkPermission($route)?.attrIsGet"
                  clickable
                  v-close-popup
                  @click.prevent="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
                  v-if="checkPermission($route)?.attrIsCreate"
                  clickable
                  v-close-popup
                  @click.prevent="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>

                <!-- มอบหมายคำสั่ง -->
                <q-item
                  clickable
                  v-close-popup
                  v-if="checkPermission($route)?.attrOwnership === 'OWNER'"
                  @click.prevent="onAssignCommand(props.row.id)"
                >
                  <q-item-section>
                    <div class="row items-center">
                      <q-icon
                        color="green-6"
                        size="xs"
                        name="mdi-account-check"
                      />
                      <div class="q-pl-md">มอบหมายคำสั่ง</div>
                    </div>
                  </q-item-section>
                </q-item>

                <!-- ยกเลิก ไม่แสดง Tabs ยกเลิก -->
                <q-item
                  v-if="
                    store.tabsMain !== 'WAITING' &&
                    store.tabsMain !== 'CANCEL' &&
                    store.tabsMain !== 'REPORTED' &&
                    checkPermission($route)?.attrIsDelete
                  "
                  clickable
                  v-close-popup
                  @click.prevent="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
                  v-if="
                    store.tabsMain === 'CANCEL' &&
                    checkPermission($route)?.attrIsCreate
                  "
                  clickable
                  v-close-popup
                  @click.prevent="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' &&
                    checkPermission($route)?.attrIsDelete
                  "
                  @click.prevent="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>
  </p-table>

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

  <DialogAssign v-model:modal="modalAssign" :command-id="commandId" :fetch-list-command="fetchListCommand" />
</template>

<style scoped></style>
