<script setup lang="ts">
import { ref, useAttrs, onMounted, reactive, watch } from "vue";
import { useQuasar } from "quasar";
import { useRoute, useRouter } from "vue-router";

import http from "@/plugins/http";
import config from "@/app.config";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useTransferDataStore } from "@/modules/05_placement/store";

import type { QTableProps } from "quasar";
import type {
  FormMainProbation,
  FormMainProbation2,
  OpfillterTypeSt,
} from "@/modules/05_placement/interface/request/Main";

import DialogHeader from "@/modules/04_registry/components/DialogHeader.vue";
import DialogOrder from "@/modules/05_placement/components/probation/DialogOrder.vue";

const $q = useQuasar(); //ใช้ noti quasar
const storeFn = useTransferDataStore();
const mixin = useCounterMixin();
const route = useRoute();
const router = useRouter();
const { statusProbationMain } = storeFn;
const { messageError, success, showLoader, hideLoader, dialogConfirm } = mixin;

const modalCommand = ref<boolean>(false); // ตัวแปร popup ออกคำสั่ง
const filterRef = ref<any>(null);
const modal = ref<boolean>(false);
const paging = ref<boolean>(true);
const filterRef2 = ref<any>(null);
const attrs = ref<any>(useAttrs());
const paging2 = ref<boolean>(true);
const fillterStatus = ref<any>([]);
const fillter = ref<any>("");
const filterKeyword = ref<string>("");
const filterKeyword2 = ref<string>("");
const rows = ref<FormMainProbation[]>([]);
const rows2 = ref<FormMainProbation2[]>([]);
const dataUpdate = ref<FormMainProbation[]>([]);
const Opfillter = ref<OpfillterTypeSt[]>([]);
const Opfillter2 = ref<OpfillterTypeSt[]>([]);
const formProbation = reactive({ keyword: "", pageSize: 10, page: 1 });
const formMain = reactive({ keyword: "", pageSize: 10, page: 1 });
const maxPage = ref<number>(1);

const modalAdd = ref<boolean>(false);
const personId = ref<string>(""); //เก็บ id คน ตาม row
const topic = ref<string>(
  "แต่งตั้งคณะกรรมการประเมินผลการทดลองปฏิบัติหน้าที่ราชการ"
);

const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

const total = ref<number>(0);
const totalList = ref<number>(1);

const pagination2 = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

/** ข้อมูลที่เเสดง */
const visibleColumns = ref<string[]>([
  "no",
  "name",
  "position_line",
  "position_level",
  "organization",
  "probation_no",
  "order_number",
  "probation_status",
]);

/** หัวตาราง */
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position_line",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    sortable: true,
    field: "position_line",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position_level",
    align: "left",
    label: "ระดับ",
    sortable: true,
    field: "position_level",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organization",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px ",
    classes: "table_ellipsis",
  },
  {
    name: "probation_no",
    align: "center",
    label: "ครั้งที่ทดลองปฏิบัติหน้าที่ราชการ",
    sortable: true,
    field: "probation_no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.probation_no ? row.probation_no : "-";
    },
  },
  {
    name: "order_number",
    align: "center",
    label: "เลขที่คําสั่งบรรจุแต่งตั้ง",
    sortable: true,
    field: "order_number",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.order_number ? row.order_number : "-";
    },
  },
  {
    name: "probation_status",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "probation_status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/** หัวตาราง2 */
const columns2 = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullname",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullname",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevelName",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: true,
    field: "posLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return (
        (row.posTypeName ? row.posTypeName : "") +
        (row.posLevelName !== null ? " (" + row.posLevelName + ")" : "")
      );
    },
  },
  {
    name: "organizationOrganization",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "organizationOrganization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "status",
    align: "left",
    label: "ทดลองปฏิบัติหน้าที่ราชการ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "refCommandNo",
    align: "center",
    label: "เลขที่คําสั่งบรรจุแต่งตั้ง",
    sortable: true,
    field: "refCommandNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/** get ข้อมูล */
async function getpersonalList() {
  showLoader();
  await http
    .get(
      config.API.probationPersonalList() +
        `?status=${fillter.value}&page=${pagination.value.page}&pageSize=${pagination.value.rowsPerPage}&keyword=${filterKeyword.value}`
    )
    .then(async (res) => {
      const data = await res.data.result.data;
      const resTotal = await res.data.result.total;
      rows.value = data;
      fillterStatus.value = data;
      dataUpdate.value = rows.value;
      Opfillter.value = storeFn.optionStatusProbation;
      Opfillter2.value = storeFn.optionStatusProbation;
      totalList.value = Math.ceil(resTotal / pagination.value.rowsPerPage);
      total.value = resTotal;
      hideLoader();
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

async function onclickAddProbation() {
  modal.value = true;
  modal.value && showLoader();
  await http
    .post(config.API.orgProfileProbation, formProbation)
    .then((res) => {
      maxPage.value = Math.ceil(res.data.result.total / formProbation.pageSize);
      rows2.value = res.data.result.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

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

async function filterKeyword2Fn(page: number) {
  page !== 1 ? (formProbation.page = 1) : await onclickAddProbation();
}

/**
 * เพิ่มข้อมูล ผู้ทดลองปฏิบัติหน้าที่ราชการ
 * @param data personal data
 */
function clickAdd(data: any) {
  const body = {
    id: data.id,
    prefix: data.prefix,
    rank: data.rank,
    firstName: data.firstName,
    lastName: data.lastName,
    position: data.position,
    idcard: data.idcard,
    order_number: data.refCommandNo ? data.refCommandNo : "",
    posLevelName: data.posLevelName,
    posTypeName: data.posTypeName,
    posNo: data.posNo,
    positionField: data.positionField,
    positionArea: data.positionArea,
    posExecutiveName: data.posExecutiveName,
    positionExecutiveField: data.positionExecutiveField,
    isProbation: data.isProbation,
    orgRootName: data.orgRootName,
    orgChild1Name: data.orgChild1Name,
    orgChild2Name: data.orgChild2Name,
    orgChild3Name: data.orgChild3Name,
    orgChild4Name: data.orgChild4Name,

    root: data.root,
    child1: data.orgChild1,
    child2: data.orgChild2,
    child3: data.orgChild3,
    child4: data.orgChild4,
  };
  dialogConfirm(
    $q,
    async () => {
      showLoader();

      await http
        .post(config.API.personalAdd(), body)
        .then(async () => {
          await http
            .get(config.API.orgProfileStatus(data.id))
            .then(async (res) => {
              await getpersonalList();
              success($q, "เพิ่มข้อมูลสำเร็จ");
              clickClose();
              hideLoader();
            })
            .catch((e) => {
              messageError($q, e);
              hideLoader();
            });
        })
        .catch((e) => {
          messageError($q, e);
          hideLoader();
        })
        .finally(() => {});
    },
    "ยันยันการเพิ่มข้อมูล",
    "ต้องการเพิ่มข้อมูลนี้หรือไม่ ?"
  );
}
/** ปิด dialog */
async function clickClose() {
  modal.value = false;
}

/** reset ฟิลเตอร์ */
function resetFilter() {
  filterKeyword.value = "";
  filterRef.value.focus();
  getSearchMain();
}

/** reset ฟิลเตอร์ ใน dialog */
function resetFilter2() {
  filterKeyword2.value = "";
  filterRef2.value.focus();
}

function paginationLabel(start: string, end: string, total: string) {
  if (paging.value == true) return " " + start + "-" + end + " ใน " + total;
  else return start + "-" + end + " ใน " + total;
}

function paginationLabel2(start: string, end: string, total: string) {
  if (paging2.value == true) return " " + start + "-" + end + " ใน " + total;
  else return start + "-" + end + " ใน " + total;
}

/**
 * ค้นหาตาม text
 * @param val ค่าที่ค้นหา
 * @param update fn
 */
function filterFn(val: string, update: any) {
  if (val == "") {
    update(() => {
      Opfillter2.value = Opfillter.value;
      fillter.value = undefined;
    });
  } else {
    update(() => {
      Opfillter2.value = Opfillter.value.filter(
        (e: any) => e.value.search(val) !== -1
      );
    });
  }
}

/** ส่งไปออกคำสั่ง */
function onCommand() {
  modalCommand.value = true;
}

function onSubmitAdd() {
  dialogConfirm($q, () => {
    const body = {
      profileId: personId.value,
      topic: topic.value,
    };
    showLoader();
    http
      .post(config.API.appointMain, body)
      .then((res) => {
        if (res) {
          closeAdd();
          hideLoader();
          router.push(`/probation/assign/${res.data.result}`);
        }
      })
      .catch((e) => {
        messageError($q, e);
        hideLoader();
      })
      .finally(() => {});
  });
}

/** แต่งตั้งคณะกรรมการประเมินผลการทดลองปฏิบัติหน้าที่ราชการ */
function onAdd(id: string) {
  modalAdd.value = true;
  personId.value = id;
}

/** ปิด popup แต่งตั้งคณะกรรมการประเมินผลการทดลองปฏิบัติหน้าที่ราชการ */
function closeAdd() {
  modalAdd.value = false;
  personId.value = "";
  topic.value = "แต่งตั้งคณะกรรมการประเมินผลการทดลองปฏิบัติหน้าที่ราชการ";
}

function getSearchMain() {
  pagination.value.page = 1;
  getpersonalList();
}

watch([() => formProbation.page, () => formProbation.pageSize], () => {
  onclickAddProbation();
});

watch(
  () => pagination.value.rowsPerPage,
  async () => {
    getSearchMain();
  }
);

/** get ค่า เมื่อโหลดหน้า */
onMounted(async () => {
  getpersonalList();
});
</script>

<template>
  <q-card flat>
    <div class="row q-col-gutter-sm">
      <div class="row col-12 q-col-gutter-sm">
        <div class="row">
          <q-select
            v-model="fillter"
            label="สถานะ"
            dense
            map-options
            option-label="value"
            :options="Opfillter2"
            option-value="id"
            lazy-rules
            emit-value
            hide-bottom-space
            :readonly="false"
            :borderless="false"
            :outlined="true"
            :hide-dropdown-icon="false"
            @update:model-value="getSearchMain()"
            @filter="filterFn"
            use-input
            behavior="menu"
          >
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
              </q-item>
            </template>
          </q-select>

          <div>
            <q-btn
              v-if="checkPermission($route)?.attrIsCreate"
              @click="onclickAddProbation"
              flat
              round
              color="add"
              icon="mdi-plus"
            >
              <q-tooltip>เพิ่มผู้ทดลองปฏิบัติหน้าที่ราชการ</q-tooltip>
            </q-btn>
          </div>
          <div>
            <q-btn
              v-if="
                checkPermission($route)?.attrIsUpdate &&
                checkPermission($route)?.attrIsGet
              "
              @click="onCommand"
              flat
              round
              color="add"
              icon="mdi-account-arrow-right"
            >
              <q-tooltip>ส่งไปออกคำสั่ง</q-tooltip>
            </q-btn>
          </div>
        </div>

        <q-space />

        <q-input
          class="col-xs-12 col-sm-3 col-md-2"
          standout
          dense
          v-model="filterKeyword"
          ref="filterRef"
          outlined
          debounce="300"
          placeholder="ค้นหา"
          @keydown.enter.prevent="getSearchMain()"
        >
          <template v-slot:append>
            <q-icon v-if="filterKeyword == ''" name="search" />
            <q-icon
              v-if="filterKeyword !== ''"
              name="clear"
              class="cursor-pointer"
              @click="resetFilter"
            />
          </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"
          class="col-xs-12 col-sm-3 col-md-2"
        />
      </div>
      <div class="col-12">
        <d-table
          :columns="columns"
          :rows="rows"
          row-key="personal_id"
          flat
          bordered
          :paging="true"
          dense
          class="custom-header-table"
          :visible-columns="visibleColumns"
          :rows-per-page-options="[10, 25, 50, 100]"
          @update:pagination="updatePaginationMain"
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th auto-width></q-th>
              <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 auto-width>
                <q-btn
                  v-if="checkPermission($route)?.attrIsGet"
                  flat
                  dense
                  round
                  color="info"
                  icon="mdi-eye"
                  @click="
                    router.push(`/probation/detail/${props.row.personal_id}`)
                  "
                >
                  <q-tooltip>รายละเอียด</q-tooltip>
                </q-btn>

                <q-btn
                  v-if="checkPermission($route)?.attrIsCreate"
                  @click="onAdd(props.row.personal_id)"
                  flat
                  round
                  color="blue"
                  icon="mdi-account-supervisor"
                >
                  <q-tooltip
                    >แต่งตั้งคณะกรรมการประเมินผลการทดลองปฏิบัติหน้าที่ราชการ</q-tooltip
                  >
                </q-btn>
              </q-td>
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                <div v-if="col.name == 'no'">
                  {{
                    (pagination.page - 1) * pagination.rowsPerPage +
                    props.rowIndex +
                    1
                  }}
                </div>
                <div v-else-if="col.name == 'order_number'">
                  {{
                    props.row.order_number
                      ? props.row.order_number != "xx/2566"
                        ? props.row.order_number
                        : "-"
                      : "-"
                  }}
                </div>
                <div v-else-if="col.name == 'probation_status'">
                  {{
                    props.row.probation_status
                      ? statusProbationMain(props.row.probation_status)
                      : "-"
                  }}
                </div>

                <div v-else class="table_ellipsis">
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
          <template v-slot:pagination="scope">
            ทั้งหมด {{ total }} รายการ
            <q-pagination
              v-model="pagination.page"
              active-color="primary"
              color="dark"
              :max="Number(totalList)"
              size="sm"
              boundary-links
              direction-links
              :max-pages="5"
              @update:model-value="getpersonalList"
            ></q-pagination>
          </template>
        </d-table>
      </div>
    </div>
  </q-card>

  <q-dialog v-model="modal" persistent>
    <q-card style="width: 900px; max-width: 80vw">
      <q-form ref="myForm">
        <DialogHeader
          tittle="เพิ่มผู้ทดลองปฏิบัติหน้าที่ราชการ "
          :close="clickClose"
        />
        <q-separator />
        <q-card-section class="q-pa-md q-col-gutter-sm">
          <q-input
            class="col-12"
            standout
            dense
            v-model="formProbation.keyword"
            ref="filterRef2"
            outlined
            debounce="300"
            placeholder="ค้นหา"
            @keydown.enter.prevent="filterKeyword2Fn(formProbation.page)"
          >
            <template v-slot:append>
              <q-icon v-if="filterKeyword2 == ''" name="search" />
              <q-icon
                v-if="filterKeyword2 !== ''"
                name="clear"
                class="cursor-pointer"
                @click="resetFilter2"
              />
            </template>
          </q-input>
          <div class="col-12">
            <d-table
              ref="table2"
              :columns="columns2"
              :rows="rows2"
              row-key="Order"
              flat
              bordered
              :paging="true"
              dense
              class="custom-header-table"
              v-bind="attrs"
              :pagination-label="paginationLabel2"
              v-model:pagination="pagination2"
              @update:pagination="updatePagination"
              :rows-per-page-options="[10, 25, 50, 100]"
            >
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th auto-width />
                  <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" class="cursor-pointer">
                  <q-td auto-width>
                    <q-btn
                      dense
                      class="q-px-md"
                      outline
                      color="primary"
                      label="เพิ่ม"
                      @click="clickAdd(props.row)"
                    >
                    </q-btn>
                  </q-td>
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    <div v-if="col.name == 'no'">
                      {{
                        (formProbation.page - 1) * formProbation.pageSize +
                        props.rowIndex +
                        1
                      }}
                    </div>

                    <div v-else-if="col.name == 'fullname'">
                      {{
                        (props.row.prefix ? props.row.prefix : "") +
                        props.row.firstName +
                        "  " +
                        props.row.lastName
                      }}
                    </div>
                    <div v-else-if="col.name == 'status'" class="text-center">
                      <q-icon
                        v-if="props.row.isProbation === true"
                        name="mdi-check"
                        color="positive"
                        size="sm"
                      />
                    </div>
                    <div
                      v-else-if="col.name == 'organizationOrganization'"
                      class="table_ellipsis"
                    >
                      <div
                        v-if="
                          props.row.orgChild4Name === null &&
                          props.row.orgChild3Name === null &&
                          props.row.orgChild2Name === null &&
                          props.row.orgChild1Name === null &&
                          props.row.orgRootName === null
                        "
                      >
                        -
                      </div>
                      {{
                        `${
                          props.row.orgChild4Name
                            ? props.row.orgChild4Name + "/"
                            : ""
                        }${
                          props.row.orgChild3Name
                            ? props.row.orgChild3Name + "/"
                            : ""
                        }${
                          props.row.orgChild2Name
                            ? props.row.orgChild2Name + "-"
                            : ""
                        }${
                          props.row.orgChild1Name
                            ? props.row.orgChild1Name + "/"
                            : ""
                        }${props.row.orgRootName ? props.row.orgRootName : ""}`
                      }}
                    </div>
                    <div v-else-if="col.name == 'refCommandNo'">
                      {{
                        props.row.refCommandNo
                          ? props.row.refCommandNo != "xx/2566"
                            ? props.row.refCommandNo
                            : "-"
                          : "-"
                      }}
                    </div>
                    <div v-else>
                      {{ col.value ? col.value : "-" }}
                    </div>
                  </q-td>
                </q-tr>
              </template>
              <template v-slot:pagination="scope">
                <q-pagination
                  v-model="formProbation.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-section>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="modalAdd" persistent>
    <q-card style="width: 900px; max-width: 80vw">
      <q-form greedy @submit.prevent @validation-success="onSubmitAdd">
        <DialogHeader
          tittle="เพิ่มการแต่งตั้งคณะกรรมการประเมินผลการทดลองปฏิบัติหน้าที่ราชการ"
          :close="closeAdd"
        />
        <q-separator />
        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <q-input
                dense
                outlined
                label="หัวข้อ"
                v-model="topic"
                class="inputgreen"
              ></q-input>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <DialogOrder v-model:modal="modalCommand" />
</template>
