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

import type { DataOption } from "@/modules/14_KPI/interface/index/Main";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

/** use*/
const $q = useQuasar();
const router = useRouter();
const { showLoader, hideLoader, dialogRemove, success, messageError } =
  useCounterMixin();

/** หัวตาราง */
const rows = ref<any[]>([]);
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 node = ref<any>([]);
const expanded = ref<any>([]);
const filterMain = ref<string>("");
const visibleColumns = ref<string[]>(["including", "includingName"]);

const roundOp = ref<DataOption[]>([]);

const totalList = ref<number>(1);

const year = ref<number>(new Date().getFullYear());
const nodeData = reactive<any>({
  page: 1,
  pageSize: 10,
  round: "",
  nodeId: null,
  node: null,
  keyword: "",
});

function fetchRoundOption() {
  showLoader();
  http
    .get(
      config.API.kpiPeriod +
        `?page=${1}&pageSize=${10}&keyword=${""}&year=${year.value}`
    )
    .then((res) => {
      const data = res.data.result.data;
      const list = data.map((e: any) => ({
        id: e.id,
        name:
          e.durationKPI === "OCT"
            ? "รอบตุลาคม"
            : e.durationKPI === "APR"
            ? "รอบเมษายน"
            : "",
      }));
      roundOp.value = list;
      nodeData.round = "";
      fetchListProjectNew();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}
function fetchList() {
  showLoader();
  http
    .get(
      config.API.kpiPlan +
        `?page=${nodeData.page}&pageSize=${nodeData.pageSize}&kpiPeriodId=${nodeData.round}&nodeId=${nodeData.nodeId}&node=${nodeData.node}&keyword=${nodeData.keyword}`
    )
    .then((res) => {
      const data = res.data.result.data;
      totalList.value = Math.ceil(res.data.result.total / nodeData.pageSize);
      rows.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onClickAddOrView(status: boolean = false, id: string = "") {
  status
    ? router.push(`/KPI-indicator-plan/${id}`)
    : router.push("/KPI-indicator-plan/add");
}

function fetchActive() {
  showLoader();
  http
    .get(config.API.activeOrganization)
    .then((res) => {
      const data = res.data.result;
      fetchTree(data.activeId);
    })
    .catch((err) => {
      messageError($q, err);
      hideLoader();
    });
}

async function fetchTree(id: string) {
  showLoader();
  http
    .get(config.API.orgByid(id.toString()))
    .then((res) => {
      const data = res.data.result;
      node.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function updateSelectedTreeMain(data: any) {
  if (nodeData.node === data.orgLevel && nodeData.nodeId === data.orgTreeId) {
    nodeData.node = null;
    nodeData.nodeId = null;
  } else {
    nodeData.node = data.orgLevel;
    nodeData.nodeId = data.orgTreeId;
  }
  fetchListProjectNew();
}

function fetchListProjectNew() {
  nodeData.page = 1;
  fetchList();
}

async function deleteData(idData: string) {
  dialogRemove($q, () =>
    http
      .delete(config.API.kpiPlanById(idData))
      .then(() => {
        fetchList();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      })
  );
}

onMounted(() => {
  fetchActive();
  fetchRoundOption();
  // fetchData();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการตัวชี้วัดตามแผนฯ
  </div>
  <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
              class="inputgreen"
              dense
              outlined
              v-model="filterMain"
              label="ค้นหา"
            >
              <template v-slot:append>
                <q-icon
                  v-if="filterMain !== ''"
                  name="clear"
                  class="cursor-pointer"
                  @click="filterMain = ''"
                />
                <q-icon v-else 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"
              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.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 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">
        <q-toolbar style="padding: 0">
          <div class="row q-gutter-sm">
            <datepicker
              menu-class-name="modalfix"
              v-model="year"
              :locale="'th'"
              autoApply
              year-picker
              :enableTimePicker="false"
              style="width: 150px"
              @update:model-value="fetchRoundOption"
            >
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input
                  class="inputgreen"
                  dense
                  lazy-rules
                  outlined
                  :model-value="year === 0 ? 'ทั้งหมด' : Number(year) + 543"
                  :label="`${'ปีงบประมาณ'}`"
                >
                  <template v-slot:prepend>
                    <q-icon
                      name="event"
                      class="cursor-pointer"
                      style="color: var(--q-primary)"
                    >
                    </q-icon>
                  </template>
                </q-input>
              </template>
            </datepicker>
            <q-select
              class="inputgreen"
              dense
              outlined
              v-model="nodeData.round"
              :options="roundOp"
              label="รอบการประเมิน"
              option-label="name"
              option-value="id"
              emit-value
              map-options
              @update:model-value="fetchListProjectNew"
              style="min-width: 150px"
            />
            <q-toolbar-title>
              <q-btn
                flat
                round
                dense
                icon="add"
                color="primary"
                @click="onClickAddOrView()"
              >
                <q-tooltip>เพิ่ม</q-tooltip>
              </q-btn>
            </q-toolbar-title>
          </div>
          <q-space />
          <div class="row q-gutter-sm">
            <q-input
              class="inputgreen"
              standout
              dense
              v-model="nodeData.keyword"
              ref="filterRef"
              outlined
              placeholder="ค้นหา"
              @keydown.enter.prevent="fetchListProjectNew"
            >
              <template v-slot:append>
                <q-icon v-if="nodeData.keyword == ''" name="search" />
                <q-icon
                  v-if="nodeData.keyword !== ''"
                  name="clear"
                  class="cursor-pointer"
                  @click="nodeData.keyword = ''"
                />
              </template>
            </q-input>
            <q-select
              class="inputgreen"
              v-model="visibleColumns"
              multiple
              outlined
              dense
              options-dense
              :display-value="$q.lang.table.columns"
              emit-value
              map-options
              :options="columns"
              option-value="name"
              options-cover
              style="min-width: 150px"
            />
          </div>
        </q-toolbar>
        <div class="col-12">
          <d-table
            for="table"
            ref="table"
            :columns="columns"
            :rows="rows"
            row-key="subject"
            flat
            bordered
            dense
            class="custom-header-table"
            :visible-columns="visibleColumns"
          >
            <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 v-for="col in props.cols" :key="col.name" :props="props">
                  <div class="table_ellipsis">
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
                <q-td>
                  <q-btn
                    color="primary"
                    flat
                    dense
                    round
                    class="q-mr-xs"
                    size="14px"
                    icon="mdi-pencil-outline"
                    clickable
                    @click="onClickAddOrView(true, props.row.id)"
                  >
                    <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                  </q-btn>
                  <q-btn
                    flat
                    round
                    icon="delete"
                    color="red"
                    @click.stop.pervent="deleteData(props.row.id)"
                  >
                    <q-tooltip>ลบข้อมูล </q-tooltip>
                  </q-btn>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </div>
    </div>
  </q-card>
</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>
