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

import type {
  ListData,
  ResponseData,
} from "@/modules/13_salary/interface/index/EmployeeChart";
import type {
  NewPagination,
  DataOption,
} from "@/modules/13_salary/interface/index/Main";
import DialogFormCriteria from "@/modules/13_salary/components/salaryEmployeeChart/DialogFormCriteria.vue";

/** importType*/
import type { QTableProps } from "quasar";
import { useQuasar } from "quasar";

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

const posTypeOp = ref<DataOption[]>([]);
const posType = ref<string>("");
const maxPage = ref<number>(1);
const $q = useQuasar();
const {
  date2Thai,
  dialogRemove,
  messageError,
  showLoader,
  hideLoader,
  success,
} = useCounterMixin();

/** ข้อมูล Table*/
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posType",
    align: "left",
    label: "กลุ่มงาน",
    sortable: true,
    field: "posType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posName",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "posName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevel",
    align: "left",
    label: "ระดับชั้นงาน",
    sortable: true,
    field: "posLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "rateOldMin",
    align: "left",
    label: "อัตราค่าจ้าง ขั้นต่ำสุด",
    sortable: true,
    field: "rateOldMin",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "groupOld",
    align: "left",
    label: "อัตราค่าจ้าง กลุ่มบัญชีค่าจ่าง",
    sortable: true,
    field: "groupOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "rateMaxOld",
    align: "left",
    label: "อัตราค่าจ้าง ขั้นสูงสุดเดิม",
    sortable: true,
    field: "rateMaxOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "groupRateHigh",
    align: "left",
    label: "อัตราค่าจ้างสูงกว่าฯ กลุ่มบัญชีค่าจ่าง",
    sortable: true,
    field: "groupRateHigh",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "rateHighMax",
    align: "left",
    label: "อัตราค่าจ้างสูงกว่าฯ ขั้นสูงใหม่",
    sortable: true,
    field: "rateHighMax",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "reson",
    align: "left",
    label: "หมายเหตุ",
    sortable: true,
    field: "reson",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

const visibleColumns = ref<string[]>([
  "no",
  "posType",
  "posName",
  "posLevel",
  "rateOldMin",
  "groupOld",
  "rateMaxOld",
  "groupRateHigh",
  "rateHighMax",
  "reson",
]);

const rows = ref<ListData[]>([]);

const formFilter = reactive({
  page: 1,
  pageSize: 10,
  keyword: "",
});

function filterFn() {
  formFilter.page = 1;
  getData();
}

const pagination = ref({
  page: formFilter.page,
  rowsPerPage: formFilter.pageSize,
});

const modalForm = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);
const dataRow = ref<any>({});

function getData() {
  showLoader();
  http
    .get(
      config.API.salaryFormula() +
        `/?page=${formFilter.page}&pageSize=${formFilter.pageSize}&keyword=${formFilter.keyword}&posTypeId=${posType.value}`
    )
    .then((res) => {
      const data = res.data.result.data;
      const total = res.data.result.total;
      maxPage.value = Math.ceil(res.data.result.total / formFilter.pageSize);
      rows.value = data.map((item: ResponseData) => ({
        id: item.id,
        posType: item.posType,
        posName: item.position,
        posLevel: item.posLevel,
        rateOldMin: item.salaryMin,
        groupOld: item.salaryEmployeeMin.sort((a, b) => a - b),
        rateMaxOld: item.salary,
        groupRateHigh: item.group,
        rateHighMax: item.salaryMax,
        reson: item.details,
      }));
    })
    .catch((e) => {
      // messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function editPopup(params: any) {
  modalForm.value = true;
  isStatusEdit.value = true;
  dataRow.value = params;
}

function updatePage(val: number) {
  formFilter.page = val;
  getData();
}

function updatePageSize(newPagination: NewPagination) {
  formFilter.page = 1;
  formFilter.pageSize = newPagination.rowsPerPage;
}

function onClickDelete(id: string) {
  dialogRemove($q, () => {
    http
      .delete(config.API.salaryFormula() + `/${id}`)
      .then(() => {
        getData();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      });
  });
}
watch(
  () => formFilter.pageSize,
  () => {
    getData();
  }
);

/** ดึงข้อมูลกลุ่มงาน */
function getPosType() {
  http
    .get(config.API.salaryEmployeePosType())
    .then((res) => {
      const data = res.data.result;
      posTypeOp.value = data.map((item: any) => ({
        id: item.id,
        name: item.posTypeName,
      }));
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {});
}

onMounted(() => {
  getData();
  getPosType();
});
</script>

<template>
  <q-toolbar class="text-primary" style="padding: 0px">
    <div class="col-3">
      <q-select
        v-model="posType"
        label="กลุ่มงาน"
        outlined
        dense
        :options="posTypeOp"
        option-label="name"
        option-value="id"
        emit-value
        map-options
        @update:model-value="getData"
      >
        <template v-if="posType" v-slot:append>
          <q-icon
            name="cancel"
            @click.stop.prevent="posType = '';getData()"
            class="cursor-pointer"
          />
        </template>
      </q-select>
    </div>
    <q-btn flat round dense icon="add" @click="() => (modalForm = true)">
      <q-tooltip>เพิ่ม </q-tooltip>
    </q-btn>
    <q-space />
    <q-input
      borderless
      dense
      outlined
      v-model="formFilter.keyword"
      placeholder="ค้นหา"
      @keydown.enter.pervrnt="filterFn"
    >
      <template v-slot:append>
        <q-icon name="search" />
      </template>
    </q-input>
    <q-select
      for="#select"
      v-model="visibleColumns"
      multiple
      outlined
      dense
      options-dense
      :display-value="$q.lang.table.columns"
      emit-value
      map-options
      :options="columns"
      option-value="name"
      options-cover
      style="min-width: 150px"
      class="col-xs-12 col-sm-3 col-md-2 q-ml-sm"
    />
  </q-toolbar>

  <d-table
    flat
    bordered
    dense
    :rows="rows"
    :columns="columns"
    row-key="name"
    class="custom-header-table"
    v-model:pagination="pagination"
    :rows-per-page-options="[20, 50, 100, 200]"
    :visible-columns="visibleColumns"
    @update:pagination="updatePageSize"
  >
    <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-th auto-width />
      </q-tr>
      <q-separator />
    </template>
    <template v-slot:body="props">
      <q-tr :props="props" class="cursor-pointer">
        <q-td v-for="col in props.cols" :key="col.name" :props="props">
          <div v-if="col.name === 'no'">
            {{
              (formFilter.page - 1) * Number(pagination.rowsPerPage) +
              props.rowIndex +
              1
            }}
          </div>
          <!-- <div v-else-if="col.name === 'group'">
            {{ col.value ? `กลุ่มที่ (${col.value})` : "-" }}
          </div> -->
          <!-- <div v-else-if="col.name === 'isActive'">
            <q-icon
              :name="col.value ? 'done' : 'close'"
              :color="col.value ? 'primary' : 'grey'"
              size="24px"
            ></q-icon>
          </div> -->
          <div
            v-else-if="
              col.name == 'rateOldMin' ||
              col.name == 'rateMaxOld' ||
              col.name == 'rateHighMax'
            "
          >
            {{ col.value ? col.value.toLocaleString() : "-" }}
          </div>
          <div v-else-if="col.name == 'groupOld'">
            <span v-for="(item, index) in col.value">
              {{ item }}{{ index + 1 == col.value.length ? "" : "," }}
            </span>
            <!-- {{ col.value }} -->
          </div>
          <div v-else>{{ col.value != "" ? col.value : "-" }}</div>
        </q-td>

        <q-td>
          <q-btn
            flat
            dense
            icon="mdi-dots-vertical"
            class="q-pa-none q-ml-xs"
            color="grey-13"
            size="12px"
          >
            <q-menu>
              <q-list dense style="min-width: 200px">
                <q-item clickable v-close-popup>
                  <q-item-section>
                    <div class="row items-center" @click="editPopup(props.row)">
                      <q-icon color="edit" size="17px" name="edit" />
                      <div class="q-pl-md">แก้ไขข้อมูล</div>
                    </div>
                  </q-item-section>
                </q-item>
                <q-item
                  clickable
                  v-close-popup
                  @click.stop="onClickDelete(props.row.id)"
                >
                  <q-item-section>
                    <div class="row items-center">
                      <q-icon color="red" size="17px" name="delete" />
                      <div class="q-pl-md">ลบ</div>
                    </div>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-menu>
          </q-btn>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:pagination="scope">
      <q-pagination
        v-model="formFilter.page"
        active-color="primary"
        color="dark"
        :max="maxPage"
        :max-pages="5"
        size="sm"
        boundary-links
        direction-links
        @update:model-value="updatePage"
      ></q-pagination>
    </template>
  </d-table>

  <DialogFormCriteria
    v-model:modal="modalForm"
    v-model:isStatusEdit="isStatusEdit"
    :data="dataRow"
    :get-data-Main="getData"
  />
</template>

<style scoped></style>
