<script setup lang="ts">
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import type { QTableProps } from "quasar";
import config from "@/app.config";

import http from "@/plugins/http";
import { reactive, ref, onMounted, watch } from "vue";
import DialogHeader from "@/components/DialogHeader.vue";
import type {
  optionData,
  tableType,
} from "@/modules/05_placement/interface/index/Main";
import { useRouter, useRoute } from "vue-router";

const total = ref<number>(0);
const totalList = ref<number>(1);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

const props = defineProps({
  getData: Function,
});
const route = useRoute();
const router = useRouter();
const id = ref<string>(route.params.id ? route.params.id.toString() : "");
const searchRules = ref<boolean>(false);
const selected = ref<any[]>([]);
const searchRef = ref<any>(null);
const rows = ref<tableType[]>([]);
const type = ref<string>("citizenId");
const search = ref<string>("");
const typeOps = ref<optionData[]>([
  { id: "citizenId", name: "เลขประจำตัวประชาชน" },
  { id: "firstname", name: "ชื่อ" },
  { id: "lastname", name: "นามสกุล" },
]);
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  showLoader,
  hideLoader,
  messageError,
  date2Thai,
  dialogConfirm,
  dialogMessageNotify,
  findOrgName,
} = mixin;

const modalDialog = defineModel<boolean>("modal", { required: true });

function onCloseDialog() {
  modalDialog.value = false;
  rows.value = [];
  selected.value = [];
  search.value = "";
  type.value = "idcard";
}

/** หัวข้อที่เเสดงในตารางผู้ถูกร้องเรียน */
const visibleColumnsRespondent = ref<string[]>([
  "no",
  "name",
  "position",
  "positionType",
  "organization",
]);

const columnsRespondent = 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",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionType",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: true,
    field: "positionType",
    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",
  },
]);

async function searchInput(check: boolean) {
  if (check) {
    searchRules.value = check;
    searchRef.value.validate();
    if (!searchRef.value.hasError) {
      await getSearch();
    }
    setTimeout(() => {
      searchRules.value = false;
    }, 100);
  }
}

async function getSearch() {
  showLoader();
  const body = {
    fieldName: type.value,
    keyword: search.value,
  };
  await http
    .post(
      config.API.orgSearchPersonal() +
        `?page=${pagination.value.page}&pageSize=${pagination.value.rowsPerPage}&searchKeyword=${search.value}`,
      body
    )
    .then((res) => {
      const data = res.data.result;
      totalList.value = Math.ceil(data.total / pagination.value.rowsPerPage);
      total.value = data.total;
      rows.value = data.data;
    })
    .catch((err) => {})
    .finally(() => {
      hideLoader();
    });
}

/** update เมื่อเปลี่ยน option */
function updateSelect() {
  search.value = "";
}

function onSubmit() {
  if (selected.value.length == 0) {
    dialogMessageNotify($q, "กรุณาเลือกรายชื่อผู้ที่ย้ายสับเปลี่ยนตำแหน่ง");
  } else {
    const dataProfile = selected.value;
    dialogConfirm($q, () => {
      showLoader();
      http
        .post(config.API.changePositionByIdProfile + `/${id.value}`, {
          changePositionId: id.value,
          profiles: dataProfile.map((i: any) => ({
            profileId: i.id,
            prefix: i.prefix,
            firstName: i.firstName,
            lastName: i.lastName,
            citizenId: i.citizenId ? i.citizenId : null,
            birthDate: i.birthDate ? i.birthDate : null,
            positionOld: i.position ? i.position : null,
            positionTypeOld: i.positionType ? i.positionType : null,
            positionLevelOld: i.positionLevel ? i.positionLevel : null,
            positionNumberOld: i.posNo ? i.posNo : null,
            organizationOld: i.organization ? i.organization : null,
            amountOld: i.salary ? i.salary : null,
            educationOld: i.educationDegree ? i.educationDegree : null,
            rootOld: i.root ? i.root : null,
            rootOldId: i.rootId ? i.rootId : null,
            rootShortNameOld: i.rootShortName ? i.rootShortName : null,
            child1Old: i.child1 ? i.child1 : null,
            child1OldId: i.child1Id ? i.child1Id : null,
            child1ShortNameOld: i.child1ShortName ? i.child1ShortName : null,
            child2Old: i.child2 ? i.child2 : null,
            child2OldId: i.child2Id ? i.child2Id : null,
            child2ShortNameOld: i.child2ShortName ? i.child2ShortName : null,
            child3Old: i.child3 ? i.child3 : null,
            child3OldId: i.child3Id ? i.child3Id : null,
            child3ShortNameOld: i.child3ShortName ? i.child3ShortName : null,
            child4Old: i.child4 ? i.child4 : null,
            child4OldId: i.child4Id ? i.child4Id : null,
            child4ShortNameOld: i.child4ShortName ? i.child4ShortName : null,
            posMasterNoOld: i.posMasterNo ? i.posMasterNo : null,
            posTypeOldId: i.posTypeId ? i.posTypeId : null,
            posTypeNameOld: i.posTypeName ? i.posTypeName : null,
            posLevelOldId: i.posLevelId ? i.posLevelId : null,
            posLevelNameOld: i.posLevelName ? i.posLevelName : null,
          })),
        })
        .then((res) => {
          onCloseDialog();
          props.getData?.();
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    });
  }
}

function updatePagination(newPagination: any) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}

watch(
  () => pagination.value.rowsPerPage,
  async () => {
    await getSearch();
  }
);
</script>
<template>
  <q-dialog v-model="modalDialog" persistent>
    <q-card :style="$q.screen.gt.xs ? 'min-width: 90vw' : 'width: 100vw'">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          :tittle="'เพิ่มรายชื่อผู้ที่ย้ายสับเปลี่ยนตำแหน่ง'"
          :close="onCloseDialog"
        />
        <q-separator />
        <q-card-section class="q-pa-none scroll" style="max-height: 80vh">
          <div class="row">
            <div class="col-12">
              <div class="row q-pa-md q-col-gutter-sm">
                <div class="col-12 col-sm-6 col-md-3">
                  <q-select
                    label="ค้นหาจาก"
                    v-model="type"
                    :options="typeOps"
                    emit-value
                    dense
                    @update:model-value="updateSelect"
                    map-options
                    outlined
                    option-label="name"
                    option-value="id"
                  />
                </div>

                <div class="col-12 col-sm-6 col-md-9">
                  <q-input
                    ref="searchRef"
                    v-model="search"
                    outlined
                    clearable
                    hide-bottom-space
                    dense
                    label="คำค้น"
                    :rules="[
                      (val) => !!val || !searchRules || `กรุณากรอกคำค้น`,
                    ]"
                  >
                    <template v-slot:after>
                      <q-btn
                        color="primary"
                        icon="search"
                        label="ค้นหา"
                        class="full-width q-py-sm q-px-md"
                        @click="searchInput(true)"
                      >
                      </q-btn>
                    </template>
                  </q-input>
                </div>
                <div class="col-12 q-pt-sm">
                  <d-table
                    ref="table"
                    :columns="columnsRespondent"
                    :rows="rows"
                    row-key="id"
                    flat
                    bordered
                    selection="multiple"
                    v-model:selected="selected"
                    :paging="true"
                    dense
                    class="custom-header-table"
                    :visible-columns="visibleColumnsRespondent"
                    :rows-per-page-options="[1, 25, 50, 100]"
                    @update:pagination="updatePagination"
                  >
                    <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="getSearch"
                      ></q-pagination>
                    </template>

                    <template v-slot:header="props">
                      <q-tr :props="props">
                        <q-th auto-width>
                          <q-checkbox
                            keep-color
                            color="primary"
                            dense
                            v-model="props.selected"
                          />
                        </q-th>
                        <q-th
                          v-for="col in props.cols"
                          :key="col.name"
                          :props="props"
                          style="color: #000000; font-weight: 500"
                        >
                          <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>
                          <q-checkbox
                            keep-color
                            color="primary"
                            dense
                            v-model="props.selected"
                          />
                        </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 == 'name'">
                            {{
                              `${props.row.prefix ? props.row.prefix : ""}${
                                props.row.firstName ? props.row.firstName : ""
                              } ${props.row.lastName ? props.row.lastName : ""}`
                            }}
                          </div>
                          <div v-else-if="col.name == 'positionType'">
                            {{
                              props.row.positionTypeName
                                ? props.row.positionTypeName
                                : ""
                            }}{{
                              props.row.positionLevelName
                                ? ` (${props.row.positionLevelName})`
                                : ""
                            }}
                          </div>
                          <div
                            v-else-if="col.name == 'organization'"
                            class="table_ellipsis"
                          >
                            {{ findOrgName(props.row) }}
                          </div>
                          <div v-else>
                            {{ col.value }}
                          </div>
                        </q-td>
                      </q-tr>
                    </template>
                  </d-table>
                </div>
              </div>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
