<script setup lang="ts">
import { computed, ref, watch } 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 { useKpiDataStore } from "@/modules/14_KPI/store";

import Dialog from "@/modules/14_KPI/components/Tab/Dialog/01_FormIndicator.vue";
import DialogEvaluate from "@/modules/14_KPI/components/Tab/DialogEvaluate/01_Indicator.vue";
import DialogViewInfo from "@/modules/14_KPI/components/Tab/Dialog/DialogViewInfo.vue";
import DialogProgress from "@/modules/14_KPI/components/Tab/Dialog/DialogCommentProgress.vue";
import DialogProblem from "@/modules/14_KPI/components/Tab/Dialog/DialogCommentProblem.vue";

const $q = useQuasar();
const store = useKpiDataStore();
const route = useRoute();
const checkRoutePermisson = ref<boolean>(route.name == "KPIDetailPage");
const { dialogRemove, showLoader, hideLoader, messageError, success } =
  useCounterMixin();

const title = defineModel<string>("title", { required: true });
const rows = defineModel<any[]>("data", { required: true });
const numpage = defineModel<number>("page", { required: true });
const checkDetail = ref<boolean>(false);
const props = defineProps({
  fetchList: { type: Function, required: true },
});

const visibleColumns = ref<string[]>(
  store.tabOpen === 3 && store.tabMain === "3"
    ? [
        "includingName",
        "target",
        "point",
        "weight",
        "achievement",
        "evaluationResults",
      ]
    : ["includingName", "target", "point", "weight"]
);
const columns = ref<QTableProps["columns"]>([
  {
    name: "includingName",
    align: "left",
    label: "ตัวชี้วัด",
    sortable: true,
    field: "includingName",
    headerStyle: "font-size: 14px;width:200px",
    style: "font-size: 14px;",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "target",
    align: "left",
    label: "ค่าเป้าหมาย",
    sortable: true,
    field: "target",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "point",
    align: "left",
    label: "ระดับคะแนนตามเกณฑ์การประเมิน",
    sortable: true,
    field: "point",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "weight",
    align: "left",
    label: "น้ำหนัก (ร้อยละ)",
    sortable: true,
    field: "weight",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "achievement",
    align: "left",
    label: "ผลสำเร็จของงาน",
    sortable: true,
    field: "achievement",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "evaluationResults",
    align: "left",
    label: "ผลการประเมิน",
    sortable: true,
    field: "evaluationResults",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const kpiUserPlannedId = ref<string>("");
const filterKeyword = ref<string>("");
const modal = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);
const modalEvaluate = ref<boolean>(false);
const modalViewInfo = ref<boolean>(false);

const modalProgress = ref<boolean>(false);
const modalProblem = ref<boolean>(false);
const type = ref<string>("");
const idList = ref<string>("");

const isEditStep1 = computed(() => {
  return (
    (store.dataEvaluation.evaluationStatus === "NEW" &&
      store.rolePerson === "USER" &&
      store.tabMain === "1") ||
    (store.dataEvaluation.evaluationStatus === "NEW_EVALUATOR" &&
      store.rolePerson === "EVALUATOR" &&
      store.tabMain === "1")
  );
});

const isEditStep3 = computed(() => {
  return (
    (store.dataEvaluation.evaluationStatus === "EVALUATING" &&
      store.rolePerson === "USER" &&
      store.tabMain === "3") ||
    (store.dataEvaluation.evaluationStatus === "EVALUATING_EVALUATOR" &&
      store.rolePerson === "EVALUATOR" &&
      store.tabMain === "3")
  );
});

/** เพิ่มข้อมูล */
function onAdd(edit: boolean = false, id: string = "") {
  isStatusEdit.value = edit;
  kpiUserPlannedId.value = id;
  modal.value = true;
}

/**  เปิด รายละเอียด */
function onClickView(id: string) {
  checkDetail.value = true;
  kpiUserPlannedId.value = id;
  modal.value = true;
}

/** เปิด popup ประเมิน */
async function onEvaluate() {
  modalEvaluate.value = true;
}

/** ลบ ข้อมูล */
function onDelete(id: string) {
  dialogRemove($q, async () => {
    try {
      showLoader();
      const url =
        numpage.value === 1
          ? config.API.kpiAchievement("planned") + `/${id}`
          : numpage.value === 2
          ? config.API.kpiAchievement("role") + `/${id}`
          : numpage.value === 3
          ? config.API.kpiAchievement("special") + `/${id}`
          : "";
      await http.delete(url);
      await props.fetchList?.();
      await success($q, "ลบข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

/** เปิด popup รายงานความก้าวหน้า */
function openPopupProgress(id: string) {
  modalProgress.value = true;
  type.value =
    numpage.value === 1 ? "plan" : numpage.value === 2 ? "role" : "special";
  idList.value = id;
}

/** เปิด popup รายงานปัญหา */
function openPopupProblem(id: string) {
  modalProblem.value = true;

  type.value =
    numpage.value === 1 ? "plan" : numpage.value === 2 ? "role" : "special";
  idList.value = id;
}

watch(
  () => modal.value,
  () => {
    if (!modal.value) {
      props.fetchList?.();
    }
  }
);
</script>

<template>
  <q-card bordered style="border-radius: 5px" class="no-shadow q-mt-sm">
    <q-card-section class="bg-grey-2 q-py-sm">
      <div class="row items-center no-wrap">
        <div class="col">
          <span class="text-weight-medium">{{ title }}</span>
          <q-btn
            v-if="isEditStep1 && !checkRoutePermisson"
            class="q-ml-xs"
            flat
            round
            icon="mdi-plus"
            color="primary"
            size="12px"
            dense
            @click="onAdd()"
          >
            <q-tooltip>เพิ่มข้อมูล</q-tooltip>
          </q-btn>
        </div>
        <div class="col-auto">
          <q-btn
            v-if="isEditStep3 && !checkRoutePermisson"
            flat
            round
            icon="mdi-clipboard-check-outline"
            color="blue-5"
            size="12px"
            dense
            @click="onEvaluate"
          >
            <q-tooltip>ประเมิน</q-tooltip>
          </q-btn>
        </div>
      </div>
    </q-card-section>
    <q-separator />
    <q-card-section class="q-pa-sm">
      <d-table
        ref="table"
        :columns="columns"
        :rows="rows"
        :filter="filterKeyword"
        row-key="id"
        flat
        bordered
        dense
        hide-pagination
        :visible-columns="visibleColumns"
        :rows-per-page-options="[20]"
        no-data-label="ไม่มีข้อมูล"
      >
        <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-th auto-width />
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props" class="cursor-pointer">
            <q-td>
              <q-btn
                v-if="isEditStep1"
                flat
                round
                icon="mdi-eye"
                color="info"
                size="12px"
                dense
                @click="onClickView(props.row.id)"
              >
                <q-tooltip>รายละเอียด</q-tooltip>
              </q-btn></q-td
            >
            <q-td v-for="col in props.cols" :key="col.id">
              <div v-if="col.name === 'point'">
                <q-btn-group outline>
                  <q-btn
                    v-for="i in 5"
                    :class="props.row.point == i && 'active'"
                    outline
                    color="grey-6"
                    :label="i"
                  >
                    <q-tooltip>
                      <div class="text-body2">
                        <span v-html="props.row[`achievement${i}`]"></span>
                      </div>
                    </q-tooltip>
                  </q-btn>
                </q-btn-group>
              </div>
              <div v-else-if="col.name === 'achievement'">
                {{ props.row.point ? `ระดับ ${props.row.point}` : "" }}
              </div>
              <div
                v-else-if="col.name === 'includingName'"
                style="width: 200px; white-space: normal"
              >
                {{ props.row.includingName ? props.row.includingName : "-" }}
              </div>
              <div v-else-if="col.name === 'evaluationResults'">
                {{
                  parseFloat(
                    Number((props.row.point / 5) * props.row.weight).toFixed(2)
                  )
                }}
              </div>
              <div v-else>
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
            <td>
              <div
                v-if="
                  (store.dataEvaluation.evaluationStatus == 'APPROVE' &&
                    store.tabMain === '2') ||
                  store.tabMain === '3'
                "
              >
                <q-btn
                  flat
                  round
                  icon="mdi-developer-board"
                  color="blue-6"
                  size="12px"
                  dense
                  @click="openPopupProgress(props.row.id)"
                >
                  <q-tooltip>รายงานความก้าวหน้า</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="!checkRoutePermisson"
                  flat
                  round
                  icon="warning"
                  color="red-5"
                  size="12px"
                  dense
                  main="problem"
                  @click="openPopupProblem(props.row.id)"
                >
                  <q-tooltip>รายงานปัญหา</q-tooltip>
                </q-btn>
              </div>

              <div v-if="isEditStep1 && !checkRoutePermisson">
                <q-btn
                  flat
                  round
                  icon="edit"
                  color="edit"
                  size="12px"
                  dense
                  @click="onAdd(true, props.row.id)"
                >
                  <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                </q-btn>

                <q-btn
                  flat
                  round
                  icon="delete"
                  color="red"
                  size="12px"
                  dense
                  @click="onDelete(props.row.id)"
                >
                  <q-tooltip>ลบข้อมูล</q-tooltip>
                </q-btn>
              </div>
            </td>
          </q-tr>
        </template>
      </d-table>
    </q-card-section>
  </q-card>

  <Dialog
    v-model:modal="modal"
    :numpage="numpage"
    v-model:is-status-edit="isStatusEdit"
    :kpi-user-planned-id="kpiUserPlannedId"
    v-model:checkDetail="checkDetail"
  />

  <DialogEvaluate
    v-model:modal="modalEvaluate"
    :data="rows"
    :numpage="numpage"
    :fetch-list="fetchList"
  />

  <DialogViewInfo
    v-model:modal="modalViewInfo"
    :numpage="numpage"
    :is-status-edit="isStatusEdit"
    :kpi-user-planned-id="kpiUserPlannedId"
  />

  <DialogProgress
    v-model:modal="modalProgress"
    v-model:type="type"
    v-model:rows="rows"
    :id-list="idList"
  />
  <DialogProblem
    v-model:modal="modalProblem"
    v-model:type="type"
    :id-list="idList"
  />
</template>

<style scoped>
.custom-table2 {
  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;
  }
}
.q-btn-group--outline > .q-btn-item:not(:last-child):before {
  border-right: 1px solid #c4c4c4;
}
.q-btn-group--outline > .q-btn-item.active {
  color: #2196f3 !important;
  background-color: #cde6fb !important;
}
.q-btn-group--outline > .q-btn-item + .q-btn-item.active:before {
  border-left: 1px solid #2196f3 !important;
  background-color: #cde6fb;
}
.q-btn-group--outline > .q-btn-item.active:not(:last-child):before {
  border: 1px solid #2196f3;
  background-color: #cde6fb;
}
</style>
