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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { usePositionEmp } from "@/modules/16_positionEmployee/store/organizational";

/**
 * importType
 */
import type { QTableProps } from "quasar";
import type {
  Position,
  SeaechResult,
  FormPositionFilter,
} from "@/modules/16_positionEmployee/interface/index/organizational";
import type {
  DataOption,
  NewPagination,
} from "@/modules/16_positionEmployee/interface/index/Main";
import type {
  OptionType,
  OptionLevel,
  SelectPerson,
  TypePos,
} from "@/modules/16_positionEmployee/interface/response/organizational";

/**
 * importCompoonents
 */
import DialogHeader from "@/components/DialogHeader.vue";

/**
 * use
 */
const $q = useQuasar();
const store = usePositionEmp();
const {
  dialogConfirm,
  showLoader,
  success,
  hideLoader,
  messageError,
  dialogMessageNotify,
} = useCounterMixin();

/**
 * props
 */
const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  fetchActive: {
    type: Function,
    require: true,
  },
  fetchDataTable: {
    type: Function,
    required: true,
  },
  getSummary: {
    type: Function,
    required: true,
  },
  dataDetailPos: { type: Object, require: true },
});

const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว
const typeOpsMain = ref<DataOption[]>([]); //ข้อมูลกลุ่มงาน
const levelOpsMain = ref<DataOption[]>([]); //ข้อมูลระดับกลุ่มงาน
const typeOps = ref<DataOption[]>([]); //รายการกลุ่มงาน
const levelOps = ref<DataOption[]>([]); //รายการระดับกลุ่มงาน
const dataLevel = ref<TypePos[]>([]);
const selected = ref<Position[]>([]); //ตำแหน่งที่เลือก
const isSit = ref<boolean>(false);

const formData = reactive<FormPositionFilter>({
  positionNo: "", //*ตำแหน่งเลขที่
  positionType: "", //*ตำแหน่งเลขที่
  positionLevel: "", //*ตำแหน่งเลขที่
  personal: "", //*ตำแหน่งเลขที่
  position: "", //*ตำแหน่งเลขที่
  status: "",
});

/**
 * ข้อมูล Table
 */
const row = ref<Position[]>([]);
const rowResult = ref<SeaechResult[]>([]);
const visibleColumnsResult = ref<String[]>([
  "no",
  "citizenId",
  "name",
  "posTypeName",
  "posLevelName",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionName",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "positionName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "posTypeName",
    align: "left",
    label: "กลุ่มงาน",
    sortable: true,
    field: "posTypeName",
    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",
  },
]);
const columnsResult = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขบัตรประชาชน",
    sortable: true,
    field: "citizenId",
    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: "positionName",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "positionName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posTypeName",
    align: "left",
    label: "กลุ่มงาน",
    sortable: true,
    field: "posTypeName",
    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",
  },
]);

/**
 * function closePopup
 */
function close() {
  modal.value = false;
  clearForm();
}

/**
 *  function เรียกข้อมูลประเภทตำแหน่ง
 */
async function fetchType() {
  showLoader();
  await http
    .get(config.API.orgEmployeeType)
    .then((res) => {
      dataLevel.value = res.data.result;
      typeOpsMain.value = res.data.result.map((e: OptionType) => ({
        id: e.id,
        name: e.posTypeName,
      }));
      typeOps.value = typeOpsMain.value;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ส่งค่า css ออกไปตามเงื่อนไข
 * @param val true/false
 */
function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer inputgreen ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

/**
 * function เรียกข้แมูลระดับตำแหน่ง
 */
function updateSelectType(val: string) {
  const listLevel: any = dataLevel.value.find((e: TypePos) => e.id === val);
  levelOpsMain.value = listLevel?.posLevels.map((e: OptionLevel) => ({
    id: e.id,
    name: e.posLevelName,
  }));
  levelOps.value = levelOpsMain.value;
  formData.positionLevel = "";
}

/**
 * ฟังก์ชั่นตรวจสอบความถูกต้องของข้อมูลในฟอร์ม
 */
function validateForm() {
  if (selected.value.length === 0) {
    dialogMessageNotify($q, "กรุณาเลือกรายการตำแหน่ง");
  } else if (selectedProfile.value.length === 0) {
    dialogMessageNotify($q, "กรุณาเลือกคนครอง");
  } else {
    onSubmit();
  }
}

/**
 * function ยืนยันการบันทึกข้อมูล
 */
function onSubmit() {
  dialogConfirm(
    $q,
    () => {
      const body = {
        posMaster: props.dataDetailPos?.id, //*id อัตรากำลัง
        position: selected.value[0]?.id, //*id ตำแหน่ง
        profileId: selectedProfile.value[0]?.id, //*id profile
        isSit: isSit.value, //*นั่งทับที่ไหม
      };
      showLoader();
      http
        .post(config.API.orgProfileEmp, body)
        .then(async () => {
          await props.fetchDataTable?.(store.treeId, store.level, false);
          await props.getSummary();
          await success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(async () => {
          modal.value = await false;
          close();
          hideLoader();
        });
    },
    "ยืนยันการเลือกคนครอง",
    "ต้องการยืนยันการเลือกคนครองตำแหน่งนี้ใช่หรือไม่?"
  );
}

const page = ref<number>(1);
const pageSize = ref<number>(10);
const totalPage = ref<number>(0);
const selectedProfile = ref<SeaechResult[]>([]);

/**
 * functiuon ค้นหาคนครอง
 */
function searchData() {
  showLoader();
  const reqBody = {
    posTypeId: formData.positionType, // id ประเภทตำแหน่ง
    posLevelId: formData.positionLevel, // id ระดับตำแหน่ง
    position: formData.position, // ตำแหน่ง
    page: page.value, //*หน้า
    pageSize: pageSize.value, //*จำนวนแถวต่อหน้า
    keyword: formData.personal, //นามสกุล ชื่อ สกุล เลขบัตร
  };
  http
    .post(config.API.orgSearchProfileEmp, reqBody)
    .then((res) => {
      totalPage.value = Math.ceil(res.data.result.total / pageSize.value);
      const list = res.data.result.data.map((e: SelectPerson) => ({
        id: e.id,
        citizenId: e.citizenId,
        name: `${e.prefix + e.firstName + " " + e.lastName}`,
        posTypeName: e.posType ?? "-",
        positionName: e.position ?? "-",
        posLevelName: e.posLevel ?? "-",
      }));
      rowResult.value = list;
    })

    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function getSearch() {
  page.value = 1;
  searchData();
}

/**
 * function update PageSize
 */
function updatePagination(newPagination: NewPagination) {
  pageSize.value = newPagination.rowsPerPage;
  page.value = 1;
}

/**
 * function เคลียร์Form
 */
function clearForm() {
  formData.positionType = "";
  formData.positionLevel = "";
  formData.personal = "";
  formData.position = "";
  row.value = [];
  rowResult.value = [];
  selected.value = [];
  selectedProfile.value = [];
  isSit.value = false;
}

/**
 * function เคลียร์ตำแหน่ง
 */
function clearPosition() {
  formData.positionType = "";
  formData.positionLevel = "";
}

/**
 * callback function ทำงานเมื่อเปิด popup
 */
watch(
  () => modal.value,
  async () => {
    if (modal.value == true) {
      await fetchType();

      if (props.dataDetailPos) {
        formData.positionNo = props.dataDetailPos.posMasterNo;
        formData.status =
          store.typeOrganizational === "current"
            ? "ปกติ"
            : store.typeOrganizational === "draft"
            ? "แบบร่าง"
            : "ยุบเลิก";
        row.value = props.dataDetailPos.positions.map((e: Position) => ({
          ...e,
          positionName: e.positionName ? e.positionName : "-",
          positionField: e.positionField ? e.positionField : "-",
          posTypeName: e.posTypeName ? e.posTypeName : "-",
          posLevelName: e.posLevelName ? e.posLevelName : "-",
          posExecutiveName: e.posExecutiveName ? e.posExecutiveName : "-",
          positionExecutiveField: e.positionExecutiveField
            ? e.positionExecutiveField
            : "-",
          positionArea: e.positionArea ? e.positionArea : "-",
        }));
        if (row.value.length === 1) {
          selected.value.push(row.value[0]);
        }
      }
    }
  }
);

watch(
  () => pageSize.value,
  async () => {
    getSearch();
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 80vw">
      <form @submit.prevent="validateForm">
        <DialogHeader :tittle="`เลือกคนครอง`" :close="close" />
        <q-separator />

        <q-card-section class="fixed-height">
          <div class="q-px-md">
            <div class="row q-col-gutter-sm q-mb-xs">
              <div class="text-bold text-body1">
                <p>ตำแหน่งเลขที่</p>
              </div>
              <div class="text-grey-8 q-ml-sm text-body1">
                <p>{{ formData.positionNo }}</p>
              </div>
            </div>

            <q-card
              bordered
              class="row col-12"
              style="border: 1px solid #d6dee1"
            >
              <div
                class="col-xs-12 col-sm-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
              >
                รายการตำแหน่ง
              </div>
              <div class="col-12"><q-separator /></div>

              <div class="q-pa-sm col-12">
                <d-table
                  flat
                  :columns="columns"
                  :rows="row"
                  row-key="id"
                  dense
                  hide-pagination
                  class="custom-header-table"
                  selection="single"
                  v-model:selected="selected"
                >
                  <template v-slot:header-selection="scope">
                    <q-checkbox
                      keep-color
                      color="primary"
                      dense
                      v-model="scope.checkBox"
                    />
                  </template>
                  <template v-slot:header="props">
                    <q-tr :props="props">
                      <q-th class="text-center"> </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" class="cursor-pointer">
                      <q-td class="text-center">
                        <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'">
                          {{ props.rowIndex + 1 }}
                        </div>

                        <div v-else>
                          {{ col.value }}
                        </div>
                      </q-td>
                    </q-tr>
                  </template>
                </d-table>
              </div>
            </q-card>

            <q-card
              bordered
              class="row col-12 q-mt-sm"
              style="border: 1px solid #d6dee1"
            >
              <div
                class="col-xs-12 col-sm-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
              >
                ค้นหาคนครอง
              </div>
              <div class="col-12"><q-separator /></div>
              <div class="col-12">
                <div class="row q-col-gutter-sm q-pa-sm">
                  <div class="col-2">
                    <q-input
                      ref="positionExecutiveFieldRef"
                      v-model="formData.personal"
                      :class="inputEdit(isReadonly)"
                      dense
                      outlined
                      for="#search"
                      label="ค้นหาจากชื่อ-นามสกุล หรือเลขประจำตัวประชาชน"
                      lazy-rules
                      hide-bottom-space
                    />
                  </div>
                  <div class="col-2">
                    <q-input
                      ref="positionRef"
                      v-model="formData.position"
                      :class="inputEdit(isReadonly)"
                      dense
                      outlined
                      for="#position"
                      label="ตำแหน่ง"
                      lazy-rules
                      hide-bottom-space
                    />
                  </div>
                  <div class="col-2">
                    <q-select
                      ref="positionTypeRef"
                      :class="inputEdit(isReadonly)"
                      label="กลุ่มงาน"
                      v-model="formData.positionType"
                      :options="typeOps"
                      emit-value
                      dense
                      @update:model-value="updateSelectType"
                      map-options
                      outlined
                      option-label="name"
                      option-value="id"
                      lazy-rules
                      hide-bottom-space
                      ><template v-if="formData.positionType" v-slot:append>
                        <q-icon
                          name="cancel"
                          @click.stop.prevent="clearPosition()"
                          class="cursor-pointer"
                        /> </template
                    ></q-select>
                  </div>
                  <div class="col-2">
                    <q-select
                      ref="positionLevelRef"
                      :class="inputEdit(isReadonly)"
                      label="ระดับชั้นงาน"
                      v-model="formData.positionLevel"
                      :disable="formData.positionType == ''"
                      :options="levelOps"
                      emit-value
                      dense
                      map-options
                      outlined
                      option-label="name"
                      option-value="id"
                      lazy-rules
                      hide-bottom-space
                    >
                      <template v-if="formData.positionLevel" v-slot:append>
                        <q-icon
                          name="cancel"
                          @click.stop.prevent="formData.positionLevel = ''"
                          class="cursor-pointer"
                        /> </template
                    ></q-select>
                  </div>
                  <div class="col-2">
                    <q-btn
                      label="ค้นหา"
                      color="teal-5"
                      class="full-height"
                      icon="search"
                      @click="getSearch()"
                    />
                  </div>

                  <q-select
                    for="#select"
                    v-model="visibleColumnsResult"
                    multiple
                    outlined
                    dense
                    options-dense
                    :display-value="$q.lang.table.columns"
                    emit-value
                    map-options
                    :options="columnsResult"
                    option-value="name"
                    
                    style="min-width: 140px"
                    class="col-xs-12 col-sm-3 col-md-2"
                  />
                  <div class="col-12">
                    <d-table
                      ref="table"
                      flat
                      :columns="columnsResult"
                      :rows="rowResult"
                      row-key="id"
                      dense
                      class="custom-header-table"
                      :paging="true"
                      :rows-per-page-options="[10, 25, 50, 100]"
                      @update:pagination="updatePagination"
                      selection="single"
                      v-model:selected="selectedProfile"
                      :visible-columns="visibleColumnsResult"
                    >
                      <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>
                            <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'">
                              {{
                                (page - 1) * Number(pageSize) +
                                props.rowIndex +
                                1
                              }}
                            </div>

                            <div v-else>
                              {{ col.value }}
                            </div>
                          </q-td>
                        </q-tr>
                      </template>
                      <template v-slot:pagination="scope">
                        <q-pagination
                          v-model="page"
                          active-color="primary"
                          color="dark"
                          :max="totalPage"
                          :max-pages="5"
                          size="sm"
                          boundary-links
                          direction-links
                          @update:model-value="searchData"
                        ></q-pagination>
                      </template>
                    </d-table>
                  </div>
                </div>
              </div>
            </q-card>

            <div class="row col-12 q-pa-sm">
              <q-checkbox
                keep-color
                color="primary"
                dense
                v-model="isSit"
                label="นั่งทับตำแหน่ง"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn type="submit" :label="`ยืนยัน`" color="public" />
        </q-card-actions>
      </form>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.fixed-height {
  overflow-y: auto;
  height: 80vh;
}
</style>
