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

import http from "@/plugins/http";
import config from "@/app.config";
import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useKpiDataStore } from "@/modules/14_KPI/store";

import type {
  FormCapacityList,
  ListCriteria,
  DataOptions,
} from "@/modules/14_KPI/interface/request/index";

import DialogListCriteria from "@/modules/14_KPI/components/Tab/Dialog/DialogListCriteria.vue";
import DialogCompetncyByRow from "@/modules/14_KPI/components/Tab/Dialog/DialogCompetncyByRow.vue";
import DialogLevel from "@/modules/14_KPI/components/Tab/Dialog/DialogLevel.vue";
import Dialog from "@/modules/14_KPI/components/Tab/Dialog/04_FormCompetency.vue";
import DialogEvaluate from "@/modules/14_KPI/components/Tab/DialogEvaluate/02_Competenct.vue";
import DialogProgress from "@/modules/14_KPI/components/Tab/Dialog/DialogCommentProgress.vue";
import DialogProblem from "@/modules/14_KPI/components/Tab/Dialog/DialogCommentProblem.vue";

const modalLevel = ref<boolean>(false);
const modalCompetncyByRow = ref<boolean>(false);
const dataCompetncyByRow = ref<any[]>([]);
const dataLevel = ref<any[]>([]);
const modalCriteria = ref<boolean>(false);
const dataListCriteria = defineModel<ListCriteria[]>("dataListCriteria", {
  required: true,
});

const sortedDataListCriteria = computed(() => {
  return dataListCriteria.value.sort((a, b) => a.level - b.level);
});

const modalEvaluate = ref<boolean>(false);
const store = useKpiDataStore();

const route = useRoute();
const checkRoutePermisson = ref<boolean>(route.name == "KPIDetailPage");
const id = ref<string>(route.params.id as string);

const idCapacity = ref<string | null>(null);

const $q = useQuasar();
const mixin = useCounterMixin();
const {
  date2Thai,
  messageError,
  showLoader,
  hideLoader,
  dialogRemove,
  success,
} = mixin;

const modal = ref<boolean>(false);

const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    align: "left",
    label: "รายการสมรรถนะ",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "level",
    align: "left",
    label: "ระดับที่คาดหวัง",
    sortable: true,
    field: "level",
    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: false,
    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: "summary",
    align: "left",
    label: "ผลการประเมิน",
    sortable: true,
    field: "summary",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const visibleColumns = ref<string[]>(
  store.tabOpen === 3 && store.tabMain === "3"
    ? ["name", "level", "point", "weight", "summary"]
    : ["name", "level", "point", "weight"]
);

const rows = ref<any[]>([]);
const lists = ref<any>([]);

const typeCompetency = ref<any>("");
function onAdd(type: string) {
  typeCompetency.value = type;
  modal.value = true;
}

/** ดึงข้อมูล สมรรถนะ */
function getData(type: any) {
  http
    .get(config.API.kpiUserCapacity + `?id=${id.value}&type=${type}`)
    .then(async (res) => {
      const data = res.data.result.data;
      rows.value[type] = data;
      lists.value = lists.value.filter((x: any) => x.type != type);
      lists.value.push({ type: type, data });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      let result = 0;
      let weight = 0;
      let total = 0;
      for (let index = 0; index < competencyType.value.length; index++) {
        const element = await competencyType.value[index];

        const dataArr = await lists.value.find(
          (x: any) => x.type == element.id
        );

        if (dataArr) {
          result += dataArr.data.reduce(
            (sum: number, e: any) => sum + (e.point / 5) * e.weight,
            0
          );
          weight += dataArr.data.reduce(
            (sum: number, e: any) => sum + e.weight,
            0
          );
          total++;
        }
      }

      if (total > 0) {
        let weightAvg = weight / total;
        let resultAvg = result / total;

        if (
          store.dataEvaluation.posTypeName == "อำนวยการ" &&
          store.dataEvaluation.posTypeName == "บริหาร"
        ) {
          store.competencyScoreVal =
            weightAvg != 0
              ? (resultAvg / weightAvg) * store.excusiveCompetencyScore
              : 0;
        } else {
          store.competencyScoreVal =
            weightAvg != 0
              ? (resultAvg / weightAvg) * store.competencyScore
              : 0;
        }

        if (
          store.isUpdate &&
          store.tabMain === "3" &&
          (store.dataEvaluation.evaluationStatus === "EVALUATOR" ||
            store.dataEvaluation.evaluationStatus === "EVALUATING_EVALUATOR")
        ) {
          http
            .put(config.API.updatePoint(store.dataEvaluation.id), {
              totalPoint2_1: store.competencyScoreVal.toFixed(2),
              summaryPoint: (
                store.indicatorScoreVal +
                store.competencyScoreVal +
                store.devScoreVal
              ).toFixed(2),
            })
            .then((res) => {});
        }
      }
    });
}

/**
 * เปิด popup แก้ไข
 * @param data ข้อมูล row
 * @param type แยกประเภท
 */
function onEdit(data: FormCapacityList, type: string) {
  idCapacity.value = data.id;
  typeCompetency.value = type;
  modal.value = true;
}

/**
 * ลบข้อมูล
 * @param id row
 * @param type แยกประเภท
 */
function onDelete(id: string, type: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.kpiUserCapacity + `/${id}`)
      .then(async () => {
        await getData(type);
        await success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** เปิด popup ประเมิน */
function onEvaluate(type: string) {
  typeCompetency.value = type;
  modalEvaluate.value = true;
}
const competencyType = ref<any[]>([]);
const modalProgress = ref<boolean>(false);
const modalProblem = ref<boolean>(false);
const type = ref<string>("");
const idList = ref<string>("");
function openPopupProgress(id: string) {
  modalProgress.value = true;
  type.value = "capacity";
  idList.value = id;
}

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 onInfo() {
  modalCriteria.value = true;
}

function onLevel(num: number, list: any) {
  dataLevel.value = list.filter((i: any) => i.level == num);
  modalLevel.value = true;
}

onMounted(() => {
  setTimeout(async () => {
    competencyType.value =
      store.dataEvaluation.posTypeName == "อำนวยการ" ||
      store.dataEvaluation.posTypeName == "บริหาร"
        ? store.competencyType.filter(
            (x: DataOptions) =>
              x.id == "HEAD" ||
              x.id == "EXECUTIVE" ||
              x.id == "INSPECTOR" ||
              x.id == "DIRECTOR"
          )
        : store.competencyType.filter(
            (x: DataOptions) => x.id == "HEAD" || x.id == "GROUP"
          );

    for (let index = 0; index < competencyType.value.length; index++) {
      const element = competencyType.value[index];
      getData(element.id);
    }
  }, 1000);
});
</script>

<template>
  <div v-for="(item, index) in competencyType" :key="index">
    <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">
          <div class="col">
            <span class="text-weight-medium">{{ item.name }}</span>
            <q-btn
              v-if="
                !checkRoutePermisson &&
                isEditStep1 &&
                item.id != 'HEAD' &&
                item.id != 'GROUP'
              "
              class="q-ml-xs"
              flat
              round
              icon="mdi-plus"
              color="primary"
              size="12px"
              dense
              @click="onAdd(item.id)"
            >
              <q-tooltip>เพิ่มข้อมูล</q-tooltip>
            </q-btn>
          </div>

          <q-space />
          <q-btn
            v-if="!checkRoutePermisson && isEditStep3"
            flat
            round
            icon="mdi-clipboard-check-outline"
            color="blue-5"
            size="12px"
            dense
            @click="onEvaluate(item.id)"
          >
            <q-tooltip>ประเมิน</q-tooltip>
          </q-btn>
        </div>
      </q-card-section>
      <q-card-section class="q-pa-sm">
        <d-table
          ref="table"
          :columns="columns"
          :rows="
            rows[item.id] && rows[item.id].length !== 0 ? rows[item.id] : []
          "
          row-key="id"
          flat
          bordered
          :paging="true"
          dense
          hide-pagination
          no-data-label="ไม่มีข้อมูล"
          :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 v-if="col.name == 'point'" class="text-weight-medium">
                  <q-btn
                    flat
                    icon="mdi-eye"
                    color="info"
                    round
                    class="q-ml-xs"
                    @click="onInfo"
                  >
                    <q-tooltip>เกณฑ์การประเมิน</q-tooltip> </q-btn
                  >{{ col.label }}</span
                >
                <span v-else 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 auto-width>
                <q-btn
                  v-if="isEditStep1"
                  flat
                  round
                  :icon="
                    item.id == 'HEAD' || item.id == 'GROUP' ? 'mdi-eye' : 'edit'
                  "
                  color="info"
                  @click.stop.pervent="onEdit(props.row, item.id)"
                >
                  <q-tooltip v-if="item.id == 'HEAD' || item.id == 'GROUP'"
                    >รายละเอียด</q-tooltip
                  >
                  <q-tooltip v-else>แก้ไข</q-tooltip>
                </q-btn>
              </q-td>
              <q-td v-for="col in props.cols" :key="col.id">
                <div v-if="col.name == 'createDate'">
                  {{ col.value ? date2Thai(col.value) : "-" }}
                </div>
                <div v-else-if="col.name == 'point'">
                  <div>
                    <q-btn-group outline>
                      <q-btn
                        v-for="(i, index) in sortedDataListCriteria"
                        :key="index"
                        :class="props.row.point == i.level && 'active'"
                        outline
                        color="grey-6"
                        :label="i.level"
                      >
                        <q-tooltip>
                          <div class="text-body2">
                            <span v-html="i.description"></span>
                          </div>
                        </q-tooltip>
                      </q-btn>
                    </q-btn-group>
                  </div>
                </div>
                <div v-else-if="col.name == 'summary'">
                  {{
                    props.row.point !== 0
                      ? (props.row.point / 5) * props.row.weight
                      : "-"
                  }}
                </div>
                <div v-else-if="col.name == 'level'">
                  <div
                    @click="onLevel(props.row.level, props.row.achievement)"
                    class="text-teal"
                  >
                    {{ props.row.level }}
                  </div>
                </div>
                <div v-else>
                  {{ col.value }}
                </div>
              </q-td>
              <q-td>
                <div
                  v-if="
                    (store.dataEvaluation.evaluationStatus == 'APPROVE' &&
                      store.tabMain === '2') ||
                    store.tabMain === '3'
                  "
                >
                  <q-btn
                    flat
                    round
                    icon="mdi-account-details"
                    color="blue-6"
                    size="12px"
                    dense
                    @click="openPopupProgress(props.row.id)"
                  >
                    <q-tooltip>บันทึกเหตุการณ์/พฤติกรรม</q-tooltip>
                  </q-btn>
                </div>

                <div v-if="isEditStep1 && !checkRoutePermisson">
                  <q-btn
                    flat
                    round
                    icon="delete"
                    color="red"
                    @click.stop.pervent="onDelete(props.row.id, item.id)"
                  >
                    <q-tooltip>ลบข้อมูล </q-tooltip>
                  </q-btn>
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
    </q-card>
  </div>

  <Dialog
    v-model:modal="modal"
    v-model:competency-type="typeCompetency"
    v-model:id="idCapacity"
    :get-data-list="getData"
  />

  <DialogEvaluate
    v-model:modal="modalEvaluate"
    v-model:data="rows[typeCompetency]"
    v-model:type="typeCompetency"
    v-model:dataListCriteria="dataListCriteria"
    :get-data="getData"
  />

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

  <DialogListCriteria
    v-model:modal="modalCriteria"
    v-model:dataListCriteria="dataListCriteria"
  />

  <DialogCompetncyByRow
    v-model:modal="modalCompetncyByRow"
    v-model:rows="dataCompetncyByRow"
  />

  <DialogLevel v-model:modal="modalLevel" v-model:rows="dataLevel" />
</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>
