<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useQuasar, type QTableProps } from "quasar";
import { useRouter, useRoute } from "vue-router";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { checkPermission } from "@/utils/permissions";
import { useStructureTree } from "@/stores/structureTree";
import { usePagination } from "@/composables/usePagination";
import { calculateFiscalYear } from "@/utils/function";

import type {
  DataOption,
  IndicatorType,
  OrgTreeNode,
  DataHistory,
  FormDataNodeData,
} from "@/modules/01_masterdata/interface/index/Main";

import DialogHistory from "@/modules/01_masterdata/components/Indicators/DialogHistory.vue";
import Summary from "@/modules/01_masterdata/components/Indicators/Summary.vue";

const $q = useQuasar();
const router = useRouter();
const route = useRoute();
const { fetchStructureTree } = useStructureTree();
const { showLoader, hideLoader, dialogRemove, success, messageError } =
  useCounterMixin();
const { pagination, params, onRequest, checkAndUpdatePage } = usePagination(
  "",
  () => fetchList()
);

const dataHistory = ref<DataHistory[]>([]);
const modalHistory = ref<boolean>(false);
const isAll = ref<boolean>(false);

/** หัวตาราง */
const rows = ref<IndicatorType[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "including",
    align: "left",
    label: "ลำดับ/รหัสตัวชี้วัด",
    sortable: true,
    field: "including",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "includingName",
    align: "left",
    label: "ชื่อตัวชี้วัด",
    sortable: true,
    field: "includingName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>(["including", "includingName"]);

const node = ref<OrgTreeNode[]>([]);
const expanded = ref<string[]>([]);
const filterMain = ref<string>("");

const roundOp = ref<DataOption[]>([
  { id: "", name: "ทั้งหมด" },
  { id: "APR", name: "รอบเมษายน" },
  { id: "OCT", name: "รอบตุลาคม" },
]);

const year = ref<number | null>(calculateFiscalYear(new Date()));
const nodeData = reactive<FormDataNodeData>({
  round: "",
  nodeId: null,
  node: null,
  keyword: "",
});

/** ฟังชั่นดึงข้อมูลรายการตัวชี้วัดตามแผน */
async function fetchList() {
  if (nodeData.nodeId) {
    showLoader();
    await http
      .post(config.API.kpiPlan + `/search-edit`, {
        isAll: isAll.value,
        keyword: nodeData.keyword.trim(),
        node: nodeData.node ? nodeData.node : 0,
        nodeId: nodeData.nodeId,
        period: nodeData.round,
        year: year.value?.toString(),
        ...params.value,
      })
      .then((res) => {
        const result = res.data.result;
        pagination.value.rowsNumber = result.total;
        rows.value = result.data;
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

/**
 * ฟังชั่น add/edit
 * @param status true = edit / false = add
 * @param id id edit
 */
function onClickAddOrView(status: boolean = false, id: string = "") {
  status
    ? router.push(`/masterdata/indicator-plan/${id}`)
    : router.push("/masterdata/indicator-plan/add");
}

/**
 * ฟังชั่นดูรายละเอียดรายการตัวชี้วัด
 * @param id id รายการตัวชี้วัดที่ต้องการดู
 */
function onClickView(id: string = "") {
  router.push(`/masterdata/indicator-plan/view/${id}`);
}

/** ดึงข้อมูลโครงสรร้าง */
async function fetchTree() {
  node.value = await fetchStructureTree(route.meta.Key as string, true);
}

/** เรียกข้อมูลตาม row โครงสร้าง*/
function updateSelectedTreeMain(data: OrgTreeNode) {
  if (nodeData.node === data.orgLevel && nodeData.nodeId === data.orgTreeId) {
    nodeData.node = null;
    nodeData.nodeId = null;
  } else {
    nodeData.node = data.orgLevel ?? null;
    nodeData.nodeId = data.orgTreeDnaId ?? null;
  }
  getSearch();
}

/**
 * ฟังชั่นลบข้อมูล
 * @param idData id ของข้อมูลที่ต้องการลบ
 */
async function deleteData(idData: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.kpiPlanById(idData))
      .then(async () => {
        await checkAndUpdatePage(rows.value.length);
        await fetchList();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * ฟังชั่นเปิด dialog history
 * @param id id รายการตัวชี้วัดที่ต้องการดูประวัติ
 */
function onClickHistory(id: string) {
  showLoader();
  http
    .get(config.API.kpiPlan + `/history/${id}`)
    .then((res) => {
      const data = res.data.result;
      dataHistory.value = data;
      modalHistory.value = true;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

onMounted(() => {
  fetchTree();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการตัวชี้วัดตามแผนฯ
  </div>

  <Summary />

  <q-card bordered class="col-12 row caedNone">
    <div class="col-xs-12 col-sm-3 row">
      <div class="col-12 row no-wrap">
        <div class="col-12 q-py-sm q-px-sm">
          <div class="q-gutter-sm">
            <div class="text-subtitle2 text-bold">หน่วยงาน/ส่วนราชการ</div>

            <q-input dense outlined v-model="filterMain" label="ค้นหา">
              <template v-slot:append>
                <q-icon name="search" color="grey-5" />
              </template>
            </q-input>

            <q-tree
              class="tree-container"
              dense
              :nodes="node"
              node-key="orgTreeName"
              label-key="labelName"
              v-model:expanded="expanded"
              :filter="filterMain.trim()"
              no-results-label="ไม่พบข้อมูลที่ค้นหา"
              no-nodes-label="ไม่มีข้อมูล"
              v-model:selected="nodeData.nodeId"
            >
              <template v-slot:default-header="prop">
                <q-item
                  clickable
                  @click.stop="updateSelectedTreeMain(prop.node)"
                  :active="nodeData.nodeId === prop.node.orgTreeDnaId"
                  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 text-grey-8">
                      {{ prop.node.orgCode == null ? null : prop.node.orgCode }}
                      {{
                        prop.node.orgTreeShortName == null
                          ? null
                          : prop.node.orgTreeShortName
                      }}
                    </div>
                  </div>
                </q-item>
              </template>
            </q-tree>
          </div>
        </div>
        <div class="col-12 row">
          <q-separator :vertical="!$q.screen.lt.md" />
        </div>
      </div>
    </div>
    <div class="col-xs-12 col-sm-9 q-pa-md row">
      <div class="col-12">
        <div class="row q-col-gutter-sm items-center q-mb-sm no-wrap">
          <datepicker
            v-model="year"
            :locale="'th'"
            autoApply
            year-picker
            :enableTimePicker="false"
            style="width: 150px"
            @update:model-value="getSearch"
          >
            <template #year="{ year }">{{ year + 543 }}</template>
            <template #year-overlay-value="{ value }">{{
              parseInt(value + 543)
            }}</template>
            <template #trigger>
              <q-input
                dense
                outlined
                :model-value="year === null ? 'ทั้งหมด' : Number(year) + 543"
                :label="`${'ปีงบประมาณ'}`"
              >
                <template v-slot:prepend>
                  <q-icon
                    name="event"
                    class="cursor-pointer"
                    style="color: var(--q-primary)"
                  >
                  </q-icon>
                </template>
                <template v-if="year" v-slot:append>
                  <q-icon
                    name="cancel"
                    @click.stop.prevent="(year = null), getSearch()"
                    class="cursor-pointer"
                  />
                </template>
              </q-input>
            </template>
          </datepicker>
          <q-select
            dense
            outlined
            v-model="nodeData.round"
            :options="roundOp"
            label="รอบการประเมิน"
            option-label="name"
            option-value="id"
            emit-value
            map-options
            @update:model-value="getSearch"
            style="min-width: 120px"
          >
            <template v-if="nodeData.round" v-slot:append>
              <q-icon
                name="cancel"
                @click.stop.prevent="(nodeData.round = ''), getSearch()"
                class="cursor-pointer"
              />
            </template>
          </q-select>

          <q-btn
            v-if="checkPermission($route)?.attrIsCreate"
            flat
            round
            dense
            icon="add"
            color="primary"
            @click="onClickAddOrView()"
          >
            <q-tooltip>เพิ่มข้อมูล</q-tooltip>
          </q-btn>

          <q-space />

          <q-checkbox
            :disable="nodeData.nodeId === null"
            keep-color
            v-model="isAll"
            label="แสดงทั้งหมด"
            color="primary"
            @update:model-value="getSearch"
          >
            <q-tooltip
              >แสดงตำแหน่งทั้งหมดภายใต้หน่วยงาน/ส่วนราชการที่เลือก</q-tooltip
            >
          </q-checkbox>
          <q-input
            standout
            dense
            v-model="nodeData.keyword"
            ref="filterRef"
            outlined
            placeholder="ค้นหา"
            @keydown.enter.prevent="getSearch"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
          <q-select
            v-model="visibleColumns"
            multiple
            outlined
            dense
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="columns"
            option-value="name"
            style="min-width: 140px"
          />
        </div>

        <div class="col-12">
          <p-table
            for="table"
            ref="table"
            :columns="columns"
            :rows="rows"
            row-key="id"
            flat
            bordered
            dense
            class="custom-header-table"
            :rows-per-page-options="[10, 25, 50, 100]"
            :visible-columns="visibleColumns"
            @request="onRequest"
            v-model:pagination="pagination"
          >
            <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">
                <q-td auto-width>
                  <q-btn
                    v-if="
                      checkPermission($route)?.attrIsGet ||
                      checkPermission($route)?.attrIsUpdate ||
                      checkPermission($route)?.attrIsDelete
                    "
                    flat
                    dense
                    color="secondary"
                    icon="mdi-dots-horizontal-circle-outline"
                    round
                  >
                    <q-menu>
                      <q-list dense style="min-width: 180px">
                        <q-item
                          v-if="checkPermission($route)?.attrIsGet"
                          clickable
                          v-close-popup
                          @click="onClickHistory(props.row.id)"
                        >
                          <q-item-section style="min-width: 0px" avatar>
                            <q-tooltip>ประวัติการแก้ไข</q-tooltip>
                            <q-icon
                              color="deep-purple"
                              flat
                              dense
                              round
                              name="mdi-history"
                              size="xs"
                            />
                          </q-item-section>
                          <q-item-section>ประวัติการแก้ไข</q-item-section>
                        </q-item>
                        <q-item
                          v-if="checkPermission($route)?.attrIsGet"
                          clickable
                          v-close-popup
                          @click="onClickView(props.row.id)"
                        >
                          <q-item-section style="min-width: 0px" avatar>
                            <q-tooltip>รายละเอียด</q-tooltip>
                            <q-icon
                              flat
                              dense
                              round
                              color="info"
                              name="mdi-eye"
                              size="xs"
                            />
                          </q-item-section>
                          <q-item-section>รายละเอียด</q-item-section>
                        </q-item>
                        <q-item
                          v-if="
                            checkPermission($route)?.attrIsGet &&
                            checkPermission($route)?.attrIsUpdate
                          "
                          clickable
                          v-close-popup
                          @click="onClickAddOrView(true, props.row.id)"
                        >
                          <q-item-section style="min-width: 0px" avatar>
                            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                            <q-icon
                              flat
                              dense
                              round
                              color="primary"
                              name="edit"
                              size="xs"
                            />
                          </q-item-section>
                          <q-item-section>แก้ไขข้อมูล</q-item-section>
                        </q-item>
                        <q-item
                          v-if="checkPermission($route)?.attrIsDelete"
                          clickable
                          v-close-popup
                          @click.stop.prevent="deleteData(props.row.id)"
                        >
                          <q-item-section style="min-width: 0px" avatar>
                            <q-tooltip>ลบข้อมูล</q-tooltip>
                            <q-icon
                              color="red"
                              flat
                              round
                              name="mdi-delete"
                              size="xs"
                            />
                          </q-item-section>
                          <q-item-section>ลบข้อมูล</q-item-section>
                        </q-item>
                      </q-list>
                    </q-menu>
                  </q-btn>
                  <!-- </q-btn> -->
                </q-td>
                <q-td v-for="col in props.cols" :key="col.name" :props="props">
                  <div class="table_ellipsis2">
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </p-table>
        </div>
      </div>
    </div>
  </q-card>

  <DialogHistory v-model:modal="modalHistory" :rows="dataHistory" />
</template>

<style lang="scss" scoped>
.tree-container {
  overflow: auto;
  height: 73vh;
  border: 1px solid #e6e6e7;
  border-radius: 10px;
}

.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>
