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

import { useCounterMixin } from "@/stores/mixin";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/Main";
import { useRoute } from "vue-router";

const mainStore = useDisciplineMainStore();

const modal = defineModel<boolean>("modal", { required: true });
const total = ref<number>(0);
const totalList = ref<number>(1);

const $q = useQuasar();
const route = useRoute();
const mixin = useCounterMixin();
const { dialogMessageNotify, showLoader, hideLoader, messageError } = mixin;

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

interface typeOp {
  id: string;
  name: string;
}

interface tableType {
  personId: string;
  idcard: string;
  prefix: string;
  firstName: string;
  lastName: string;
  position: string;
  positionLevel: string;
  organization: string;
  salary: string;
  name: string;
}

const rows = ref<tableType[]>([]);
const rowsMain = ref<tableType[]>([]);
const type = ref<string>("citizenId");
const search = ref<string>("");
const selected = ref<any>([]);
const isSelect = ref<boolean>(false);

const employeeClass = ref<string>("officer");
const employeeClassOption = ref<typeOp[]>([
  { id: "officer", name: "ข้าราชการ กทม. สามัญ" },
  { id: "employee", name: "ลูกจ้างประจำ กทม." },
]);

const typeOps = ref<typeOp[]>([
  { id: "citizenId", name: "เลขประจำตัวประชาชน" },
  { id: "fullName", name: "ชื่อ-นามสกุล" },
]);

/** รับค่ามาจาก หน้าหลัก */
const props = defineProps({
  btnTitle: {
    type: String,
    default: "เพิ่ม",
  },
  title: {
    type: String,
    default: "",
  },
  desc: {
    type: String,
    default: "",
  },
  selectedData: {
    type: Array,
    default: [],
  },
  close: {
    type: Function,
    default: () => console.log("not function"),
    required: true,
  },
  save: {
    type: Function,
    default: () => console.log("not function"),
    required: true,
  },
  selecetSwitch: {
    type: String,
    default: "multiple",
  },
  system: {
    type: String || undefined,
    default: "",
  },
});

/**ส่งค่ากลับหน้าหลัก */
const emit = defineEmits(["returnData"]);

/** ปิด dialog */
async function close() {
  modal.value = false;
  rows.value = [];
  rowsMain.value = [];
  selected.value = [];
  employeeClass.value = "officer";
  search.value = "";
}

/** เปิด dialog ยืนยัน */
function savePost() {
  if (selected.value.length != 0) {
    saveData();
  } else {
    dialogMessageNotify($q, "กรุณาเลือกอย่างน้อย 1 รายการ");
  }
}

/** save data หลังจาก ยืนยัน */
function saveData() {
  props.save(selected.value, employeeClass.value);
  close();
}

const searchRef = ref<any>(null);
/** input ค้นหา */
async function searchInput() {
  searchRef.value.validate();
  if (!searchRef.value.hasError) {
    pagination.value.page = 1;
    await getSearch();
  }
}

async function getSearch() {
  showLoader();
  // API ค้นหารายบุคคล
  const employeeSuffix = employeeClass.value === "officer" ? "" : "-employee";
  const apiMethod =
    props.system === "SYS_DISCIPLINE_APPEAL"
      ? config.API.orgSearchPersonalByTypeNoKeycloak
      : config.API.orgSearchPersonalByType;

  const apiPath = apiMethod(employeeSuffix);

  // สร้าง query params
  const queryParams = `?page=${pagination.value.page}&pageSize=${pagination.value.rowsPerPage}`;

  // สร้าง body
  const body = {
    fieldName: type.value,
    keyword: search.value ? search.value.trim() : "",
    system: props.system ?? undefined,
  };

  await http
    .post(apiPath + queryParams, body)
    .then((res) => {
      const data = res.data.result.data;
      totalList.value = Math.ceil(
        res.data.result.total / pagination.value.rowsPerPage
      );
      total.value = res.data.result.total;
      const list = data.map((e: any) => ({
        personId: e.id,
        idcard: e.citizenId,
        prefix: e.prefix,
        firstName: e.firstName,
        lastName: e.lastName,
        name: e.name,
        posNo: e.posNo ?? "-",
        position: e.position ?? "-",
        positionLevel: e.positionLevelName ?? "-",
        salary: e.salary ?? "",
        organization: e.organization ?? "-",
        phone: e.phone ?? "-",
        email: e.email ?? "-",
        root: e.root,
        rootId: e.rootId,
        rootShortName: e.rootShortName,
        child1: e.child1,
        child1Id: e.child1Id,
        child1ShortName: e.child1ShortName,
        child2: e.child2,
        child2Id: e.child2Id,
        child2ShortName: e.child2ShortName,
        child3: e.child3,
        child3Id: e.child3Id,
        child3ShortName: e.child3ShortName,
        child4: e.child4,
        child4Id: e.child4Id,
        child4ShortName: e.child4ShortName,
        posMasterNo: e.posMasterNo,
        posTypeId: e.posTypeId,
        posTypeName: e.posTypeName,
        posLevelId: e.posLevelId,
        posLevelName: e.posLevelName,

        rootDnaId: e.rootDnaId,
        child1DnaId: e.child1DnaId,
        child2DnaId: e.child2DnaId,
        child3DnaId: e.child3DnaId,
        child4DnaId: e.child4DnaId,
      }));
      rowsMain.value = list;
      rows.value = list;

      // if (route.name == "disciplineInvestigatefactsEdit") {
      //   const idIsSend = mainStore.rowsAdd
      //     .filter(
      //       (item: any) => item.isSend === "DONE" || item.isAncestorDNA === true
      //     )
      //     .map((item: any) => item.personId);
      //   rows.value = list.filter(
      //     (item: any) => !idIsSend.includes(item.personId)
      //   );
      // } else {
      //   const idIsSend = mainStore.rowsAdd
      //     .filter((item: any) => item.isAncestorDNA === true)
      //     .map((item: any) => item.personId);
      //   rows.value = list.filter(
      //     (item: any) => !idIsSend.includes(item.personId)
      //   );
      // }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}
/** update เมื่อเปลี่ยน option */
function updateSelect() {
  search.value = "";
}
// watch(
//   () => props.selectedData,
//   () => {
//     if (props.selectedData) {
//       selected.value = props.selectedData;
//     }
//   }
// );

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

function checkList(propsRow: tableType) {
  // const filterCondition =
  //   route.name === "disciplineInvestigatefactsEdit"
  //     ? (item: any) => item.isSend === "DONE" || item.isAncestorDNA === true
  //     : (item: any) => item.isAncestorDNA === true;

  const idIsSend = mainStore.rowsAdd
    // .filter(filterCondition)
    .map((item: any) => item.personId);

  return !idIsSend.includes(propsRow.personId);
}

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

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 60vw">
      <q-toolbar>
        <q-toolbar-title class="text-subtitle2 text-bold">{{
          props.title
        }}</q-toolbar-title>
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="close"
          style="color: #ff8080; background-color: #ffdede"
        />
      </q-toolbar>
      <q-separator />
      <q-card-section class="q-pa-md scroll" style="max-height: 80vh">
        <div class="row q-col-gutter-sm items-start q-mb-sm">
          <div class="col-12 col-sm-5 col-md-3">
            <q-select
              label="ประเภทตำแหน่ง"
              v-model="employeeClass"
              :options="employeeClassOption"
              emit-value
              dense
              map-options
              outlined
              option-label="name"
              option-value="id"
              @update:model-value="(rows = []), (selected = [])"
            />
          </div>
        </div>
        <div class="row q-col-gutter-sm items-start q-mb-sm">
          <div class="col-12 col-sm-5 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-7 col-md-9">
            <q-input
              ref="searchRef"
              v-model="search"
              outlined
              dense
              label="คำค้น"
            >
              <template v-slot:after>
                <q-btn
                  color="primary"
                  icon="search"
                  label="ค้นหา"
                  outline
                  class="full-width q-py-sm q-px-md"
                  @click="searchInput()"
                >
                </q-btn>
              </template>
            </q-input>
          </div>
        </div>

        <div class="full-width">
          <d-table
            ref="table"
            :columns="mainStore.columnsRespondent?.filter((item:any)=>item.name !== 'profileType' && item.name !== 'isSend' && item.name !== 'remarkReject' && item.name !== 'disciplineRejectDoc')"
            :rows="rows"
            row-key="personId"
            flat
            bordered
            :paging="true"
            dense
            class="custom-header-table"
            :visible-columns="mainStore.visibleColumnsRespondent"
            :selection="props.selecetSwitch"
            v-model:selected="selected"
            :rows-per-page-options="[10, 25, 50, 100]"
            @update:pagination="updatePagination"
          >
            <template v-slot:pagination="scope">
              ทั้งหมด {{ total?.toLocaleString() }} รายการ
              <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-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-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">
                <td class="text-center">
                  <q-checkbox
                    v-if="checkList(props.row)"
                    keep-color
                    color="primary"
                    dense
                    v-model="props.selected"
                  />
                  <q-checkbox
                    v-else
                    disable
                    keep-color
                    color="primary"
                    dense
                    v-model="isSelect"
                  />
                </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-if="col.name === 'fullName'">
                    {{ props.prefix }}
                  </div>
                  <div v-else-if="col.name === 'salary'">
                    {{
                      props.row.salary ? props.row.salary.toLocaleString() : "0"
                    }}
                  </div>

                  <div v-else>
                    {{ col.value }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right" class="q-mx-sm q-my-xs">
        <q-btn
          color="public"
          id="onSubmit"
          @click="savePost"
          :disable="rows.length === 0"
        >
          <!-- <q-icon left name="add" /> -->
          <div>{{ props.btnTitle }}</div>
          <!-- icon="mdi-content-save-outline" -->
          <q-tooltip>{{ props.btnTitle }}</q-tooltip>
        </q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
