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

import http from "@/plugins/http";
import config from "@/app.config";
import { useSalaryListSDataStore } from "@/modules/13_salary/store/SalaryListsStore";
import { useCounterMixin } from "@/stores/mixin";

/** importType*/
import type { QTableProps } from "quasar";
import type {
  DataOption,
  ItemsCards,
} from "@/modules/13_salary/interface/index/Main";
import type { ResSalaryOrg } from "@/modules/13_salary/interface/response/SalaryList";

/** use*/
const $q = useQuasar();
const store = useSalaryListSDataStore();
const { messageError, showLoader, hideLoader, onSearchDataTable } =
  useCounterMixin();

/** props*/
const props = defineProps({
  year: Number,
  snapShot: String,
  roundFilter: Object,
});

const gruup = ref<string>("");
const options = ref<DataOption[]>([
  { id: "", name: "ทั้งหมด" },
  { id: "GROUP1", name: "กลุ่ม 1" },
  { id: "GROUP2", name: "กลุ่ม 2" },
]);

/** itemsCard*/
const itemsCardAPR = ref<ItemsCards[]>([
  {
    label: "จำนวนคนทั้งหมด",
    name: "group1",
    color: "secondary",
    total: 0,
  },
  {
    label: "15% ของจำนวนคน",
    name: "group2",
    color: "light-blue-4",
    total: 0,
  },
  {
    label: "เลือกไปแล้ว",
    name: "group2",
    color: "primary",
    total: 0,
  },
  {
    label: "คงเหลือโควตา",
    name: "group2",
    color: "indigo-6",
    total: 0,
  },
  {
    label: "สำรอง",
    name: "group2",
    color: "red-6",
    total: 0,
  },
]);
const itemsCardOCT = ref<ItemsCards[]>([
  {
    label: "จำนวนเงินคนครองปัจจุบัน",
    name: "group1",
    color: "secondary",
    total: 0,
  },

  {
    label: "วงเงิน 6%",
    name: "group2",
    color: "light-blue-4",
    total: 0,
  },
  {
    label: "ยอดเงินที่ใช้ไป",
    name: "group2",
    color: "primary",
    total: 0,
  },
  {
    label: "วงเงิน 6%-ยอดเงินที่ใช้ไป",
    name: "group2",
    color: "indigo-6",
    total: 0,
  },
  {
    label: "ใช้ไปเท่าไหร่",
    name: "group2",
    color: "blue-6",
    total: 0,
  },
  {
    label: "เหลือเท่าไหร่",
    name: "group2",
    color: "green-6",
    total: 0,
  },
  {
    label: "สำรอง",
    name: "group2",
    color: "red-6",
    total: 0,
  },
]);
const itemsCardSpeciel = ref<ItemsCards[]>([
  {
    label: "จำนวนคนทั้งหมด",
    name: "group1",
    color: "secondary",
    total: 0,
  },
  {
    label: "เลือกไปแล้ว",
    name: "group2",
    color: "primary",
    total: 0,
  },
  {
    label: "สำรอง",
    name: "group2",
    color: "red-6",
    total: 0,
  },
]);
const itemsCard = computed(() => {
  const items =
    store.roundMainCode === "APR"
      ? itemsCardAPR.value
      : store.roundMainCode === "OCT"
      ? itemsCardOCT.value
      : itemsCardSpeciel.value;
  return items;
});

/** ข้อมูล Table*/
const rows = ref<ResSalaryOrg[]>([]);
const rowsData = ref<ResSalaryOrg[]>([]);
const filter = ref<string>("");
const columnsAPR = ref<QTableProps["columns"]>([
  {
    name: "org",
    align: "left",
    label: "หน่วยงาน",
    sortable: true,
    field: "org",
    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",
    format: (v) => Number(v).toLocaleString(),
  },

  {
    name: "fifteenPercent",
    align: "left",
    label: "15% ของจำนวนคน",
    sortable: true,
    field: "fifteenPercent",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) =>
      Number(v).toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }),
  },
  {
    name: "chosen",
    align: "left",
    label: "เลือกไปแล้ว",
    sortable: true,
    field: "chosen",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
  },
  {
    name: "remaining",
    align: "left",
    label: "คงเหลือโควตา",
    sortable: true,
    field: "remaining",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
  },
  {
    name: "totalBackup",
    align: "left",
    label: "สำรอง",
    sortable: true,
    field: "totalBackup",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
  },
]);
const columnsOCT = ref<QTableProps["columns"]>([
  {
    name: "org",
    align: "left",
    label: "หน่วยงาน",
    sortable: true,
    field: "org",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "currentAmount",
    align: "left",
    label: "จำนวนเงินคนครองปัจจุบัน",
    sortable: true,
    field: "currentAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) =>
      Number(v).toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }),
  },

  {
    name: "sixPercentAmount",
    align: "left",
    label: "วงเงิน 6%",
    sortable: true,
    field: "sixPercentAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) =>
      Number(v).toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }),
  },
  {
    name: "spentAmount",
    align: "left",
    label: "ยอดเงินที่ใช้ไป",
    sortable: true,
    field: "spentAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) =>
      Number(v).toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }),
  },
  {
    name: "sixPercentSpentAmount",
    align: "left",
    label: "วงเงิน 6%-ยอดเงินที่ใช้ไป",
    sortable: true,
    field: "sixPercentSpentAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) =>
      Number(v).toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }),
  },

  {
    name: "useAmount",
    align: "left",
    label: "ใช้ไปเท่าไหร่",
    sortable: true,
    field: "useAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) =>
      Number(v).toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }),
  },
  {
    name: "remainingAmount",
    align: "left",
    label: "เหลือเท่าไหร่",
    sortable: true,
    field: "remainingAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) =>
      Number(v).toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }),
  },
  {
    name: "totalBackup",
    align: "left",
    label: "สำรอง",
    sortable: true,
    field: "totalBackup",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
  },
]);
const columnsSpeciel = ref<QTableProps["columns"]>([
  {
    name: "org",
    align: "left",
    label: "หน่วยงาน",
    sortable: true,
    field: "org",
    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",
    format: (v) => Number(v).toLocaleString(),
  },

  {
    name: "chosen",
    align: "left",
    label: "เลือกไปแล้ว",
    sortable: true,
    field: "chosen",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
  },

  {
    name: "totalBackup",
    align: "left",
    label: "สำรอง",
    sortable: true,
    field: "totalBackup",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
  },
]);
const visibleColumns = ref<string[]>(
  store.roundMainCode === "APR"
    ? ["org", "total", "chosen", "totalBackup"]
    : store.roundMainCode === "OCT"
    ? [
        "org",
        "currentAmount",
        "sixPercentAmount",
        "spentAmount",
        "sixPercentSpentAmount",
        "useAmount",
        "remainingAmount",
        "totalBackup",
      ]
    : ["org", "total", "fifteenPercent", "chosen", "remaining", "totalBackup"]
);
const columns = computed(() => {
  const columnsss =
    store.roundMainCode === "APR"
      ? columnsAPR.value
      : store.roundMainCode === "OCT"
      ? columnsOCT.value
      : columnsSpeciel.value;
  return columnsss;
});

/** function fetch ข้อมูลสถิติ*/
async function fetchDataDashboard() {
  showLoader();
  const formData = {
    year: props?.year,
    group: gruup.value,
    period: props?.roundFilter?.id,
    snapshot: props?.snapShot,
  };
  await http
    .post(config.API.salaryDashboard, formData)
    .then(async (res) => {
      const quota = await res.data.result.dashboard;
      itemsCardAPR.value[0].total = quota.total.toLocaleString();
      itemsCardAPR.value[1].total = quota.fifteenPercent.toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      });
      itemsCardAPR.value[2].total = quota.chosen.toLocaleString();
      itemsCardAPR.value[3].total = quota.remaining.toLocaleString();
      itemsCardAPR.value[4].total = quota.totalBackup.toLocaleString();
      itemsCardOCT.value[0].total = quota.currentAmount.toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      });
      itemsCardOCT.value[1].total = quota.sixPercentAmount.toLocaleString(
        "en",
        {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        }
      );
      itemsCardOCT.value[2].total = quota.spentAmount.toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      });
      itemsCardOCT.value[3].total = quota.sixPercentSpentAmount.toLocaleString(
        "en",
        {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        }
      );
      itemsCardOCT.value[4].total = quota.useAmount.toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      });
      itemsCardOCT.value[5].total = quota.remainingAmount.toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      });
      itemsCardOCT.value[6].total = quota.totalBackup.toLocaleString();

      itemsCardSpeciel.value[0].total = quota.total.toLocaleString();
      itemsCardSpeciel.value[1].total = quota.chosen.toLocaleString();
      itemsCardSpeciel.value[2].total = quota.totalBackup.toLocaleString();

      rows.value = res.data.result.salaryOrg;
      rowsData.value = res.data.result.salaryOrg;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onSearch() {
  rows.value = onSearchDataTable(
    filter.value,
    rowsData.value,
    columns.value ? columns.value : []
  );
}

/** HookLifecycle*/
onMounted(() => {
  fetchDataDashboard();
});

watch([() => props?.snapShot, () => props.roundFilter], () => {
  fetchDataDashboard();
});
</script>

<template>
  <!-- Card โควต้า -->
  <q-toolbar class="q-pa-md">
    <q-select
      dense
      outlined
      v-model="gruup"
      :options="options"
      label="กลุ่ม"
      emit-value
      map-options
      option-label="name"
      option-value="id"
      style="width: 150px"
      @update:model-value="fetchDataDashboard"
    />
  </q-toolbar>
  <div class="row col-12 q-pa-md bg-grey-2">
    <div class="row col-12 q-col-gutter-sm">
      <div
        v-for="(item, index) in itemsCard"
        :key="index"
        :class="
          store.roundMainCode === 'APR'
            ? 'col-6 col-sm-4 col-md-3 col-lg-2'
            : 'col-3'
        "
      >
        <q-card>
          <q-card-section>
            <div class="row items-center no-wrap">
              <div class="col">
                <div class="">{{ item.label }}</div>
              </div>

              <div :class="`text-${item.color} text-bold`">
                {{
                  item.total
                    ? store.roundMainCode === "OCT"
                      ? item.total.toLocaleString("en", {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 2,
                        })
                      : item.total
                    : 0
                }}
              </div>
            </div>
          </q-card-section>
        </q-card>
      </div>
    </div>
  </div>
  <q-separator />
  <div class="row q-pa-md">
    <div class="col-12">
      <q-toolbar style="padding: 0px">
        <q-space />
        <div class="row q-col-gutter-sm">
          <q-input
            borderless
            dense
            v-model="filter"
            placeholder="ค้นหา"
            outlined
            @keydown.enter.prevent="onSearch"
          >
            <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>
      </q-toolbar>
    </div>
    <div class="col-12">
      <d-table
        for="table"
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="id"
        flat
        bordered
        dense
        :visible-columns="visibleColumns"
      >
        <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">{{ col.label }}</span>
            </q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div class="table_ellipsis">
                {{ col.value ?? "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </div>
</template>

<style scoped></style>
