<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import DialogHeader from "@/modules/04_registry/components/DialogHeader.vue";
import type { QInput, QForm } from "quasar";
import type { treeTab } from "@/modules/05_placement/interface/index/Main";
import http from "@/plugins/http";
import config from "@/app.config";
import type { QTableProps } from "quasar";

const props = defineProps({
  next: {
    type: Function,
    default: () => console.log("not function"),
  },
  previous: {
    type: Function,
    default: () => console.log("not function"),
  },
});

const next = () => props.next();
const previous = () => props.previous();

const $q = useQuasar();
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const { dialogMessage, messageError, showLoader, hideLoader } = mixin;

const myForm = ref<QForm>();
const filterRef = ref<QInput>();
const filter = ref<string>("");
const mutiselect = ref([]);
const modal = ref<boolean>(false);
const search = ref<string>("");
const expanded = ref<string[]>([]);
const selected = ref<string>("");
const nodesTree = ref<treeTab[]>([]);
const send = ref<String[]>([]);
const selectedModal = ref([]);
const test = ref([]);
const filterModal = ref<string>("");
const visibleColumnsModal = ref<String[]>(["no", "idcard", "name"]);
const columnsModal = ref<QTableProps["columns"]>([
  { name: "no", align: "left", label: "ลำดับ", field: "no", sortable: true },
  {
    name: "idcard",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    field: "idcard",
    sortable: true,
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-สกุล",
    field: "name",
    sortable: true,
  },
]);

const rowsModal = [
  {
    no: "0ac56905-1a74-4606-a120-233340adde95",
    name: "นางนัทธ์ เหล่าสกุล",
    idcard: "9158455632145",
    educate: "",
  },
  {
    no: "0de607a0-b094-4a6d-9e30-979343ab5e53",
    name: "นางขรรค์ จันทรสมบัติ",
    idcard: "8558455632126",
    educate: "",
  },
  {
    no: "93ca7366-2a35-4f94-a331-9c23c9ea78d3",
    name: "นางโอภาส จรัสวงศ์",
    idcard: "8158455635425",
    educate: "",
  },
  {
    no: "d3777c19-2bd0-42df-90ce-c3eeeee55ac6",
    name: "นางธิญา หงษ์ทอง",
    idcard: "4558455632145",
    educate: "",
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางธนวิทย์ พิกุลเทพ",
    idcard: "5542455632145",
    educate: "",
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางหนึ่ง สตาภิรมย์",
    idcard: "7448455632145",
    educate: "",
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางสัจพร คมคาย",
    idcard: "1236455632145",
    educate: "",
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางตุลยากร ปรีดาศิริกุล",
    idcard: "1523455632145",
    educate: "",
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางบัลลังค์ จิรวาณิชย์",
    idcard: "1258455632145",
    educate: "",
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางคมคาย เรืองรังสรรค์",
    idcard: "8548455632145",
    educate: "",
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางพรทิพา คมคาย",
    idcard: "6598455632145",
    educate: "",
  },
];

const paginationModal = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});
const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});
const optionSelect = ref<any>([
  { id: 1, name: "อีเมล" },
  { id: 2, name: "กล่องข้อความ" },
]);

const visibleColumns = ref<String[]>([
  "no",
  "idcard",
  "name",
  "position",
  "agency",
  "send",
]);
const columns = ref<QTableProps["columns"]>([
  { name: "no", align: "left", label: "ลำดับ", field: "no", sortable: true },
  {
    name: "idcard",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    field: "idcard",
    sortable: true,
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-สกุล",
    field: "name",
    sortable: true,
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    field: "position",
    sortable: true,
  },
  {
    name: "agency",
    align: "left",
    label: "หน่วยงาน",
    field: "agency",
    sortable: true,
  },
  {
    name: "send",
    align: "left",
    label: "ช่องทางการส่งสำเนา",
    field: "send",
    sortable: true,
  },
]);

const rows = ref([
  {
    no: "0ac56905-1a74-4606-a120-233340adde95",
    name: "นางนัทธ์ เหล่าสกุล",
    idcard: "9158455632145",
    send: "",
    position: "ผู้อำนวยการ",
    agency: "กลุ่มงานช่วยบริหาร",
    mutiselect: [],
  },
  {
    no: "0de607a0-b094-4a6d-9e30-979343ab5e53",
    name: "นางขรรค์ จันทรสมบัติ",
    idcard: "8558455632126",
    send: "",
    position: "นักจัดการทั่วไป",
    agency: "กลุ่มงานช่วยบริหาร",
    mutiselect: [],
  },
  {
    no: "93ca7366-2a35-4f94-a331-9c23c9ea78d3",
    name: "นางโอภาส จรัสวงศ์",
    idcard: "8158455635425",
    send: "",
    position: "นักจัดการทั่วไป",
    agency: "กลุ่มงานช่วยบริหาร",
    mutiselect: [],
  },
  {
    no: "d3777c19-2bd0-42df-90ce-c3eeeee55ac6",
    name: "นางธิญา หงษ์ทอง",
    idcard: "4558455632145",
    send: "",
    position: "นักจัดการทั่วไป",
    agency: "กลุ่มงานช่วยบริหาร",
    mutiselect: [],
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางธนวิทย์ พิกุลเทพ",
    idcard: "5542455632145",
    send: "",
    position: "นักจัดการทั่วไป",
    agency: "กลุ่มงานช่วยบริหาร",
    mutiselect: [],
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางหนึ่ง สตาภิรมย์",
    idcard: "7448455632145",
    send: "",
    position: "นิติกร",
    agency: "กลุ่มงานนิติกร",
    mutiselect: [],
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางสัจพร คมคาย",
    idcard: "1236455632145",
    send: "",
    position: "นิติกร",
    agency: "กลุ่มงานนิติกร",
    mutiselect: [],
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางตุลยากร ปรีดาศิริกุล",
    idcard: "1523455632145",
    send: "",
    position: "นิติกร",
    agency: "กลุ่มงานนิติกร",
    mutiselect: [],
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางบัลลังค์ จิรวาณิชย์",
    idcard: "1258455632145",
    send: "",
    position: "นิติกร",
    agency: "กลุ่มงานนิติกร",
    mutiselect: [],
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางคมคาย เรืองรังสรรค์",
    idcard: "8548455632145",
    send: "",
    position: "นิติกร",
    agency: "กลุ่มงานนิติกร",
    mutiselect: [],
  },
  {
    no: "1ccead6f-a851-4291-b3ab-a20757ecddbd",
    name: "นางพรทิพา คมคาย",
    idcard: "6598455632145",
    send: "",
    position: "นิติกร",
    agency: "กลุ่มงานนิติกร",
    mutiselect: [],
  },
]);

onMounted(async () => {
  await nodeTree();
});

const paginationLabel = (start: number, end: number, total: number) => {
  //   if (props.paging == true)
  //     return " " + start + " ใน " + end + " จากจำนวน " + total + " รายการ";
  //   else
  return start + "-" + end + " ใน " + total;
};

const resetFilter = () => {
  // reset ค่าที่ค้นหาเมื่อกดปุ่ม X ในกล่องค้นหา
  filter.value = "";
  filterRef.value!.focus();
};

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};

const clickClose = async () => {
  //   if (editRow.value == true) {
  //   dialogMessage(
  //     $q,
  //     "ข้อมูลมีการแก้ไข",
  //     "ยืนยันที่จะปิดโดยไม่บันทึกใช่หรือไม่?",
  //     "mdi-help-circle-outline",
  //     "ตกลง",
  //     "orange",
  //     () => (modal.value = false),
  //     undefined
  //   );
  //   } else {
  modal.value = false;
  //     next.value = false;
  //     previous.value = false;
  //   }
};

const clickAdd = () => {
  modal.value = true;
};

const clickDelete = (id: string) => {
  dialogMessage(
    $q,
    "ยืนยันการลบข้อมูล",
    "ต้องการลบข้อมูลนี้ใช่หรือไม่?",
    "mdi-help-circle-outline",
    "ตกลง",
    "red",
    () => deleteData(id),
    undefined
  );
};

const nodeTree = async () => {
  showLoader();
  await http
    .get(config.API.profileOrganizRoot)
    .then((res: any) => {
      const data = res.data.result;
      nodesTree.value = data;
      if (data.length > 0) {
        expanded.value = [data[0].id];
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const onSelected = async (id: string) => {
  //   await fetchPositionNumber(id);
};

const deleteData = async (id: string) => {};
</script>

<template>
  <div>
    <div class="q-py-md q-pl-md" style="height: 68vh; overflow-y: scroll">
      <div class="col-12 row q-py-sm items-center">
        <q-btn flat round color="primary" @click="clickAdd" icon="mdi-plus">
          <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"
                @click="resetFilter"
              />
            </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>
      <d-table
        :rows="rows"
        :columns="columns"
        :visible-columns="visibleColumns"
        :filter="filter"
        row-key="name"
      >
        <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 key="no" :props="props">
              {{ props.rowIndex + 1 }}
            </q-td>
            <q-td key="idcard" :props="props">
              {{ props.row.idcard }}
            </q-td>
            <q-td key="name" :props="props">
              {{ props.row.name }}
            </q-td>
            <q-td key="position" :props="props">
              {{ props.row.position }}
            </q-td>
            <q-td key="agency" :props="props">
              {{ props.row.agency }}
            </q-td>
            <q-td key="send" :props="props">
              <q-select
                :class="getClass(true)"
                hide-bottom-space
                multiple
                :outlined="true"
                dense
                lazy-rules
                v-model="props.row.mutiselect"
                :rules="[(val:any) => !!val || `${'กรุณาเลือกช่องทางการส่งสำเนา'}`,(val:any) => val.length > 0 || `${'กรุณาเลือกช่องทางการส่งสำเนา'}`]"
                :label="`${'เลือกช่องทางการส่งสำเนา'}`"
                emit-value
                map-options
                option-label="name"
                :options="optionSelect"
                option-value="id"
                input-debounce="0"
                color="primary"
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-black">
                      ไม่พบข้อมูลที่ค้นหา
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
            </q-td>
            <q-td auto-width>
              <q-btn
                dense
                size="12px"
                flat
                round
                color="red"
                @click="clickDelete(props.row.id)"
                icon="mdi-delete"
              >
                <q-tooltip>ลบข้อมูล</q-tooltip>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
    <q-separator />
    <div class="flex justify-end q-pa-sm q-gutter-sm">
      <q-btn
        dense
        outline
        color="primary"
        icon="chevron_left"
        @click="previous"
        class="q-pr-md"
        label="เลือกรายชื่อ"
      >
      </q-btn>
      <q-btn
        dense
        unelevated
        label="บันทึก"
        color="public"
        @click="next"
        class="q-px-md"
        ><!-- icon="mdi-content-save-outline"
        <q-tooltip>บันทึก</q-tooltip> -->
      </q-btn>
      <!-- <q-btn flat round color="primary" icon="chevron_right" @click="next">
        <q-tooltip>ต่อไป</q-tooltip>
      </q-btn> -->
    </div>
  </div>

  <q-dialog v-model="modal" persistent full-width>
    <q-card>
      <q-form ref="myForm">
        <DialogHeader tittle="เลือกรายชื่อตามหน่วยงาน" :close="clickClose" />
        <q-separator />
        <q-card-section class="q-pa-sm bg-grey-1">
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-12 col-sm-5 row">
              <q-card flat bordered class="fit q-pa-sm">
                <q-scroll-area visible style="height: 70vh">
                  <q-input
                    outlined
                    dense
                    v-model="search"
                    placeholder="ค้นหา"
                    class="q-mb-sm"
                  >
                    <template v-slot:append>
                      <q-icon name="mdi-magnify" />
                    </template>
                  </q-input>
                  <q-tree
                    :nodes="nodesTree"
                    dense
                    node-key="id"
                    v-model:selected="selected"
                    v-model:expanded="expanded"
                    no-selection-unset
                    selected-color="primary"
                    @update:selected="onSelected"
                    default-expand-all
                  />
                </q-scroll-area>
              </q-card>
            </div>
            <div class="col-xs-12 col-sm-7">
              <div class="col-12 row q-py-sm items-center">
                <q-space />
                <div class="items-center" style="display: flex">
                  <q-input
                    standout
                    dense
                    v-model="filterModal"
                    ref="filterRef"
                    outlined
                    debounce="300"
                    placeholder="ค้นหา"
                    style="max-width: 200px"
                    class="q-ml-sm"
                  >
                    <template v-slot:append>
                      <q-icon v-if="filterModal == ''" name="search" />
                      <q-icon
                        v-if="filterModal !== ''"
                        name="clear"
                        class="cursor-pointer"
                        @click="resetFilter"
                      />
                    </template>
                  </q-input>

                  <q-select
                    v-model="visibleColumnsModal"
                    :display-value="$q.lang.table.columns"
                    multiple
                    outlined
                    dense
                    :options="columnsModal"
                    options-dense
                    option-value="name"
                    map-options
                    emit-value
                    style="min-width: 150px"
                    class="gt-xs q-ml-sm"
                  />
                </div>
              </div>
              <d-table
                :rows="rowsModal"
                :columns="columnsModal"
                :visible-columns="visibleColumnsModal"
                :filter="filterModal"
                row-key="name"
                selection="multiple"
                v-model:selected="selectedModal"
              >
                <template v-slot:header-selection="scope">
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    v-model="scope.selected"
                  />
                </template>

                <template v-slot:body-selection="scope">
                  <!-- <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    :model-value="scope.selected"
                    @update:model-value="
                      (val, evt) => {
                        Object.getOwnPropertyDescriptor(scope, 'selected').set(
                          val,
                          evt
                        );
                      }
                    "
                  /> -->
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    v-model="scope.selected"
                  />
                </template>

                <template v-slot:body-cell="props">
                  <q-td :props="props">
                    <div v-if="props.col.name == 'no'">
                      {{ props.rowIndex + 1 }}
                    </div>

                    <div v-else>
                      {{ props.value }}
                    </div>
                  </q-td>
                </template>
              </d-table>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn
            flat
            round
            color="public"
            icon="mdi-content-save-outline"
            @click="clickClose"
          >
            <q-tooltip>บันทึก</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style lang="scss"></style>
