<script setup lang="ts">
import { ref, onMounted, reactive, watch } from "vue";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";

/** importType*/
import type { QTableProps } from "quasar";
import type {
  NewPagination,
  ItemsMenu,
} from "@/modules/13_salary/interface/index/Main";
import type { Salary } from "@/modules/13_salary/interface/response/Main";
import type { FormQuerySalary } from "@/modules/13_salary/interface/request/Main";
import DialogFormUpload from "@/modules/13_salary/components/SalaryChart/DialogUpload.vue";
import DialogFormMain from "@/modules/13_salary/components/SalaryChart/DialogFormMain.vue";
/** importStore*/
import { useCounterMixin } from "@/stores/mixin";

/** use*/
const isActive = ref<boolean>(false);
const $q = useQuasar();
const router = useRouter();
const {
  date2Thai,
  dialogRemove,
  messageError,
  showLoader,
  hideLoader,
  success,
} = useCounterMixin();

const total = ref<number>();
/** modalDialog*/
const modalDialogFormMain = ref<boolean>(false);
const modalUpload = ref<boolean>(false);
const rowId = ref<string>("");
/** Table*/
const rows = ref<Salary[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    align: "left",
    label: "ชื่อผังบัญชีอัตราเงินเดือน",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posList",
    align: "left",
    label: "ประเภทผังบัญชีเงินเดือน",
    sortable: true,
    field: "posList",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "startDate",
    align: "left",
    label: "วันที่มีผลบังคับใช้",
    sortable: true,
    field: "startDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isActive",
    align: "center",
    label: "สถานะการใช้งาน",
    sortable: true,
    field: "isActive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "name",
  "posList",
  "startDate",
  "isActive",
]);

/** List Mune*/
const itemMenu = ref<ItemsMenu[]>([
  {
    label: "แก้ไข",
    icon: "edit",
    color: "edit",
    type: "edit",
  },
  {
    label: "เอกสารอ้างอิง",
    icon: "mdi-file-document-outline",
    color: "teal",
    type: "upload",
  },
  {
    label: "อัตราเงินเดือน",
    icon: "mdi-format-list-bulleted-triangle",
    color: "secondary",
    type: "salaryRate",
  },
  {
    label: "คัดลอก",
    icon: "content_copy",
    color: "blue-6",
    type: "copy",
  },
]);

/** queryString*/
const formQuery = reactive<FormQuerySalary>({
  page: 1, //*หน้า
  pageSize: 10, //*จำนวนแถวต่อหน้า
  keyword: "", //keyword ค้นหา
});
const maxPage = ref<number>(1);

/**
 * function updatePagination
 * @param newPagination ข้อมูล Pagination ใหม่
 */
function updatePagination(newPagination: NewPagination) {
  formQuery.page = 1;
  formQuery.pageSize = newPagination.rowsPerPage;
}

async function fetchListSalaly() {
  showLoader();
  const page = await formQuery.page.toString();
  const pageSize = await formQuery.pageSize.toString();
  const keyword = await formQuery.keyword.toString();
  await http
    .get(
      config.API.salaryChart +
        `?page=${page}&pageSize=${pageSize}&keyword=${keyword}`
    )
    .then((res) => {
      total.value = res.data.result.total;
      maxPage.value = Math.ceil(res.data.result.total / formQuery.pageSize);
      const data = res.data.result.data;
      rows.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const typeAction = ref<string>("");
const dataRow = ref<Salary>();
async function onClickSalary(type: string, data: Salary | null) {
  modalDialogFormMain.value = !modalDialogFormMain.value;
  typeAction.value = type;

  if (data) {
    dataRow.value = data;
  }
}

async function onClickSalaryRate(id: string) {
  router.push(`/salary/rate/${id}`);
}

async function onClickCoppy(id: string) {
  await http
    .post(config.API.salaryChartCopy, { id: id })
    .then(() => {
      success($q, "คัดลอกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      fetchListSalaly();
    });
}

async function onClickDelete(id: string) {
  dialogRemove($q, async () => {
    await http
      .delete(config.API.salaryChartByid(id))
      .then(() => {
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        fetchListSalaly();
      });
  });
}

async function onClickUpload(type: string, id: string, active: boolean) {
  modalUpload.value = true;
  typeAction.value = type;
  rowId.value = id;
  isActive.value = active;
}

onMounted(async () => {
  await fetchListSalaly();
});

watch([() => formQuery.page, () => formQuery.pageSize], async () => {
  await fetchListSalaly();
});

async function filterFn(page: number) {
  page !== 1 ? (formQuery.page = 1) : await fetchListSalaly();
}
</script>

<template>
  <div class="row items-center">
    <div class="toptitle text-dark row items-center q-py-xs">
      รายการผังบัญชีเงินเดือน
    </div>
  </div>

  <q-card flat bordered class="q-pa-md">
    <div class="col-12 row text-primary">
      <q-btn flat round dense icon="add" @click="onClickSalary('add', null)">
        <q-tooltip>เพิ่มผังบัญชีเงินเดือน </q-tooltip>
      </q-btn>
      <q-space />

      <q-input
        borderless
        dense
        debounce="300"
        outlined
        v-model="formQuery.keyword"
        placeholder="ค้นหา"
        @keydown.enter.prevent="filterFn(formQuery.page)"
      >
        <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"
      />
    </div>

    <div class="col-12 q-pt-sm">
      <d-table
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="id"
        flat
        bordered
        :paging="true"
        dense
        :rows-per-page-options="[10, 25, 50, 100]"
        @update:pagination="updatePagination"
        :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-th auto-width></q-th>
          </q-tr>
        </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 === 'isActive'">
                <q-icon
                  :name="col.value ? 'done' : 'close'"
                  :color="col.value ? 'primary' : 'grey'"
                  size="24px"
                />
              </div>
              <div v-else-if="col.name === 'posList'" class="row">
                <div class="column text-weight-light">
                    <span>ประเภทตำแหน่ง</span>
                    <span>ระดับตำแหน่ง</span>

    
                  </div>
                <div class="column q-ml-sm">
                    <span>{{ props.row.posType }}</span>
                    <span>{{ props.row.isSpecial ? `${props.row.posLevel} (ฉ)` : `${props.row.posLevel}` }}</span>
                    
                    
          
                  </div>
              </div>
              <div v-else-if="col.name === 'salaryType'">
                {{
                  col.value === "OFFICER"
                    ? "ข้าราชการกรุงเทพมหานครสามัญ"
                    : "ลูกจ้างประจำกรุงเทพมหานคร"
                }}
              </div>
              <div v-else-if="col.name === 'startDate'">
                {{ col.value ? date2Thai(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
                      v-for="(item, index) in itemMenu"
                      :key="index"
                      clickable
                      v-close-popup
                      @click.stop="
                        item.type === 'edit'
                          ? onClickSalary('edit', props.row)
                          : item.type === 'salaryRate'
                          ? onClickSalaryRate(props.row.id)
                          : item.type === 'upload'
                          ? onClickUpload(
                              'edit',
                              props.row.id,
                              props.row.isActive
                            )
                          : item.type === 'copy'
                          ? onClickCoppy(props.row.id)
                          : null
                      "
                    >
                      <q-item-section>
                        <div class="row items-center">
                          <q-icon
                            :color="item.color"
                            size="17px"
                            :name="item.icon"
                          />
                          <div class="q-pl-md">{{ item.label }}</div>
                        </div>
                      </q-item-section>
                    </q-item>
                    <q-item
                      v-if="props.row.isActive == false"
                      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">
          ทั้งหมด {{ total }} รายการ
          <q-pagination
            v-model="formQuery.page"
            active-color="primary"
            color="dark"
            :max="maxPage"
            size="sm"
            boundary-links
            direction-links
            :max-pages="5"
          ></q-pagination>
        </template>
      </d-table>
    </div>
  </q-card>

  <DialogFormMain
    v-model:modal="modalDialogFormMain"
    :typeAction="typeAction"
    :data="dataRow"
    :fetchData="fetchListSalaly"
  />
  <DialogFormUpload
    v-model:modal="modalUpload"
    :typeAction="typeAction"
    :id="rowId"
    :fetchData="fetchListSalaly"
    :isActive="isActive"
  />
</template>

<style scoped></style>
