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

/** 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: "indicatorNo",
    align: "left",
    label: "ลำดับตัวชี้วัด ",
    sortable: true,
    field: "indicatorNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "indicatorPass",
    align: "left",
    label: "รหัสตัวชี้วัด",
    sortable: true,
    field: "indicatorPass",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "indicatorName",
    align: "left",
    label: "ชื่อตัวชี้วัด",
    sortable: true,
    field: "indicatorName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const node = ref<any>([]);
const expanded = ref<any>([]);
const filter = ref<string>("");
const filterMain = ref<string>("");
const visibleColumns = ref<string[]>([
  "indicatorNo",
  "indicatorPass",
  "indicatorName",
]);

const orgOp = ref<any[]>([
  { id: "1", name: "กลุ่มงานช่วยนักบริหาร" },
  { id: "2", name: "กลุ่มงานช่วยนักบริหาร 2" },
]);

const roundOp = ref<any[]>([
  { id: "1", name: "รอบเมษายน" },
  { id: "2", name: "รอบตุลาคม" },
]);

const formFilter = reactive({
  page: 1,
  pageSize: 10,
  org: "1",
  round: "1",
  keyword: "",
});

const nodeData = reactive<any>({
  node: null,
  nodeId: null,
});

function fetchList() {
  showLoader();
  const data = [
    {
      id: "1",
      indicatorNo: "1",
      indicatorPass: "1กก",
      indicatorName: "ตัวชี้วัด 1",
    },
    {
      id: "2",
      indicatorNo: "2",
      indicatorPass: "2กก",
      indicatorName: "ตัวชี้วัด 2",
    },
  ];
  rows.value = data;
  setTimeout(() => {
    hideLoader();
  }, 500);
}

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

function onClickDelete(id: number) {
  dialogRemove($q, () => {
    rows.value.splice(id, 1);
    success($q, "ลบข้อมูลสำเร็จ");
  });
}

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;
  }
}

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

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการตัวชี้วัดตามแผนฯ
  </div>
  <q-card flat bordered class="q-pa-md">
    <div class="row q-col-gutter-sm">
      <q-card bordered class="col-4">
        <q-card-section class="q-py-sm">
          <div class="text-subtitle2 text-bold">หน่วยงาน/ส่วนราชการ</div>
        </q-card-section>
        <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">
                <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>
                <div>
                  <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>
            <div class="col-12 row">
              <q-separator :vertical="!$q.screen.lt.md" />
            </div>
          </div>
        </div>
      </q-card>
      <div class="col-8">
        <div class="row q-col-gutter-sm q-mb-sm">
          <div class="col-3">
            <q-select
              dense
              outlined
              v-model="formFilter.round"
              :options="roundOp"
              label="รอบการประเมิน"
              option-label="name"
              option-value="id"
              emit-value
              map-options
            />
          </div>
          <div class="col-2">
            <q-btn
              flat
              round
              dense
              icon="add"
              color="primary"
              @click="onClickAddOrView()"
            >
              <q-tooltip>เพิ่ม</q-tooltip>
            </q-btn>
          </div>
          <div class="col-4">
            <q-input
              standout
              dense
              v-model="formFilter.keyword"
              ref="filterRef"
              outlined
              debounce="300"
              placeholder="ค้นหา"
            >
              <template v-slot:append>
                <q-icon v-if="formFilter.keyword == ''" name="search" />
                <q-icon
                  v-if="formFilter.keyword !== ''"
                  name="clear"
                  class="cursor-pointer"
                  @click="formFilter.keyword = ''"
                />
              </template>
            </q-input>
          </div>
          <div class="col-3">
            <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: 150px"
            />
          </div>
        </div>
        <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"
                  @click="onClickAddOrView(true, props.row.id)"
                >
                  <div class="table_ellipsis">
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
                <q-td>
                  <q-btn
                    flat
                    round
                    icon="delete"
                    color="red"
                    @click.stop.pervent="onClickDelete(props.rowIndex)"
                  >
                    <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: 65vh;
  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>
