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

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

import type { FormComment } from "@/modules/08_KPI/interface/request/index";
import type { ResEvaluator } from "@/modules/08_KPI/interface/response/index";

import DialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar();
const route = useRoute();
const { showLoader, hideLoader, messageError, dialogConfirm, success,onSearchDataTable } =
  useCounterMixin();

const evaluatorId = ref<string>(route.params.id.toString());
const isReadonly = <boolean>(route.name === "KPIEditEvaluator" ? true : false);

const props = defineProps({
  type: {
    type: String,
    require: true,
  },
});

/** Table*/
const visibleColumns = ref<string[]>(["topic", "reason"]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "topic",
    align: "left",
    label: "หัวข้อ",
    sortable: true,
    field: "topic",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px;",
  },
  {
    name: "reason",
    align: "left",
    label: "ความคิดเห็น",
    sortable: true,
    field: "reason",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px;",
  },
]);
const rows = ref<ResEvaluator[]>([]);
const rowsData = ref<ResEvaluator[]>([]);
const filterKeyword = ref<string>("");

const modal = ref<boolean>(false);
const formComment = reactive<FormComment>({
  topic: "",
  reason: "",
});
const optionTopicMain = ref<string[]>([
  "เห็นชอบตัวชี้วัดผลสัมฤทธิ์ของงาน รายการสมรรถนะ และน้ำหนักคะแนนของผู้ใต้บังคับบัญชา",
  "ส่งกลับให้แก้ไข",
  "บันทึกคำปรึกษาแนะนำ",
  "บันทึกความเห็น",
  "เห็นด้วยกับผลการประเมิน",
  "บันทึกข้อเสนอแนะการพัฒนา",
]);
const optionTopic = ref<string[]>(optionTopicMain.value);

function fetchList() {
  showLoader();
  http
    .get(config.API.kpiEvaluation + `/${props.type}/${evaluatorId.value}`)
    .then((res) => {
      rows.value = res.data.result;
      rowsData.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function openDialog() {
  modal.value = true;
}

function closeDialog() {
  modal.value = false;
  formComment.topic = "";
  formComment.reason = "";
}

function createValue(val: string, done: Function) {
  if (val.length > 0) {
    if (!optionTopic.value.includes(val)) {
      optionTopic.value.push(val);
    }
    done(val);
  }
}

function filterFn(val: string, update: Function) {
  update(() => {
    optionTopic.value = optionTopicMain.value.filter(
      (v: string) => v.indexOf(val) > -1
    );
  });
}

function onSubmit() {
  dialogConfirm($q, () => {
    showLoader();
    http
      .put(
        config.API.kpiEvaluation + `/${props.type}/${evaluatorId.value}`,
        formComment
      )
      .then(() => {
        fetchList();
        closeDialog();
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

function onSearch() {
  rows.value = onSearchDataTable(
    filterKeyword.value,
    rowsData.value,
    columns.value ? columns.value : []
  );
}

onMounted(() => {
  fetchList();
});
</script>
<template>
  <div class="q-pa-md">
    <q-toolbar style="padding: 0px">
      <q-btn
        v-if="isReadonly"
        flat
        round
        dense
        icon="add"
        color="blue-4"
        @click="openDialog"
      >
        <q-tooltip>เสนอความคิดเห็น</q-tooltip>
      </q-btn>
      <q-space />
      <div class="row q-col-gutter-sm">
        <q-input
          outlined
          dense
          debounce="300"
          v-model="filterKeyword"
          placeholder="ค้นหา"
          @keydown.enter.prevent="onSearch"
        >
          <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>
    </q-toolbar>
    <div class="col-12">
      <q-table
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="id"
        flat
        bordered
        dense
        class="custom-table"
        :visible-columns="visibleColumns"
        :rows-per-page-options="[10, 20, 50, 100]"
        no-data-label="ไม่มีข้อมูล"
        v-model:pagination="pagination"
      >
        <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-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props" class="cursor-pointer">
            <q-td v-for="col in props.cols" :key="col.id" style="width: 50%">
              {{ col.value ? col.value : "-" }}
            </q-td>
          </q-tr>
        </template>
        <template v-slot:pagination="scope">
          ทั้งหมด {{ rows.length }} รายการ
          <q-pagination
            v-model="pagination.page"
            active-color="primary"
            color="dark"
            :max="scope.pagesNumber"
            :max-pages="5"
            size="sm"
            boundary-links
            direction-links
          ></q-pagination>
        </template>
      </q-table>
    </div>
  </div>

  <q-dialog v-model="modal" persistent>
    <q-card style="width: 700px; max-width: 80vw">
      <DialogHeader :tittle="'เสนอความคิดเห็น'" :close="closeDialog" />
      <q-separator />
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <q-card-section>
          <div class="row q-col-gutter-md">
            <div class="col-12">
              <q-select
                class="inputgreen"
                dense
                outlined
                v-model="formComment.topic"
                use-input
                input-debounce="0"
                @new-value="createValue"
                :options="optionTopic"
                @filter="filterFn"
                hide-bottom-space
                lazy-rules
                label="หัวข้อ"
                :rules="[
                  (val:string) =>
                    !!val || `${'กรุณาเลือกหัวข้อ'}`,
                ]"
              />
            </div>
            <div class="col-12">
              <q-input
                v-model="formComment.reason"
                class="inputgreen"
                dense
                outlined
                type="textarea"
                label="ควาดคิดเห็น"
                hide-bottom-space
                lazy-rules
                :rules="[
                  (val:string) =>
                    !!val || `${'กรุณากรอกความคิดเห็น'}`,
                ]"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.custom-table {
  max-height: 64vh;

  .q-table tr:nth-child(odd) td {
    background: white;
  }

  .q-table tr:nth-child(even) td {
    background: #f8f8f8;
  }

  .q-table thead tr {
    background: #ecebeb;
  }

  .q-table thead tr th {
    position: sticky;
  }

  .q-table td:nth-of-type(2) {
    z-index: 3 !important;
  }

  .q-table th:nth-of-type(2),
  .q-table td:nth-of-type(2) {
    position: sticky;
    left: 0;
    z-index: 1;
  }

  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }

  .q-table thead tr:first-child th {
    top: 0;
  }
}
</style>
