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

/** importType*/
import type { QInput, QTableProps } from "quasar";
import type { NewPagination } from "@/modules/08_registryEmployee/interface/index/Main";
import type { DataEmployee } from "@/modules/08_registryEmployee/interface/response/Employee";

/** importComponents*/
import DialogAddEmployee from "@/modules/08_registryEmployee/components/DialogAddEmployee.vue";
import DialogSelectPos from "@/modules/08_registryEmployee/components/DialogSelectPos.vue";
import DialogSendOrder from "@/modules/08_registryEmployee/components/DialogSendOrder.vue";

/** inportStore*/
import { useCounterMixin } from "@/stores/mixin";
import { useRegistryEmp } from "@/modules/08_registryEmployee/stores/registry-employee";

const $q = useQuasar();
const router = useRouter();
const {
  success,
  messageError,
  showLoader,
  hideLoader,
  date2Thai,
  dialogRemove,
} = useCounterMixin();
const { statusText } = useRegistryEmp();

const filter = ref<string>("");

/** Table*/
const rows = ref<DataEmployee[]>([]);
const maxPage = ref<number>(0);
const total = ref<number>(0);
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  type: "temp",
});

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: (row) =>
      (queryParams.page - 1) * queryParams.pageSize +
      rows.value.indexOf(row) +
      1,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },
  {
    name: "fullname",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: (row) => `${row.prefix}${row.firstName}  ${row.lastName}`,
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },
  {
    name: "draftOrganizationOrganization",
    align: "left",
    label: "หน่วยงานที่รับการบรรจุ",
    sortable: true,
    field: "draftOrganizationOrganization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "draftPositionEmployee",
    align: "left",
    label: "หน่วยงานที่บรรจุ",
    sortable: true,
    field: "draftPositionEmployee",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },

  {
    name: "govAge",
    align: "left",
    label: "อายุราชการ(ปี)",
    sortable: true,
    field: "govAge",
    format(val) {
      return val;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateEmployment",
    align: "left",
    label: "วันที่จ้าง",
    sortable: true,
    field: "dateEmployment",
    format: (val) => date2Thai(val),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  // {
  //   name: "dateStart",
  //   align: "left",
  //   label: "วันที่เริ่มปฎิบัติราชการ",
  //   sortable: true,
  //   field: "dateStart",
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
  {
    name: "salaryDate",
    align: "left",
    label: "วันที่แต่งตั้ง",
    sortable: true,
    field: "salaryDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "age",
    align: "left",
    label: "อายุ",
    sortable: true,
    field: "age",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่สร้าง",
    sortable: true,
    field: "createdAt",
    format(val) {
      return date2Thai(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateRetireLaw",
    align: "left",
    label: "วันที่พ้นราชการ",
    sortable: true,
    field: "dateRetireLaw",
    format(val) {
      return date2Thai(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "statustext",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: (row) => statusText(row.draftOrgEmployeeStatus),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<String[]>([
  "no",
  "citizenId",
  "fullname",
  "draftOrganizationOrganization",
  "draftPositionEmployee",
  "govAge",
  "dateEmployment",
  // "dateStart",
  "age",
  "createdAt",
  "dateRetireLaw",
  "statustext",
]);

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

watch(
  () => queryParams.pageSize,
  () => {
    fetchList();
  }
);

function fetchList() {
  showLoader();
  http
    .get(config.API.registryNew("-employee"), { params: queryParams })
    .then((res) => {
      maxPage.value = Math.ceil(res.data.result.total / queryParams.pageSize);
      total.value = res.data.result.total;
      rows.value = res.data.result.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onClickDelete(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.registryNew("-employee") + `/${id}`)
      .then(() => {
        success($q, "ลบข้อมูลสำเร็จ");
        fetchList();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function redirectToPageDetail(id: string) {
  router.push(`/registry-employee/${id}`);
}

/** เพิ่มข้อมูลลูกจ้างชั่วคราว*/
const modalAddEmployee = ref<boolean>(false);

function onClickAddEmployee() {
  modalAddEmployee.value = true;
}

/** เกำหนดตำแหน่ง */
const modalPos = ref<boolean>(false);
const dataRow = ref<DataEmployee>();
function onClickSelectPos(data: DataEmployee) {
  modalPos.value = true;
  dataRow.value = data;
}

/** ส่งไปออกคำสั่ง*/
const modalSendOrder = ref<boolean>(false);
function onClickSendOrder() {
  modalSendOrder.value = true;
}

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

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายชื่อลูกจ้างชั่วคราว
  </div>
  <q-card flat bordered class="q-pa-md">
    <div class="col-12 row items-center">
      <q-btn
        flat
        round
        color="primary"
        icon="mdi-plus"
        @click="onClickAddEmployee"
      >
        <q-tooltip>เพิ่มข้อมูล</q-tooltip>
      </q-btn>
      <q-btn
        flat
        round
        color="primary"
        icon="mdi-account-arrow-right"
        @click="onClickSendOrder"
      >
        <q-tooltip>ส่งรายชื่อไปออกคำสั่ง</q-tooltip>
      </q-btn>
      <q-space />
      <div class="items-center" style="display: flex">
        <!-- ค้นหาข้อความใน table -->
        <q-input
          standout
          dense
          v-model="filter"
          ref="filterRef"
          outlined
          debounce="300"
          placeholder="ค้นหา"
          style="max-width: 200px"
          class="q-ml-sm"
        >
          <template v-slot:append>
            <q-icon v-if="filter == ''" name="search" />
            <q-icon v-if="filter !== ''" name="clear" class="cursor-pointer" />
          </template>
        </q-input>
        <!-- แสดงคอลัมน์ใน table -->
        <q-select
          v-model="visibleColumns"
          :display-value="$q.lang.table.columns"
          multiple
          outlined
          dense
          :options="columns"
          options-dense
          option-value="name"
          map-options
          emit-value
          style="min-width: 150px"
          class="gt-xs q-ml-sm"
        />
      </div>
    </div>
    <div class="col-12 q-pt-sm">
      <d-table
        :rows="rows"
        :columns="columns"
        :visible-columns="visibleColumns"
        :filter="filter"
        row-key="id"
        :rows-per-page-options="[10, 25, 50, 100]"
        @update:pagination="updatePagination"
      >
        <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>
        </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">
              <template v-if="col.name === 'draftOrganizationOrganization'">
                <div
                  v-if="
                    props.row.orgName !== null ||
                    props.row.positionPath !== null
                  "
                >
                  <div class="col-4">
                    <div class="text-weight-medium">
                      {{ props.row.root !== null ? props.row.root : "-" }}
                      {{
                        props.row.rootShortName !== null
                          ? `(${props.row.rootShortName})`
                          : ""
                      }}
                    </div>
                    <div class="text-weight-light">
                      {{
                        props.row.nodeName !== null ? props.row.nodeName : ""
                      }}
                      {{
                        props.row.nodeShortName !== null
                          ? `(${props.row.nodeShortName}${props.row.posNo})`
                          : ""
                      }}
                    </div>
                  </div>
                </div>

                <div v-else>
                  <div class="col-4">
                    <div class="text-weight-medium">-</div>
                  </div>
                </div>
              </template>
              <div v-else>
                {{ col.value !== null && col.value !== "" ? col.value : "-" }}
              </div>
            </q-td>
            <q-td auto-width>
              <q-btn
                icon="mdi-dots-vertical"
                size="12px"
                color="grey-7"
                flat
                round
                dense
              >
                <q-menu transition-show="jump-down" transition-hide="jump-up">
                  <q-list dense style="min-width: 160px">
                    <q-item
                      clickable
                      v-close-popup
                      v-if="
                        props.row.draftOrgEmployeeStatus === null ||
                        props.row.draftOrgEmployeeStatus === 'REPORT'
                      "
                      @click.pervent="onClickSelectPos(props.row)"
                    >
                      <q-item-section
                        style="min-width: 0px"
                        avatar
                        class="q-py-sm"
                      >
                        <q-icon
                          color="blue"
                          size="xs"
                          name="mdi-account-settings"
                        />
                      </q-item-section>
                      <q-item-section>กำหนดตำแหน่ง</q-item-section>
                    </q-item>
                    <q-item
                      clickable
                      v-close-popup
                      @click.pervent="redirectToPageDetail(props.row.id)"
                    >
                      <q-item-section
                        style="min-width: 0px"
                        avatar
                        class="q-py-sm"
                      >
                        <q-icon color="primary" size="xs" name="mdi-account" />
                      </q-item-section>
                      <q-item-section>แก้ไขข้อมูล</q-item-section>
                    </q-item>
                    <q-separator />
                    <q-item
                      clickable
                      v-close-popup
                      @click.pervent="onClickDelete(props.row.id)"
                    >
                      <q-item-section
                        style="min-width: 0px"
                        avatar
                        class="q-py-sm"
                      >
                        <q-icon color="red" size="xs" name="mdi-delete" />
                      </q-item-section>
                      <q-item-section>ลบ</q-item-section>
                    </q-item>

                    <q-separator />
                  </q-list>
                </q-menu>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
        <template v-slot:pagination="scope">
          ทั้งหมด {{ total }} รายการ
          <q-pagination
            v-model="queryParams.page"
            active-color="primary"
            color="dark"
            :max="Number(maxPage)"
            size="sm"
            boundary-links
            direction-links
            :max-pages="5"
            @update:model-value="fetchList"
          ></q-pagination>
        </template>
      </d-table>
    </div>
  </q-card>

  <DialogAddEmployee v-model:modal="modalAddEmployee" :fetchData="fetchList" />

  <DialogSelectPos
    v-model:modal="modalPos"
    :dataRow="dataRow"
    :fetchData="fetchList"
  />

  <DialogSendOrder v-model:modal="modalSendOrder" :fetchData="fetchList" />
</template>
