<script setup lang="ts">
import { ref, onMounted, reactive, computed } from "vue";
import { useQuasar } from "quasar";
import { checkPermission } from "@/utils/permissions";
import http from "@/plugins/http";
import config from "@/app.config";
import genReportXLSX from "@/plugins/genreportxlsx";

/** importType*/
import type { DataOption } from "@/modules/13_salary/interface/index/Main";
import type { DataFilter } from "@/modules/13_salary/interface/index/SalaryList";
import type {
  DataPeriodLatest,
  DataPeriod,
} from "@/modules/13_salary/interface/response/SalaryList";

/** importComponents*/
import TableTabType1 from "@/modules/13_salary/components/05_salaryListsEmployee/TableTypePending.vue";
import TableTabType2 from "@/modules/13_salary/components/05_salaryListsEmployee/TableTypeOther.vue";
import DialogInfoCriteria from "@/modules/13_salary/components/05_salaryListsEmployee/DialogInfoCriteria.vue";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";
import { useSalaryEmployeeListSDataStore } from "@/modules/13_salary/store/SalaryEmployeeListsStore";

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

/** props*/
const props = defineProps({
  periodLatest: { type: Object as () => DataPeriodLatest, require: true },
  rootId: { type: String, require: true },
  periodId: { type: String, require: true },
  roundFilter: { type: Object, require: true },
});

const splitterModel = ref<number>(13);
const modalDialogInfoCriteria = ref<boolean>(false); //popup หลักเกณฑ์การพิจารณาเลื่อนขั้นเงินข้าราชการ
const isRetire = ref<boolean | string>(false); //แสดงเฉพาะผู้เกษียณอายุราชการ
const rows = ref<DataPeriod[]>([]); //ข้อมูลรายชื่อ
const total = ref<number>(0); //จำนวนรายการ
const maxPage = ref<number>(1); //จำนวนหน้า

//itemsTab กลุ่ม
const itemsTabGroup = ref([
  {
    lable: "กลุ่ม 1",
    name: "group1",
  },
  {
    lable: "กลุ่ม 2",
    name: "group2",
  },
]);
//itemsTab ขั้น
const itemsTabType = computed(() => {
  return store.roundMainCode === "OCT"
    ? [
        {
          lable: "รายชื่อคนครอง",
          name: "tab1",
          type: "PENDING",
        },
        {
          lable: "1 ขั้น",
          name: "tab2",
          type: "FULL",
        },
        {
          lable: "0.5 ขั้น",
          name: "tab3",
          type: "HAFT",
        },
        {
          lable: "1.5 ขั้น",
          name: "tab4",
          type: "FULLHAFT",
        },
        {
          lable: "ไม่ได้เลื่อน",
          name: "tab4",
          type: "NONE",
        },
      ]
    : store.roundMainCode === "APR"
    ? [
        {
          lable: "รายชื่อคนครอง",
          name: "tab1",
          type: "PENDING",
        },
        {
          lable: "1 ขั้น",
          name: "tab2",
          type: "FULL",
        },
        {
          lable: "0.5 ขั้น",
          name: "tab3",
          type: "HAFT",
        },
        {
          lable: "ไม่ได้เลื่อน",
          name: "tab4",
          type: "NONE",
        },
      ]
    : [
        {
          lable: "รายชื่อคนครอง",
          name: "tab1",
          type: "PENDING",
        },
        {
          lable: "1 ขั้น",
          name: "tab2",
          type: "FULL",
        },
        {
          lable: "0.5 ขั้น",
          name: "tab3",
          type: "HAFT",
        },
      ];
});
//itemsCard
const itemsCard = ref([
  {
    lable: "จำนวนคนทั้งหมด",
    name: "group1",
    color: "secondary",
    total: 0,
  },
  {
    lable: "15% ของจำนวนคน",
    name: "group2",
    color: "light-blue-4",
    total: 0,
  },
  {
    lable: "เลือกไปแล้ว",
    name: "group2",
    color: "primary",
    total: 0,
  },
  {
    lable: "คงเหลือโควตา",
    name: "group2",
    color: "indigo-6",
    total: 0,
  },
  {
    lable: "สำรอง",
    name: "group2",
    color: "red-6",
    total: 0,
  },
  {
    lable: "จำนวนเงินคนครองปัจจุบัน",
    name: "group1",
    color: "secondary",
    total: 0,
  },

  {
    lable: "วงเงิน 6%",
    name: "group2",
    color: "light-blue-4",
    total: 0,
  },
  {
    lable: "ยอดเงินที่ใช้ไป",
    name: "group2",
    color: "primary",
    total: 0,
  },
  {
    lable: "วงเงิน 6%-ยอดเงินที่ใช้ไป",
    name: "group2",
    color: "indigo-6",
    total: 0,
  },
  {
    lable: "ใช้ไปเท่าไหร่",
    name: "group2",
    color: "blue-6",
    total: 0,
  },
  {
    lable: "เหลือเท่าไหร่",
    name: "group2",
    color: "green-6",
    total: 0,
  },
  {
    lable: "สำรอง",
    name: "group2",
    color: "red-6",
    total: 0,
  },
]);
//ข้อมูลค้นหารายชื่อคยขึ้นเงินเดือน
const formFilter = reactive<DataFilter>({
  page: 1,
  pageSize: 10,
  keyword: "",
  type: store.tabType,
});

/**
 * function เรียกข้อมูลจำนวนโควต้า
 * @param id กลุ่ม
 */
function fetchDataQuota(id: string) {
  http
    .get(config.API.salaryListPeriodQuotaEmp(id))
    .then((res) => {
      const data = res.data.result;
      store.remaining = data.remaining;
      store.statusQuota = data.status;
      itemsCard.value[0].total = data.total;
      itemsCard.value[1].total = data.fifteenPercent;
      itemsCard.value[2].total = data.chosen;
      itemsCard.value[3].total = data.remaining;
      itemsCard.value[4].total = data.totalBackup;

      itemsCard.value[5].total = data.currentAmount;
      itemsCard.value[6].total = data.sixPercentAmount;
      itemsCard.value[7].total = data.spentAmount;
      itemsCard.value[8].total = data.sixPercentSpentAmount;
      itemsCard.value[9].total = data.useAmount;
      itemsCard.value[10].total = data.remainingAmount;

      itemsCard.value[11].total = data.totalBackup;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * function เรียกข้อมูลรายชื่อ
 * @param id กลุ่ม
 */
async function fetchDataPeriod(id: string) {
  showLoader();
  rows.value = [];
  let formData = {
    page: formFilter.page.toString(),
    pageSize: formFilter.pageSize.toString(),
    keyword: formFilter.keyword,
    type: store.tabType,
    isRetire:
      store.roundMainCode !== "OCT"
        ? null
        : isRetire.value === true
        ? "1"
        : "0",
  };

  await http
    .put(config.API.salaryListPeriodORGEmp(id), formData)
    .then((res) => {
      rows.value = res.data.result.data;
      total.value = res.data.result.total;
      maxPage.value = Math.ceil(res.data.result.total / formFilter.pageSize);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      setTimeout(() => {
        hideLoader();
      }, 1000);
    });
}

/**
 * function เปลี่ยนขั้น
 */
function changeTabType() {
  formFilter.page = 1;
  formFilter.pageSize = 10;
  formFilter.keyword = "";
  store.groupId && fetchDataPeriod(store.groupId);
}

/**
 * function เรียกข้อมูลรายชื่ออีกครั้ง
 */
function fetchDataPeriodNew() {
  store.groupId && fetchDataPeriod(store.groupId);
  store.groupId && fetchDataQuota(store.groupId);
}

/**
 * function โหลดไฟล์
 * @param data ข้อมูลที่ต้องการโหล
 * @param type ประเภทไฟล์ docx,xlsx
 */
async function onClickDownload(data: DataOption, type: string = "xlsx") {
  showLoader();
  if (data.id === "emp-08" || data.id === "emp2-08") {
    const formData = {
      type: "HAFT",
      startDate:
        data.id === "emp-08"
          ? `${props?.roundFilter?.year - 1}-10-01`
          : `${props?.roundFilter?.year}-04-01`,
      endDate:
        data.id === "emp-08"
          ? `${props?.roundFilter?.year}-03-31`
          : `${props?.roundFilter?.year}-09-30`,
    };
    await http
      .post(config.API.leaveReportLeaveday("employee"), formData)
      .then(async (res) => {
        const dataList = await res.data.result;
        await genReportXLSX(dataList, data.name);
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  } else {
    if (props.rootId && props.periodId) {
      await http
        .get(
          config.API.salaryReportListsByid(
            data.id,
            props.rootId,
            props.periodId
          )
        )
        .then(async (res) => {
          const dataList = await res.data.result;
          await genReportXLSX(dataList, data.name, type);
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    }
  }
}

/**
 * funrion แสดงเฉพาะผู้เกษียณอายุราชการ
 */
function updateIsShowRetire() {
  isRetire.value = !isRetire.value;
  fetchDataPeriodNew();
}

onMounted(() => {
  if (props.rootId) {
    fetchDataQuota(store.groupId);
    fetchDataPeriod(store.groupId);
    splitterModel.value = store.roundMainCode === "APR" ? 13 : 16;
  }
});
</script>

<template>
  <!-- <q-separator /> -->
  <q-tab-panels v-model="store.tabGroup" animated class="bg-grey-1">
    <q-tab-panel
      style="padding: 0px"
      v-for="(item, index) in itemsTabGroup"
      :key="index"
      :name="item.name"
    >
      <!-- Card โควต้า -->
      <div class="row col-12 q-pa-md" v-if="store.roundMainCode !== 'SPECIAL'">
        <div
          :class="`row col-12 ${
            store.roundMainCode === 'APR'
              ? `q-col-gutter-md`
              : `q-col-gutter-md`
          } items-start`"
        >
          <div
            v-for="(item, index) in store.roundMainCode === 'APR'
              ? itemsCard.slice(0, 5)
              : store.roundMainCode === 'OCT'
              ? itemsCard.slice(5, 12)
              : []"
            :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.lable }}</div>
                  </div>

                  <div :class="`text-${item.color} text-bold`">
                    {{ item.total ? item.total.toLocaleString() : 0 }}
                  </div>
                </div>
              </q-card-section>
            </q-card>
          </div>
          <div
            class="row col justify-end self-center"
            v-if="
              store.roundMainCode !== 'SPECIAL' &&
              checkPermission($route)?.attrIsGet
            "
          >
            <q-btn-dropdown color="blue-5" label="ดาวน์โหลด">
              <q-list>
                <q-item
                  v-for="(item, index) in store.roundMainCode === 'APR'
                    ? store.itemDownloadApr
                    : store.roundMainCode === 'OCT'
                    ? store.itemDownloadOct
                    : []"
                  :key="index"
                  clickable
                  v-close-popup
                  @click="onClickDownload(item, item.type)"
                >
                  <q-item-section>
                    <q-item-label>{{ item.name }}</q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>
            <!-- <q-btn color="blue-5" icon="download" label="ดาวน์โหลด" /> -->
          </div>
        </div>
      </div>
      <!-- <q-separator /> -->

      <!-- Tab ขั้น -->
      <q-card flat bordered>
        <div v-if="store.roundMainCode === 'OCT'" class="row col-12 q-pa-sm">
          <q-toggle
            dense
            :model-value="isRetire"
            color="primary"
            @update:model-value="updateIsShowRetire"
            class="q-pr-md"
          >
            แสดงเฉพาะผู้เกษียณอายุราชการ
          </q-toggle>
        </div>

        <q-splitter v-model="splitterModel" disable class="border-top">
          <template v-slot:before>
            <q-tabs
              v-model="store.tabType"
              vertical
              dense
              class="text-grey-black"
              active-color="blue-5"
              active-class="bg-blue-1"
              indicator-color="blue-5"
              align="left"
            >
              <div
                v-for="(item, index) in itemsTabType"
                :key="index"
                class="row"
                :style="index === 0 ? 'border-bottom: 1px solid #c8d3db;' : ''"
              >
                <q-tab
                  class="col-12"
                  style="justify-content: left"
                  :name="item.type"
                  :label="item.lable"
                  @click="changeTabType()"
                />
              </div>
            </q-tabs>
          </template>
          <template v-slot:after>
            <q-tab-panels
              v-model="store.tabType"
              animated
              swipeable
              vertical
              transition-prev="jump-up"
              transition-next="jump-up"
            >
              <q-tab-panel
                class="q-pa-md"
                v-for="(item, index) in itemsTabType"
                :key="index"
                :name="item.type"
              >
                <TableTabType1
                  v-if="index === 0"
                  v-model:max-page="maxPage"
                  v-model:form-filter="formFilter"
                  :fetch-data-table="fetchDataPeriodNew"
                  :rows="rows"
                  :total="total"
                />
                <TableTabType2
                  v-else
                  :rows="rows"
                  v-model:max-page="maxPage"
                  v-model:form-filter="formFilter"
                  :fetch-data-table="fetchDataPeriodNew"
                  :total="total"
                  :type="item.type"
                />
              </q-tab-panel>
            </q-tab-panels>
          </template>
        </q-splitter>
      </q-card>
    </q-tab-panel>
  </q-tab-panels>

  <DialogInfoCriteria v-model:modal="modalDialogInfoCriteria" />
</template>

<style scoped>
.my-card {
  width: 100%;
  max-width: 200px;
}
.q-tabs--vertical .q-tab {
  padding: 0 20px;
}
.border-top {
  border-top: 1px solid #ededed;
}
</style>
