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

import { useRoute, useRouter } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useAllocateDataStore } from "@/modules/07_insignia/storeAllocate";
import http from "@/plugins/http";
import config from "@/app.config";

/** impotrType */
import type { QTableProps } from "quasar";
import type { OptionData } from "@/modules/07_insignia/interface/index/Main";
import type { ResponseAllocate } from "@/modules/07_insignia/interface/response/Main";
import type { DataStructureTree } from "@/interface/main";

/** impotrComponents */
import cardTop from "@/modules/07_insignia/components/2_Manage/StatCard.vue";
import DialogForm from "@/modules/07_insignia/components/4_Allocate/DialogForm.vue";
import DialogEdit from "@/modules/07_insignia/components/4_Allocate/DialogEdit.vue";

/** impotrStores */
const router = useRouter();
const DataStore = useAllocateDataStore();
const mixin = useCounterMixin();
const {
  showLoader,
  hideLoader,
  messageError,
  success,
  dialogRemove,
  onSearchDataTable,
} = mixin;

const attrs = ref<any>(useAttrs());
const $q = useQuasar(); //ใช้ noti quasar
const route = useRoute();

/** ข้อมูล Table*/
const rows = ref<ResponseAllocate[]>([]);
const rowsMain = ref<ResponseAllocate[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organization",
    align: "left",
    label: "หน่วยงาน",
    sortable: true,
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "total",
    align: "left",
    label: "จำนวนครื่องราช ฯ ที่ได้รับ",
    sortable: true,
    field: "total",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "allocate",
    align: "left",
    label: "จัดสรรให้ข้าราชการแล้ว",
    sortable: true,
    field: "allocate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "remain",
    align: "left",
    label: "คงเหลือ",
    sortable: true,
    field: "remain",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "organization",
  "total",
  "allocate",
  "remain",
]);

const name = ref<string>("");
const id = ref<string>(route.params.id.toString());
const modal = ref<boolean>(false);
const orgList = ref<OptionData[]>([]); //รายการหน่วยงาน
const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

const stat = ref({
  total: 0, //จำนวนเครื่องราช ฯ ทั้งหมด
  allocate: 0, //จำนวนเครื่องราช ฯ ที่จัดสรรให้หน่วยงานแล้ว
  remain: 0, //จำนวนเครื่องราช ฯ คงเหลือ
});

/** funcion เรียกข้อมูล stat*/
async function fetchDashboard() {
  await http
    .get(config.API.insigniaManageOrgDashboard(id.value))
    .then((res) => {
      stat.value = {
        total: res.data.result.total,
        allocate: res.data.result.allocate,
        remain: res.data.result.remain,
      };
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** funcion เรียกข้อมูลรายชื่อ หน่วยงานจัดสรรเครื่องราชอิสริยาภรณ์ ตริตาภรณ์มงกุฎไทย ()*/
async function fetchListData() {
  await http
    .get(config.API.insigniaManageOrg(id.value))
    .then((res) => {
      rows.value = res.data.result.map((e: ResponseAllocate) => ({
        id: e.id,
        organization: e.organizationOrganization,
        total: e.total,
        allocate: e.allocate,
        remain: e.remain,
      }));
      rowsMain.value = rows.value;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** funcion เรียกข้อมูลหน่วยงานจัดสรรเครื่องราชอิสริยาภรณ์*/
async function fetchOrgList() {
  http
    .get(config.API.activeOrganization)
    .then((res) => {
      const data = res.data.result;

      http
        .get(config.API.orgByIdSystem(data.activeId, route.meta.Key as string))
        .then(async (res) => {
          const data = await res.data.result.map((item: DataStructureTree) => ({
            id: item.orgTreeId,
            name: item.orgName,
          }));
          orgList.value = data;
        })
        .catch((err) => {
          messageError($q, err);
        });
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** funcion ย้อนกลับหน้าจัดสรรเครื่องราชอิสริยาภรณ์*/
function backHistory() {
  router.push(`/insignia/allocate`);
}

/** funcion closePopup*/
function close() {
  modal.value = false;
  modalEdit.value = false;
}

/**
 * function บันทึกข้อมูลจัดสรรเครื่องราชฯ
 * @param organizationId เครื่องราช
 * @param total จำนวน
 */
async function save(organizationId: string, total: string) {
  showLoader();
  await http
    .post(config.API.insigniaManageOrgAdd(), {
      organizationOrganizationId: organizationId,
      insigniaManageId: id.value,
      total: total,
    })
    .then(async () => {
      await Promise.all([fetchListData(), fetchDashboard()]);
      close();
      success($q, "บันทึกมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function บันทึกการแก้ไขข้อมูลจัดสรรเครื่องราชฯ
 * @param organizationId เครื่องราช
 * @param amount จำนวน
 */
async function saveEdit(organizationId: string, amount: number) {
  showLoader();
  await http
    .put(config.API.insigniaManageOrg(organizationId), {
      total: Number(amount),
    })
    .then(async () => {
      await Promise.all([fetchListData(), fetchDashboard()]);
      close();
      success($q, "แก้ไขมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const rowData = ref<ResponseAllocate>(); //ข้อมูลที่ค้องการแก้ไข
const modalEdit = ref<boolean>(false); // popup แก้ไข
/**
 * function openPopup แก้ไข
 * @param data ข้อมูลที่จะแก้ไข
 */
function clickEditrow(data: ResponseAllocate) {
  rowData.value = data;
  modalEdit.value = true;
}

/**
 * function ลบรายการ
 * @param insigniaId เครื่องราช
 */
async function clickDelete(insigniaId: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.insigniaManageOrg(insigniaId))
      .then(async () => {
        await Promise.all([fetchDashboard(), fetchListData()]);
        await success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function clickAdd() {
  modal.value = true;
}

/** ค้นหาในตาราง*/
const filterKeyword = ref<string>("");
const filterRef = ref<any>(null);

function serchDataTable() {
  rows.value = onSearchDataTable(
    filterKeyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

/** Hook*/
onMounted(async () => {
  showLoader();
  name.value = DataStore.insigniaName;
  await Promise.all([
    fetchDashboard(),
    fetchListData(),
    fetchOrgList(),
  ]).finally(() => hideLoader());
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    <q-btn
      icon="mdi-arrow-left"
      unelevated
      round
      dense
      flat
      color="primary"
      class="q-mr-sm"
      @click="backHistory"
    />
    หน่วยงานจัดสรรเครื่องราชอิสริยาภรณ์ {{ name }}
  </div>
  <q-card bordered class="q-py-sm row col-12">
    <div class="col-12 row bg-white">
      <div class="fit q-px-md q-py-sm">
        <div class="row col-12 q-col-gutter-md fit">
          <cardTop
            :amount="stat.total"
            label="จำนวนเครื่องราช ฯ ทั้งหมด"
            color="#016987"
          />
          <cardTop
            :amount="stat.allocate"
            label="จำนวนเครื่องราช ฯ ที่จัดสรรให้หน่วยงานแล้ว"
            color="#02A998"
          />
          <cardTop
            :amount="stat.remain"
            label="จำนวนเครื่องราช ฯ คงเหลือ"
            color="#2EA0FF"
          />
        </div>
      </div>
    </div>
  </q-card>

  <q-card flat bordered class="col-12 q-mt-sm q-pa-md">
    <div class="row q-col-gutter-sm">
      <div class="row col-12">
        <div>
          <q-btn
            @click="clickAdd()"
            flat
            round
            color="primary"
            icon="mdi-plus"
            v-if="checkPermission($route)?.attrIsCreate"
          >
            <q-tooltip>จัดสรรเครื่องราชอิสริยาภรณ์ให้หน่วยงาน</q-tooltip>
          </q-btn>
        </div>
        <q-space />
        <div class="row q-col-gutter-sm">
          <q-input
            standout
            dense
            v-model="filterKeyword"
            ref="filterRef"
            outlined
            @keydown.enter.prevent="serchDataTable"
            placeholder="ค้นหา"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </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"
            style="min-width: 140px"
          />
        </div>
      </div>

      <div class="col-12">
        <d-table
          ref="table"
          :columns="columns"
          :rows="rows"
          row-key="id"
          flat
          bordered
          :paging="true"
          dense
          class="custom-header-table"
          v-bind="attrs"
          :visible-columns="visibleColumns"
          v-model:pagination="pagination"
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th auto-width></q-th>
              <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
                  v-if="checkPermission($route)?.attrIsUpdate"
                  flat
                  round
                  dense
                  icon="edit"
                  color="edit"
                  @click.stop="clickEditrow(props.row)"
                >
                  <q-tooltip> แก้ไขข้อมูล</q-tooltip>
                </q-btn>

                <q-btn
                  v-if="checkPermission($route)?.attrIsDelete"
                  flat
                  round
                  dense
                  icon="delete"
                  color="red"
                  @click.stop="clickDelete(props.row.id)"
                >
                  <q-tooltip> ลบข้อมูล</q-tooltip>
                </q-btn>
              </q-td>
              <q-td key="no" :props="props">
                {{ props.rowIndex + 1 }}
              </q-td>
              <q-td key="organization" :props="props">
                {{ props.row.organization }}
              </q-td>
              <q-td key="total" :props="props">
                {{ props.row.total }}
              </q-td>
              <q-td key="allocate" :props="props">
                {{ props.row.allocate }}
              </q-td>
              <q-td key="remain" :props="props">
                {{ props.row.remain }}
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </div>
    </div>
  </q-card>

  <DialogForm
    :modal="modal"
    :close="close"
    :save="save"
    :insignia-list="orgList"
  />

  <DialogEdit
    :modal="modalEdit"
    :save="saveEdit"
    :close="close"
    :insigniadata="rowData"
  />
</template>

<style lang="scss" scope>
.filter-card {
  background-color: #f1f1f1b0;
}

.toggle-expired-account {
  font-size: 12px;
  font-weight: 400;
  font-size: 15px;
  line-height: 150%;
  color: #35373c;
}

.icon-color {
  color: #4154b3;
}

.custom-header-table {
  max-height: 64vh;

  .q-table tr:nth-child(odd) td {
    background: white;
  }

  .q-table tr:nth-child(even) td {
    background: #f8f8f8;
  }

  .q-table thead tr {
    background: #ecebeb;
  }

  .q-table thead tr th {
    position: sticky;
    z-index: 1;
  }

  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }

  .q-table thead tr:first-child th {
    top: 0;
  }
}
</style>
