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

import http from "@/plugins/http";
import config from "@/app.config";

import type { DataOption } from "@/modules/01_masterdata/interface/index/Main";
import DialogHistory from "@/modules/01_masterdata/components/Indicators/DialogHistory.vue";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";

/** use*/
const dataHistory = ref<any[]>([]);
const modalHistory = ref<boolean>(false);
const isAll = ref<boolean>(false);
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[]>([
  { id: "", name: "ทั้งหมด" },
  { id: "APR", name: "รอบเมษายน" },
  { id: "OCT", name: "รอบตุลาคม" },
]);

const totalList = ref<number>(1);

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

function fetchList() {
  if (nodeData.nodeId) {
    showLoader();
    http
      .post(config.API.kpiPlan + `/search`, {
        isAll: isAll.value,
        keyword: nodeData.keyword,
        node: nodeData.node ? nodeData.node : 0,
        nodeId: nodeData.nodeId,
        period: nodeData.round,
        year: year.value?.toString(),
        pageSize: nodeData.pageSize,
        page: nodeData.page,
      })
      .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(`/masterdata/indicator-plan/${id}`)
    : router.push("/masterdata/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();
      })
  );
}

function clearFilter() {
  nodeData.keyword = "";
  fetchActive();
  fetchListProjectNew();
}

/**
 * เปิด dialog history
 * @param 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();
    });
}

onMounted(() => {
  fetchActive();
});
</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 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">
        <div class="row q-col-gutter-sm items-center q-mb-sm no-wrap">
          <datepicker
            menu-class-name="modalfix"
            v-model="year"
            :locale="'th'"
            autoApply
            year-picker
            :enableTimePicker="false"
            style="width: 150px"
            @update:model-value="fetchListProjectNew"
          >
            <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), (nodeData.page = 1), fetchListProjectNew()
                    "
                    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="fetchListProjectNew"
            style="min-width: 120px"
          >
            <template v-if="nodeData.round" v-slot:append>
              <q-icon
                name="cancel"
                @click.stop.prevent="
                  (nodeData.round = ''), fetchListProjectNew()
                "
                class="cursor-pointer"
              />
            </template>
          </q-select>

          <q-btn
            flat
            round
            dense
            icon="add"
            color="primary"
            @click="onClickAddOrView()"
          >
            <q-tooltip>เพิ่ม</q-tooltip>
          </q-btn>

          <q-space />

          <q-checkbox
            keep-color
            v-model="isAll"
            label="แสดงทั้งหมด"
            color="primary"
            @update:model-value="fetchListProjectNew"
          >
            <q-tooltip
              >แสดงตำแหน่งทั้งหมดภายใต้หน่วยงาน/ส่วนราชการที่เลือก</q-tooltip
            >
          </q-checkbox>
          <q-input
            standout
            dense
            v-model="nodeData.keyword"
            ref="filterRef"
            outlined
            style="width: 150px"
            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="clearFilter"
              />
            </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"
            options-cover
            style="min-width: 120px"
          />
        </div>

        <div class="col-12">
          <d-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"
          >
            <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" class="cursor-pointer">
                <q-td auto-width>
                  <q-btn
                    flat
                    round
                    color="grey"
                    @click.stop
                    size="14px"
                    icon="more_vert"
                  >
                    <q-menu>
                      <q-list style="min-width: 180px">
                        <q-item
                          clickable
                          v-close-popup
                          @click="onClickAddOrView(true, props.row.id)"
                        >
                          <q-item-section
                            style="min-width: 0px"
                            avatar
                            class="q-py-sm"
                          >
                            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                            <q-icon
                              color="primary"
                              size="xs"
                              name="mdi-pencil-outline"
                            />
                          </q-item-section>
                          <q-item-section>แก้ไขข้อมูล</q-item-section>
                        </q-item>
                        <q-item
                          clickable
                          v-close-popup
                          @click="onClickHistory(props.row.id)"
                        >
                          <q-item-section
                            style="min-width: 0px"
                            avatar
                            class="q-py-sm"
                          >
                            <q-tooltip>ประวัติการแก้ไข</q-tooltip>
                            <q-icon color="info" size="xs" name="mdi-history" />
                          </q-item-section>
                          <q-item-section>ประวัติการแก้ไข</q-item-section>
                        </q-item>
                        <q-item
                          clickable
                          v-close-popup
                          @click.stop.pervent="deleteData(props.row.id)"
                        >
                          <q-item-section
                            style="min-width: 0px"
                            avatar
                            class="q-py-sm"
                          >
                            <q-tooltip>ลบข้อมูล</q-tooltip>
                            <q-icon color="red" size="xs" name="mdi-delete" />
                          </q-item-section>
                          <q-item-section>ลบข้อมูล</q-item-section>
                        </q-item>
                      </q-list>
                    </q-menu>
                  </q-btn>
                </q-td>
                <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-tr>
            </template>
          </d-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>
