<!-- =============================== -->
<!-- page:main page จัดการบัญชี 2 -->
<!-- =============================== -->
<template>
  <div class="toptitle text-dark col-12 row items-center">จัดการบัญชี 2</div>
  <q-card flat bordered class="col-12 q-mt-sm">
    <q-layout
      view="hHh Lpr lff"
      container
      class="shadow-2 rounded-borders page-relative"
      style="height: 80vh"
    >
      <q-drawer
        v-model="isDrawer"
        class="bg-grey-1"
        :width="220"
        :breakpoint="400"
        bordered
      >
        <q-btn
          size="13px"
          class="btn-absolute btnShadow"
          color="white"
          dense
          round
          unelevated
          @click="isDrawer = false"
          v-if="isDrawer"
        >
          <q-tooltip>ปิด</q-tooltip>
          <q-icon name="chevron_left" size="20px" color="grey-7" />
        </q-btn>
        <q-scroll-area class="fit">
          <div class="row col-12 text-dark q-pt-sm">
            <div class="col-12 q-pa-sm">
              <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"
                @update:expanded="clickTree"
              />
            </div>
          </div>
        </q-scroll-area>
      </q-drawer>
      <q-page-container class="q-mx-sm q-pt-md">
        <TableReport
          :rows="rows"
          :columns="columns"
          :filter="filter"
          :visible-columns="visibleColumns"
          v-model:inputfilter="filter"
          v-model:inputvisible="visibleColumns"
          v-model:isTab="isDrawer"
          :delect="true"
          :onTab="changeTab"
          :onConfirm="onConfirm"
          :onHistory="onHistory"
          table-style="height: 64vh"
        >
          <template #columns="props">
            <q-tr :props="props" class="cursor-pointer">
              <q-td
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                @click="clickTransfer(props.row)"
              >
                <div v-if="col.name == 'no'">
                  {{ props.rowIndex + 1 }}
                </div>
                <div
                  v-else-if="col.name == 'levelOld' || col.name == 'levelNew'"
                >
                  {{ String(col.value) }}
                </div>
                <div v-else>
                  {{ col.value }}
                </div>
              </q-td>
              <!-- <q-td>
                <q-btn
                  size="14px"
                  dense
                  flat
                  round
                  color="info"
                  icon="mdi-history"
                >
                  <q-tooltip>ประวัติ</q-tooltip>
                </q-btn>
              </q-td> -->
            </q-tr>
          </template>
        </TableReport>
      </q-page-container>
    </q-layout>
  </q-card>
</template>

<script setup lang="ts">
import { onMounted, computed, ref, watch } from "vue";
import { useQuasar, QForm } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useRouter, useRoute } from "vue-router";

import TableReport from "@/modules/02_organizational/components/TableReport.vue";
import type { Columns } from "@/modules/02_organizational/interface/index/Main";
import http from "@/plugins/http";
import config from "@/app.config";
import type { treeTab } from "@/modules/04_registry/interface/index/Main";
import type { ResponseTree } from "@/modules/02_organizational/interface/response/Mapping";
import { useDataStore } from "@/stores/data";

const dataStore = useDataStore();
const $q = useQuasar(); // show dialog
const mixin = useCounterMixin();
const router = useRouter();
const route = useRoute();
const { selectedReport2, expandedReport2, changeTreeReport2 } = dataStore;
const { date2Thai, success, dateToISO, modalError, showLoader, hideLoader } =
  mixin;
const filter = ref<string>(""); //search data table
const visibleColumns = ref<String[]>([]);

const profileType = ref<string>("officer");
const isDrawer = ref<boolean>(true);
const expanded = ref<string[]>([]);
const selected = ref<string>("");
const nodesTree = ref<treeTab[]>([]);
const columns = ref<any>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-สกุล",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },
  {
    name: "edu",
    align: "left",
    label: "คุณวุฒิ",
    sortable: true,
    field: "edu",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "posiNumOld",
    align: "left",
    label: "ตำแหน่งเลขที่เดิม",
    sortable: true,
    field: "posiNumOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
    // sort: (a: string, b: string) => {
    //   let setA = "";
    //   let setB = "";

    //   for (let index = 0; index < a.length; index++) {
    //     const num = a[index];
    //     const check = parseInt(num);
    //     if (!isNaN(check)) {
    //       setA += num.toString();
    //     }
    //   }

    //   for (let index = 0; index < b.length; index++) {
    //     const num = b[index];
    //     const check = parseInt(num);
    //     if (!isNaN(check)) {
    //       setB += num.toString();
    //     }
    //   }

    //   return parseInt(setA) - parseInt(setB);
    // },
  },
  {
    name: "posiOld",
    align: "left",
    label: "ตำแหน่งเดิม",
    sortable: true,
    field: "posiOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "levelOld",
    align: "left",
    label: "ระดับเดิม",
    sortable: true,
    field: "levelOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posiNumNew",
    align: "left",
    label: "ตำแหน่งเลขที่ใหม่",
    sortable: true,
    field: "posiNumNew",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posiNew",
    align: "left",
    label: "ตำแหน่งใหม่",
    sortable: true,
    field: "posiNew",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "levelNew",
    align: "left",
    label: "ระดับใหม่",
    sortable: true,
    field: "levelNew",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "change",
    align: "left",
    label: "การเปลี่ยนแปลง",
    sortable: true,
    field: "change",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "statusPosition",
    align: "left",
    label: "สถานะตำแหน่งเลขที่",
    sortable: true,
    field: "statusPosition",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const rows = ref<ResponseTree[]>([]);

onMounted(async () => {
  let arVisible: string[] = [];
  columns.value.map((r: any) => {
    arVisible.push(r.name);
  });
  visibleColumns.value = arVisible;

  await nodeTree();
  await doSearch();
});

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) {
        selected.value = selectedReport2 == "" ? data[0].id : selectedReport2;
        expanded.value =
          expandedReport2.length == 0 ? [data[0].id] : expandedReport2;
      }
    })
    .catch((e: any) => {})
    .finally(() => {
      hideLoader();
    });
};

const onSelected = async (id: string) => {
  clickTree();
  await doSearch();
};

const clickTree = () => {
  changeTreeReport2(expanded.value, selected.value);
};

const onHistory = async () => {
  showLoader();
  await http
    .get(config.API.report2HistoryId(selected.value))
    .then((res) => {
      const data = res.data.result;
      if (data.length == 0) {
        modalError(
          $q,
          "ประวัติแก้ไขข้อมูลบัญชี 2",
          "ไม่มีข้อมูลประวัติแก้ไขข้อมูลบัญชี 2"
        );
      } else {
        router.push(`/organizational/manage/report/history/${selected.value}`);
      }
    })
    .catch((e) => {
      modalError(
        $q,
        "ประวัติแก้ไขข้อมูลบัญชี 2",
        "ไม่มีข้อมูลประวัติแก้ไขข้อมูลบัญชี 2"
      );
    })
    .finally(async () => {
      hideLoader();
    });
};

const doSearch = async () => {
  //ทำไว้แล้ว เหลือ ใส่ type
  showLoader();
  await http
    .get(config.API.report2TreeId(selected.value))
    .then((res) => {
      const data = res.data.result;
      if (data.length > 0) {
        rows.value = [];
        let array: ResponseTree[] = [];
        data.map((e: ResponseTree, index: number) => {
          array.push({
            no: index + 1,
            report2Id: e.report2Id,
            profilePositionId: e.profilePositionId,
            organizationPositionId: e.organizationPositionId,
            name: e.name ?? "-",
            edu: e.edu ?? "-",
            posiNumOld: e.posiNumOld ?? "-",
            posiNumNew: e.posiNumNew ?? "-",
            posiOld: e.posiOld ?? "-",
            posiNew: e.posiNew ?? "-",
            levelOld: e.levelOld ?? "-",
            levelNew: e.levelNew ?? "-",
            change:
              e.report2Id == "00000000-0000-0000-0000-000000000000"
                ? "ไม่เปลี่ยนแปลง"
                : "เปลี่ยนแปลง",
            statusPosition:
              e.statusPosition?.toString() === "true" ? "ครอง" : "ไม่ครอง",
          });
        });
        rows.value = array;
      }
    })
    .catch((e) => {})
    .finally(() => {
      hideLoader();
    });
};

const changeTab = () => {
  isDrawer.value = !isDrawer.value;
};

const onConfirm = async () => {
  $q.dialog({
    title: `ยืนยันเพื่อเอาไปออกคำสั่ง`,
    message: `ต้องยืนยันเพื่อเอาไปออกคำสั่งใช่หรือไม่?`,
    cancel: "ยกเลิก",
    ok: "ยืนยัน",
    persistent: true,
  }).onOk(async () => {
    showLoader();
    await http
      .get(config.API.report2DoneId(selected.value))
      .then((res) => {
        success($q, "ยืนยันเพื่อเอาไปออกคำสั่งสำเร็จ");
      })
      .catch((e) => {})
      .finally(async () => {
        hideLoader();
        await doSearch();
      });
  });
};

const clickTransfer = async (rows: ResponseTree) => {
  //   if (rows.statusPosition) {
  router.push(
    `/organizational/manage/report/${rows.organizationPositionId ?? "1"}`
  );
  //   }
};
</script>

<style lang="scss" scope>
.expan .q-expansion-item--expanded {
  border: 1px solid #eaeaea;
  border-radius: 2px;
  margin: 5px 0px !important;
  background: #eaeaea4a !important;
}
.expan .q-expansion-item {
  border: 1px solid #eaeaea;
  margin-top: -1px;
  border-radius: 2px;
  background: white;
}
.my-custom-toggle {
  border: 1px solid #02a998;
}

.btn-absolute {
  z-index: 50;
  position: absolute;
  left: 200px;
  top: 10px;
}
.btnShadow {
  box-shadow: 0 1px 2px rgb(0 0 0 / 10%), 3px 3px 7px 1px rgba(95, 95, 95, 0.15) !important;
}
</style>
