<script setup lang="ts">
import DialogHeader from "@/components/DialogHeader.vue";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import { ref, watch, reactive } from "vue";
import type { QInput, QTableProps } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

import type {
  OrgTree,
  DataTree,
  Positions,
  DataPositionNo,
  FormActive,
  TreeMain,
} from "@/interface/request/orgSelect/org";

const rows = ref<any[]>([]);
const filterRef = ref<QInput>();
const filterModal = ref<string>("");
const props = defineProps({
  dataRows: {
    type: Object,
    require: true,
  },
  onSubmit: Function,
  saveData: Function,
});
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  dialogConfirm,
  showLoader,
  messageError,
  hideLoader,
  date2Thai,
  dialogMessageNotify,
} = mixin;

const modal = defineModel<boolean>("modal", { required: true });
const title = defineModel<string>("title", { required: true });
const selectedModal = defineModel<any[]>("selectedModal");

const filter = ref<string>("");
const isAll = ref<boolean>(false);
const isBlank = ref<boolean>(false);
const positionNo = ref<DataPositionNo[]>();
const itemTaps = ref<string[]>();
const positionId = ref<string>("");
const selectedPos = ref<any[]>([]);
const seletcId = ref<string>("");
const datePos = ref<Date>(new Date());
const rowsPosition = ref<Positions[]>([]);
const positionData = ref<any>();
/** active form */
const formActive = reactive<FormActive>({
  activeId: "",
  activeName: "",
  draftId: "",
  draftName: "",
  orgPublishDate: null,
  isPublic: false,
});
/** node */
const nodes = ref<Array<OrgTree>>([]);
const lazy = ref(nodes);
const expanded = ref<string[]>([]);
const nodeLevel = ref<number>(0);
const nodeId = ref<string>(""); // id ของ Tree

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    field: "no",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    field: "citizenId",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-นามสกุล",
    field: "name",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    field: "position",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const visibleColumns = ref<String[]>(["no", "citizenId", "name", "position"]);

/** ปิด dialog */
function close() {
  modal.value = false;
  filter.value = "";
  isAll.value = false;
  isBlank.value = false;

  nodes.value = [];
  expanded.value = [];
  nodeLevel.value = 0;
  nodeId.value = "";

  rows.value = [];
  selectedModal.value = [];
}

async function getDataTable(id: string, level: number = 0) {
  //new
  showLoader();
  http
    .post(config.API.orgDeceasedProfile, {
      nodeId: id,
      node: level,
      isAll: isAll.value,
    })
    .then((res) => {
      const data = res.data.result.data;

      rows.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
  //old
  //   showLoader();

  //   const body = {
  //     node: level,
  //     nodeId: id,
  //     typeCommand: type.value,
  //     position: posType.value ? posType.value : "",
  //     posLevel: posLevel.value ? posLevel.value : "",
  //     posType: position.value ? position.value : "",
  //     isAll: isAll.value,
  //     isBlank: isBlank.value,
  //   };

  //   await http
  //     .post(config.API.orgPosPlacement, body)
  //     .then((res) => {
  //       const dataMain: PositionMain[] = [];
  //       posMasterMain.value = res.data.result.data;

  //       res.data.result.data.forEach((e: PositionNo) => {
  //         const p = e.positions;
  //         if (p.length !== 0) {
  //           const a = p.find((el: Positions) => el.positionIsSelected === true);
  //           const { id, ...rest } = a ? a : p[0];
  //           const data: any = { ...e, ...rest };
  //           dataMain.push(data);
  //         }
  //       });
  //       const listPosNo: DataPositionNo[] = dataMain.map((e: PositionMain) => ({
  //         id: e.id,
  //         isPosition: e.isPosition,
  //         posMasterNo:
  //           e.orgShortname +
  //           (e.posMasterNoPrefix != null ? e.posMasterNoPrefix : "") +
  //           e.posMasterNo +
  //           (e.posMasterNoSuffix != null ? e.posMasterNoSuffix : ""),
  //         positionName: e.positionName,
  //         posTypeName: e.posTypeName,
  //         posLevelName: e.posLevelName,
  //         positionIsSelected: e.positionIsSelected
  //           ? e.fullNameCurrentHolder
  //           : "-",
  //         isSit: e.isSit,
  //         positions: e.positions,
  //         node: e.node,
  //         nodeId: e.nodeId,
  //       }));

  //       positionNo.value = listPosNo;
  //       positionData.value = listPosNo;
  //     })
  //     .catch((err) => {
  //       messageError($q, err);
  //     })
  //     .finally(() => {
  //       setTimeout(() => {
  //         hideLoader();
  //       }, 1000);
  //     });
}

/**
 * funtion เลือกข้อมูล Tree
 * @param data ข่อมูล Tree
 */
function updateSelected(data: DataTree) {
  positionId.value = "";
  seletcId.value = "";
  selectedPos.value = [];
  datePos.value = new Date();

  nodeId.value = data.orgTreeId ? data.orgTreeId : "";
  nodeLevel.value = data.orgLevel;
  getDataTable(data.orgTreeId, data.orgLevel);
}

/** ดึงข้อมูล active */
async function getActive() {
  showLoader();
  await http
    .get(config.API.activeOrganization)
    .then((res) => {
      const data = res.data.result;

      formActive.activeId = data.activeId;
      formActive.activeName = data.activeName;
      formActive.draftId = data.draftId;
      formActive.draftName = data.draftName;
      formActive.orgPublishDate = data.orgPublishDate;
      formActive.isPublic = data.isPublic;

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

/** ดึงข้อมูล หน่วยงาน */
async function getTreeData(id: string) {
  showLoader();
  await http
    .get(config.API.orgByid(id))
    .then((res) => {
      const data = res.data.result;
      nodes.value = data;
      filterItemsTaps(data);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function filterItemsTaps(data: TreeMain[]) {
  let orgTreeIds: string[] = [];
  for (const child of data) {
    orgTreeIds.push(child.orgTreeId);
    if (child.children) {
      orgTreeIds = orgTreeIds.concat(filterItemsTaps(child.children));
    }
  }
  itemTaps.value = orgTreeIds;
  return orgTreeIds;
}

/**
 * function เลือกเลขที่ตำแหน่ง
 * @param id เลชที่ตำแหน่ง
 */
async function onClickSelectPos(id: string) {
  positionData.value = positionNo.value;
  positionId.value = id;
  selectedPos.value = [];
  const position: DataPositionNo = positionData.value.find(
    (e: DataPositionNo) => e.id === id
  );

  // หาตำแหน่ง
  if (position) {
    rowsPosition.value = position.positions;
    if (seletcId.value) {
      selectedPos.value = rowsPosition.value.filter(
        (e) => e.id === seletcId.value
      );
    }
  }
}

/**
 * function fetch ข้อมูล expanded tree
 * @param level levelTree
 * @param id treeId
 */
async function fetchPosFind(level: number, id: string) {
  showLoader();
  const body = {
    node: level,
    nodeId: id,
  };
  await http
    .post(config.API.orgPosFind, body)
    .then((res) => {
      const data = res.data.result;
      expanded.value = data;
      nodeId.value = id;
      positionId.value = props?.dataRows?.posmasterId;
      seletcId.value = props?.dataRows?.positionId;
      datePos.value = props?.dataRows?.reportingDateFullDate;

      getDataTable(nodeId.value, level);
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    });
}

watch(
  () => modal.value,
  async (n) => {
    if (n == true) {
      getActive();
    }
  }
);

watch(
  () => isAll.value,
  (value, oldVal) => {
    if (value !== oldVal) {
      getDataTable(nodeId.value, nodeLevel.value);
    }
  }
);

watch(
  () => isBlank.value,
  (value, oldVal) => {
    if (value !== oldVal) {
      getDataTable(nodeId.value, nodeLevel.value);
    }
  }
);

watch(
  () => positionId.value,
  (n) => {
    if (n) {
      onClickSelectPos(n);
    }
  }
);
function onSubmit() {
  if (nodeId.value == "") {
    dialogMessageNotify($q, "กรุณาเลือกตำแหน่ง");
  } else {
    dialogConfirm($q, async () => {
      props.saveData?.();
      close();
    });
  }
}

function resetFilter() {
  filter.value = "";
  filterRef.value!.focus();
}
</script>
<template>
  <q-dialog v-model="modal" persistent full-width>
    <q-card class="no-scroll">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader :tittle="title" :close="close" />
        <q-separator />
        <q-card-section style="max-height: 80vh" class="scroll">
          <div class="row">
            <q-card
              bordered
              class="col-12 col-sm-3 scroll q-pa-sm"
              style="height: 75vh"
            >
              <q-input dense outlined v-model="filter" label="ค้นหา">
                <template v-slot:append>
                  <q-icon
                    v-if="filter !== ''"
                    name="clear"
                    class="cursor-pointer"
                    @click="filter = ''"
                  />
                </template>
              </q-input>
              <q-tree
                class="q-pa-sm q-gutter-sm"
                dense
                :nodes="lazy"
                node-key="orgTreeId"
                label-key="orgTreeName"
                :filter="filter"
                no-results-label="ไม่พบข้อมูลที่ค้นหา"
                no-nodes-label="ไม่มีข้อมูล"
                v-model:expanded="expanded"
              >
                <template v-slot:default-header="prop">
                  <q-item
                    @click.stop="updateSelected(prop.node)"
                    clickable
                    :active="nodeId == prop.node.orgTreeId"
                    active-class="my-list-link text-primary text-weight-medium"
                    class="row col-12 items-center text-dark q-py-xs q-pl-sm rounded-borders my-list"
                  >
                    <div>
                      <div class="text-weight-medium">
                        {{ prop.node.orgTreeName }}
                      </div>
                      <div class="text-weight-light">
                        {{
                          prop.node.orgCode == null ? null : prop.node.orgCode
                        }}
                        {{
                          prop.node.orgTreeShortName == null
                            ? null
                            : prop.node.orgTreeShortName
                        }}
                      </div>
                    </div>
                  </q-item>
                </template>
              </q-tree>
            </q-card>
            <q-card bordered class="col-12 col-sm-9 q-pa-sm">
              <div class="col-12 row q-py-sm items-center q-col-gutter-sm">
                <q-space />
                <div class="items-center" style="display: flex">
                  <q-checkbox
                    keep-color
                    v-model="isAll"
                    label="แสดงทั้งหมด"
                    color="primary"
                  >
                    <q-tooltip>แสดงทั้งหมด</q-tooltip>
                  </q-checkbox>
                  <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="visibleColumns"
                    :display-value="$q.lang.table.columns"
                    multiple
                    outlined
                    dense
                    :options="columns"
                    options-dense
                    option-value="name"
                    map-options
                    emit-value
                    style="min-width: 140px"
                    class="gt-xs q-ml-sm"
                  />
                </div>
                <div class="col-12">
                  <d-table
                    :rows="rows"
                    :columns="columns"
                    :visible-columns="visibleColumns"
                    :filter="filterModal"
                    row-key="id"
                    selection="multiple"
                    v-model:selected="selectedModal"
                    :rows-per-page-options="[10, 25, 50, 100]"
                  >
                    <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 auto-width>
                          <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>
              </div>
            </q-card>
          </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>
<style scoped>
.my-list-link {
  color: rgb(118, 168, 222);
  border-radius: 5px;
  background: #a3d3fb48 !important;
  font-weight: 600;
  border: 1px solid rgba(175, 185, 196, 0.217);
}
</style>
