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

import http from "@/plugins/http";
import config from "@/app.config";
import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useEditPosDataStore } from "@/modules/04_registryPerson/stores/Edit";

import type { QTableColumn } from "quasar";
import type { DataPosition } from "@/modules/04_registryPerson/interface/response/Edit";

import DialogForm from "@/modules/04_registryPerson/views/edit/components/DialogForm.vue";

const $q = useQuasar();
const route = useRoute();
const store = useEditPosDataStore();
const {
  date2Thai,
  findOrgName,
  onSearchDataTable,
  dialogRemove,
  showLoader,
  hideLoader,
  messageError,
  success,
  findOrgNameHtml,
} = useCounterMixin();

const empType = ref<string>(route.params.type.toString());
const profileId = ref<string>(route.params.id.toString());

const tabs = defineModel<string>("tabs", { required: true });
const statusCheckEdit = defineModel<string>("statusCheckEdit", {
  required: true,
});

//Table
const isLoad = ref<boolean>(true);
const rowIndex = ref<number>(0);
const rows = ref<DataPosition[]>([]);
const rowsMain = ref<DataPosition[]>([]);
const keyword = ref<string>("");
const baseColumns = ref<QTableColumn[]>([
  {
    name: "commandDateAffect",
    align: "left",
    label: "วันที่คำสั่งมีผล",
    sortable: false,
    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: false,
    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: "posNo",
    align: "left",
    label: empType.value === "employee" ? "ตำแหน่งเลขที่" : "เลขที่ตำแหน่ง",
    sortable: false,
    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: empType.value === "employee" ? "ตำแหน่ง" : "ตำแหน่งในสายงาน",
    sortable: false,
    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: empType.value === "employee" ? "กลุ่มงาน" : "ตำแหน่งประเภท",
    sortable: false,
    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: empType.value === "employee" ? "ระดับชั้นงาน" : "ระดับ",
    sortable: false,
    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: false,
    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: false,
    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: false,
    field: "commandCode",
    format(val, row) {
      return store.convertCommandCodeName(val);
    },
    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: false,
    field: "organization",
    headerStyle: "font-size: 14px",
    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: empType.value === "employee" ? "ค่าจ้าง" : "เงินเดือน",
    sortable: false,
    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: false,
    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: false,
    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: false,
    field: "remark",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumns = ref<string[]>([
  "commandDateAffect",
  "posNo",
  "positionName",
  "positionType",
  "positionLevel",
  "positionExecutive",
  "amount",
  "positionSalaryAmount",
  "mouthSalaryAmount",
  "commandNo",
  "commandCode",
  "commandDateSign",
  "organization",
  "remark",
]);
const columns = computed<QTableColumn[]>(() => {
  if (empType.value === "employee") {
    if (baseColumns.value) {
      return baseColumns.value.filter(
        (column) =>
          column.name !== "positionSalaryAmount" &&
          column.name !== "mouthSalaryAmount"
      );
    }
  }
  return baseColumns.value;
});

const modal = ref<boolean>(false);

/** function fetch ข้อมูลรายการตำแหน่งเงินเดือน*/
async function fetchData() {
  isLoad.value = true;
  rowsMain.value = [];
  rows.value = [];
  const paht =
    tabs.value === "PENDING"
      ? `/${empType.value}/${profileId.value}`
      : `/${empType.value}/done/${profileId.value}`;
  http
    .get(config.API.salaryTemp + `${paht}`)
    .then((res) => {
      const data = res.data.result;
      rowsMain.value = data;
      rows.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoad.value = false;
    });
}

/** function ค้นหาข้อมูลรายการในตาราง*/
function serchDataTable() {
  rows.value = onSearchDataTable(
    keyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

/**
 * funciton
 * @param index
 */
function onEditData(index: number) {
  rowIndex.value = index;
  modal.value = true;
}

async function onSwapData(action: string, id: string) {
  showLoader();
  await http
    .get(config.API.salaryTemp + `/swap/${action}/${id}`)
    .then(async () => {
      await fetchData();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onDeleteData(id: string, isDelete: boolean) {
  dialogRemove($q, async () => {
    showLoader();
    const path = isDelete ? "/delete-renew" : "/delete";
    await http
      .post(config.API.salaryTemp + `${path}`, {
        type: empType.value,
        salaryId: id,
      })
      .then(async () => {
        await fetchData();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function classColorRow(isDelete: boolean, isEdit: boolean, isEntry: boolean) {
  return isDelete
    ? "text-red"
    : isEdit
    ? "text-orange"
    : isEntry
    ? "text-grey"
    : "";
}

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

<template>
  <div class="row q-col-gutter-sm">
    <div class="col-12">
      <div class="row q-col-gutter-sm">
        <q-space />
        <q-input
          dense
          outlined
          v-model="keyword"
          label="ค้นหา"
          @keydown.enter.pervent="serchDataTable"
        >
          <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"
        row-key="id"
        flat
        bordered
        dense
        :columns="columns"
        :rows="rows"
        :paging="true"
        :rows-per-page-options="[20, 50, 100]"
        :visible-columns="visibleColumns"
        :loading="isLoad"
      >
        >
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th v-if="tabs === 'PENDING' && statusCheckEdit !== 'CHECKED'" />
            <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-if="tabs === 'PENDING' && statusCheckEdit !== 'CHECKED'">
              <q-btn
                dense
                flat
                round
                :color="props.rowIndex + 1 == 1 ? 'grey' : 'green'"
                :disable="props.rowIndex + 1 == 1"
                icon="mdi-arrow-up-bold"
                @click.stop.pervent="onSwapData('up', props.row.id)"
              />
              <q-btn
                dense
                flat
                round
                :color="rows.length == props.rowIndex + 1 ? 'grey' : 'red'"
                :disable="rows.length == props.rowIndex + 1"
                icon="mdi-arrow-down-bold"
                @click.stop.pervent="onSwapData('down', props.row.id)"
              >
              </q-btn>

              <q-btn
                flat
                dense
                round
                color="edit"
                icon="edit"
                @click.stop.pervent="onEditData(props.rowIndex)"
              >
                <q-tooltip>แก้ไขข้อมูล</q-tooltip>
              </q-btn>
              <q-btn
                flat
                dense
                round
                :icon="props.row.isDelete ? 'mdi-refresh-circle' : 'delete'"
                :color="props.row.isDelete ? 'orange' : 'red'"
                @click.stop.pervent="
                  onDeleteData(props.row.id, props.row.isDelete)
                "
              >
                <q-tooltip>{{
                  props.row.isDelete ? "ย้อนกลับข้อมูล" : "ลบ"
                }}</q-tooltip>
              </q-btn>
            </q-td>
            <q-td
              v-for="col in props.cols"
              :key="col.id"
              :class="
                tabs === 'PENDING'
                  ? classColorRow(
                      props.row.isDelete,
                      props.row.isEdit,
                      props.row.isEntry
                    )
                  : ''
              "
            >
              <div
                v-if="col.name === 'organization'"
                class="text-html table_ellipsis"
              >
                {{
                  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-if="col.name === 'commandCode'"
                class="table_ellipsis"
              >
                {{ col.value ? col.value : "-" }}
              </div>
              <div v-else>
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </div>

  <DialogForm
    v-model:modal="modal"
    v-model:row-index="rowIndex"
    :emp-type="empType"
    :row-data="rows"
    :fetch-data="fetchData"
  />
</template>

<style scoped></style>
