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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useCommandMainStore } from "@/modules/18_command/store/Main";
import type { HistoryResultCommand } from "@/modules/11_discipline/interface/index/Main";
import DialogHeader from "@/components/DialogHeader.vue";

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

const modal = defineModel<boolean>("modal", { required: true });
const personId = defineModel<string>("personId", { required: true });
const rows = ref<HistoryResultCommand[]>([]);

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "commandSubject",
    align: "left",
    label: "คำสั่ง",
    sortable: true,
    field: "commandSubject",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่ส่งไปออกคำสั่ง",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

function getHistory(id: string) {
  showLoader();
  http
    .get(config.API.historyOrderById(id))
    .then((res) => {
      const data = res.data.result;
      rows.value = data.map((item: any) => ({
        commandSubject: item.commandSubject ? item.commandSubject : "-",
        createdAt: item.createdAt
          ? date2Thai(item.createdAt, false, true)
          : "-",
        lastUpdatedAt: item.lastUpdatedAt
          ? date2Thai(item.lastUpdatedAt, false, true)
          : "-",
      }));
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

async function getCommand() {
  if (storeCommand.commandTypes.length > 0) return;
  await storeCommand.getCommandTypes();
}

function convertCommand(codeType: string) {
  const data = storeCommand.commandTypes.find(
    (items: any) => items.code == codeType
  );
  if (data) return data.name;
}

function close() {
  modal.value = false;
}
watch(
  () => [modal.value, personId.value],
  async ([newModal, newPersonId], [oldModal, oldPersonId]) => {
    if (newModal && newPersonId !== oldPersonId) {
      rows.value = [];
      await getCommand();
      await getHistory(personId.value);
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 40vw">
      <q-form ref="myForm">
        <DialogHeader :tittle="`ประวัติการออกคำสั่ง`" :close="close" />
        <q-separator />
        <q-card-section>
          <d-table
            ref="table"
            flat
            bordered
            :columns="columns"
            :rows="rows"
            dense
            :rows-per-page-options="[10, 25, 50, 100]"
          >
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th v-for="col in props.cols" :key="col.name" :props="props">
                  <span class="text-weight-medium" v-html="col.label" />
                </q-th>
              </q-tr>
            </template>
            <template v-slot:body="props">
              <q-tr :props="props" class="cursor-pointer">
                <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 == 'commandSubject'">
                    {{
                      props.row.commandSubject
                        ? convertCommand(props.row.commandSubject)
                        : "-"
                    }}
                  </div>
                  <div v-else>
                    {{ col.value }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </q-card-section>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.my-menu-link {
  background: #ebf9f7 !important;
  border-radius: 5px;
  border: 1px solid #1bb19ab8;
  color: #1bb19ab8 !important;
}
</style>
