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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";

/** importType*/
import type { QTableColumn } from "quasar";
import type { DataPosSalary } from "@/modules/13_salary/interface/response/Main";
import type { ResListSalary } from "@/modules/04_registryPerson/interface/response/Salary";

import SkeletonTable from "@/components/SkeletonTable.vue";
import DialogPreviewCommand from "@/modules/18_command/components/DialogPreviewCommand.vue";

const $q = useQuasar();
const {
  date2Thai,
  messageError,
  onSearchDataTable,
  findOrgName,
  findOrgNameHtml,
} = useCounterMixin();

/** props*/
const profileId = defineModel<string>("profileId", { required: true });
const employeeClass = defineModel<string>("employeeClass", { required: true });
const citizenId = defineModel<string>("citizenId", { required: true });

const modalCommand = ref<boolean>(false);
const command = ref<string>("");
const commandId = ref<string>("");
const isLoading = ref<boolean>(true);

/** Table*/
const keyword = ref<string>("");
const rows = ref<DataPosSalary[]>([]);
const rowsData = ref<DataPosSalary[]>([]);
const baseColumns = ref<QTableColumn[]>([
  {
    name: "commandDateAffect",
    align: "left",
    label: "วันที่คำสั่งมีผล",
    sortable: true,
    field: "commandDateAffect",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "commandDateSign",
    align: "left",
    label: "วันที่ลงนาม",
    sortable: true,
    field: "commandDateSign",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posNumCodeSit",
    align: "left",
    label: "หน่วยงานที่ออกคำสั่ง",
    sortable: false,
    field: "posNumCodeSit",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.posNumCodeSitAbb && row.posNumCodeSit
        ? `${row.posNumCodeSit} (${row.posNumCodeSitAbb})`
        : row.posNumCodeSit
        ? row.posNumCodeSit
        : "-";
    },
  },
  {
    name: "posNo",
    align: "left",
    label:
      employeeClass.value === "-employee" ? "ตำแหน่งเลขที่" : "เลขที่ตำแหน่ง",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.posNoAbb && row.posNo
        ? `${row.posNoAbb}${row.posNo}`
        : row.posNo
        ? row.posNo
        : "-";
    },
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionName",
    align: "left",
    label: employeeClass.value === "-employee" ? "ตำแหน่ง" : "ตำแหน่งในสายงาน",
    sortable: true,
    field: "positionName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionType",
    align: "left",
    label: employeeClass.value === "-employee" ? "กลุ่มงาน" : "ตำแหน่งประเภท",
    sortable: true,
    field: "positionType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionLevel",
    align: "left",
    label: employeeClass.value === "-employee" ? "ระดับชั้นงาน" : "ระดับ",
    sortable: true,
    field: "positionLevel",
    format(val, row) {
      return `${
        row.positionLevel
          ? row.positionLevel
          : row.positionCee
          ? row.positionCee
          : "-"
      }`;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionExecutive",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: true,
    field: "positionExecutive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "commandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "commandNo",
    format(val, row) {
      return row.commandNo && row.commandYear
        ? `${row.commandNo}/${Number(row.commandYear) + 543}`
        : "";
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "commandCode",
    align: "left",
    label: "ประเภทคำสั่ง",
    sortable: true,
    field: "commandCode",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "organization",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "organization",
    headerStyle: "font-size: 14px;min-width:280px",
    style: "font-size: 14px",
    format(val, row) {
      return findOrgName({
        root: row.orgRoot,
        child1: row.orgChild1,
        child2: row.orgChild2,
        child3: row.orgChild3,
        child4: row.orgChild4,
      });
    },
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "amount",
    align: "left",
    label: employeeClass.value === "-employee" ? "ค่าจ้าง" : "เงินเดือน",
    sortable: true,
    field: "amount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(v, row) {
      return row.amount
        ? `${row.amount.toLocaleString()}${
            row.amountSpecial !== 0 && row.amountSpecial
              ? ` (${row.amountSpecial.toLocaleString()})`
              : ""
          }`
        : "-";
    },
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "mouthSalaryAmount",
    align: "left",
    label: "เงินค่าตอบแทนรายเดือน",
    sortable: true,
    field: "mouthSalaryAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionSalaryAmount",
    align: "left",
    label: "เงินประจำตำแหน่ง",
    sortable: true,
    field: "positionSalaryAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },

  {
    name: "remark",
    align: "left",
    label: "หมายเหตุ",
    sortable: true,
    field: "remark",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v, false, true),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const columns = computed<QTableColumn[]>(() => {
  if (employeeClass.value === "-employee") {
    if (baseColumns.value) {
      return baseColumns.value.filter(
        (column) =>
          column.name !== "positionSalaryAmount" &&
          column.name !== "mouthSalaryAmount"
      );
    }
  }
  return baseColumns.value.filter(
    (e: QTableColumn) =>
      e.name !== "lastUpdateFullName" && e.name !== "lastUpdatedAd"
  );
});
const visibleColumns = ref<string[]>([
  "commandDateAffect",
  "posNumCodeSit",
  "posNo",
  "positionName",
  "positionType",
  "positionLevel",
  "positionExecutive",
  "amount",
  "positionSalaryAmount",
  "mouthSalaryAmount",
  "commandNo",
  "commandCode",
  "commandDateSign",
  "organization",
  "remark",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);

/** function fetch ข้อมูลเงินเดือน / ค่าจ้าง */
function fetchListSalary() {
  isLoading.value = true;
  http
    .get(config.API.salaryListCard(profileId.value, employeeClass.value))
    .then((res) => {
      rowsData.value = res.data.result;
      onSearch();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoading.value = false;
    });
}

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

function onRefCommand(data: ResListSalary) {
  modalCommand.value = true;
  command.value = data.refCommandNo;
  commandId.value = data.commandId;
}

onMounted(() => {
  fetchListSalary();
});
</script>

<template>
  <q-card-section class="q-pt-none">
    <div class="row items-center q-gutter-x-sm q-pb-sm">
      <q-space />
      <q-input
        dense
        outlined
        v-model="keyword"
        label="ค้นหา"
        class="q-mr-sm"
        @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>
    <div class="col-12">
      <SkeletonTable v-if="isLoading" :columns="columns" />

      <d-table
        v-else
        ref="table"
        row-key="id"
        flat
        bordered
        dense
        :paging="true"
        :rows-per-page-options="[20, 50, 100]"
        :visible-columns="visibleColumns"
        :rows="rows"
        :columns="columns"
      >
        <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.id"
              :class="props.row.isEntry ? 'text-red' : ''"
            >
              <div
                v-if="col.name == 'commandNo' && props.row.commandId"
                @click="col.value ? onRefCommand(props.row) : null"
                :class="
                  col.value
                    ? 'table_ellipsis text-blue cursor-pointer'
                    : 'table_ellipsis'
                "
              >
                {{ col.value ? col.value : "-" }}
                <q-tooltip v-if="col.value">ดูคำสั่ง</q-tooltip>
              </div>

              <div v-else-if="col.name == 'organization'" class="text-html">
                {{
                  props.row
                    ? findOrgNameHtml({
                        root: props.row.orgRoot,
                        child1: props.row.orgChild1,
                        child2: props.row.orgChild2,
                        child3: props.row.orgChild3,
                        child4: props.row.orgChild4,
                      })
                    : "-"
                }}
              </div>
              <div v-else>
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card-section>

  <DialogPreviewCommand
    v-model:modal="modalCommand"
    v-model:command="command"
    v-model:commandId="commandId"
    :citizen-id="citizenId"
  />
</template>

<style scoped></style>
