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

import http from "@/plugins/http";
import config from "@/app.config";
import { useKpiDataStore } from "@/modules/08_KPI/store";
import { useCounterMixin } from "@/stores/mixin";

import type { DataOptions } from "@/modules/08_KPI/interface/index/Main";
import type { ListCapacity } from "@/modules/08_KPI/interface/request/index";

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

const dataListCapacityDetails = ref<ListCapacity[]>([]);
const route = useRoute();
const idParam = ref<string>(route.params.id as string);

const props = defineProps({
  getDataList: Function,
});

const $q = useQuasar();
const store = useKpiDataStore();
const expectedLevel = ref<number | null>(null);
const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 20,
});

const weight = ref<number>(100);
const mixin = useCounterMixin();
const {
  showLoader,
  hideLoader,
  dialogConfirm,
  messageError,
  dialogMessageNotify,
  success,
} = mixin;
const modal = defineModel<boolean>("modal", { required: true });
const idProps = defineModel<string | null>("id", { required: true });
const competencyType = defineModel<string>("competencyType", {
  required: true,
});
const search = ref<string>("");

const type = ref<string>("");

const listCheck = ref<string>();
const listTarget = ref<any>([]);
const listTargetMain = ref<any>([]);

const expectedLevelOp = ref<Object[]>(["1", "2", "3", "4", "5"]);
const formDetail = reactive<any>({
  id: "",
  type: "สมรรถนะหลัก",
  name: "สมรรถนะ 1",
  definition: "",
  criteria: "",
});
const formScore = reactive<any>({
  score1: "",
  score2: "",
  score3: "",
  score4: "",
  score5: "",
});

const fieldDetailLabels = {
  type: "ประเภทสมรรถนะ",
  name: "ชื่อสมรรถนะ",
  definition: "คำจำกัดความ",
};

const fieldLabels = {
  score1: "1",
  score2: "2",
  score3: "3",
  score4: "4",
  score5: "5",
};

const competencyTypeOp = ref<DataOptions[]>(store.competencyType);

const visibleColumns = ref<String[]>(["level", "description"]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "level",
    align: "center",
    label: "ระดับสมรรถนะ",
    sortable: true,
    field: "level",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:5px;",
  },
  {
    name: "description",
    align: "left",
    label: "พฤติกรรมที่คาดหวัง/พฤติกรรมย่อย",
    sortable: true,
    field: "description",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:15%;",
  },
]);

function clickList(index: string, data: any) {
  const dataCapacityDetails = data.capacityDetails.sort(
    (a: any, b: any) => a.level - b.level
  );
  showLoader();
  setTimeout(() => {
    hideLoader();
  }, 100);
  formScore.score1 = "";
  formScore.score2 = "";
  formScore.score3 = "";
  formScore.score4 = "";
  formScore.score5 = "";
  listCheck.value = index as string;

  formDetail.id = data.id;
  formDetail.type = data.type;
  formDetail.name = data.name;
  formDetail.definition = data.description;
  dataListCapacityDetails.value = dataCapacityDetails;
  // formScore.score1 = dataCapacityDetails[0].description;
  // formScore.score2 = dataCapacityDetails[1].description;
  // formScore.score3 = dataCapacityDetails[2].description;
  // formScore.score4 = dataCapacityDetails[3].description;
  // formScore.score5 = dataCapacityDetails[4].description;
}

/** ปิด dialog */
function closeDialog() {
  modal.value = false;
  type.value = "";
  search.value = "";
  listCheck.value = "";
  formScore.score1 = "";
  formScore.score2 = "";
  formScore.score3 = "";
  formScore.score4 = "";
  formScore.score5 = "";
  formDetail.id = "";
  formDetail.type = "";
  formDetail.name = "";
  formDetail.definition = "";
  formDetail.criteria = "";
  idProps.value = null;
  // weight.value = null;
  expectedLevel.value = null;

  dataListCapacityDetails.value = [];
}

/** เรียกใช้ class */
function getclass() {
  return "inputgreen";
}

/** save สมรรถนะ */
function onSubmit() {
  if (formDetail.id == "") {
    dialogMessageNotify($q, "กรุณาเลือกสมรรถนะ");
  } else {
    dialogConfirm($q, () => {
      const url = idProps.value
        ? config.API.kpiUserCapacity + `/${idProps.value}`
        : config.API.kpiUserCapacity;
      const body = {
        kpiUserEvaluationId: idParam.value,
        kpiCapacityId: formDetail.id,
        level: expectedLevel.value?.toString(),
        weight: weight.value,
      };
      showLoader();
      http[idProps.value ? `put` : `post`](url, body)
        .then((res) => {
          success($q, "บันทึกข้อมูลสำเร็จ");
          closeDialog();
          props.getDataList?.(competencyType.value);
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    });
  }
}

/** ดึงข้อมูล สมรรถนะ */
function getData() {
  showLoader();
  http
    .get(config.API.KpiCapacity + `?type=${type.value}&pageSize=100`)
    .then((res) => {
      const data = res.data.result.data;
      listTarget.value = data;
      listTargetMain.value = data;
      if (data.capacityDetails) {
        formScore.score1 = data.capacityDetails[0].description;
        formScore.score2 = data.capacityDetails[1].description;
        formScore.score3 = data.capacityDetails[2].description;
        formScore.score4 = data.capacityDetails[3].description;
        formScore.score5 = data.capacityDetails[4].description;
      }
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟิลเตอร์
 * @param val ค่าที่ฟิลเตอร์
 */
function filterTxt(val: any) {
  listTarget.value = listTargetMain.value.filter(
    (v: any) => v.name.indexOf(val) > -1
  );
}

/** ดึงข้อมูลตามไอดี */
function getDataById() {
  http
    .get(config.API.kpiUserCapacity + `/${idProps.value}`)
    .then((res) => {
      const list = listTargetMain.value;
      const data = res.data.result;
      const target = list.find((item: any) => item.name == data.name);

      const dataListCriteria = target.capacityDetails.sort(
        (a: any, b: any) => a.level - b.level
      );

      listCheck.value = data.name as string;
      formDetail.name = data.name;

      weight.value = data.weight;
      expectedLevel.value = data.level;

      formDetail.id = target.id;
      formDetail.type = target.type;
      formDetail.name = target.name;
      formDetail.definition = target.description;

      dataListCapacityDetails.value = dataListCriteria;
    })
    .catch((e) => {})
    .finally(() => {});
}

watch(
  () => modal.value,
  () => {
    if (modal.value) {
      type.value = competencyType.value;
      getData();
      if (idProps.value) {
        setTimeout(() => {
          getDataById();
        }, 500);
      } else {
        if (type.value == "HEAD") {
          expectedLevel.value = store.defaultCompetencyCoreLevel;
        } else if (type.value == "GROUP") {
          expectedLevel.value = store.defaultCompetencyGroupLevel;
        } else {
          expectedLevel.value = null;
        }
      }
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 85%">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          :tittle="
            competencyType == 'HEAD' || competencyType == 'GROUP'
              ? `รายละเอียดสมรรถนะ`
              : `เพิ่มสมรรถนะ`
          "
          :close="closeDialog"
        />
        <q-separator />

        <q-card-section class="q-pa-none scroll" style="max-height: 80vh">
          <div class="row">
            <div
              v-if="competencyType != 'HEAD' && competencyType != 'GROUP'"
              class="bg-grey-1 q-pa-md col-xs-12 col-md-3 row lineRight"
            >
              <div class="col-12 q-col-gutter-sm fit">
                <div class="col-12">
                  <q-select
                    v-model="type"
                    outlined
                    label="ประเภทสมรรถนะ"
                    dense
                    readonly
                    bg-color="white"
                    option-label="name"
                    option-value="id"
                    :options="competencyTypeOp"
                    emit-value
                    :class="getclass()"
                    map-options
                  />
                </div>
                <div class="col-12">
                  <q-input
                    v-model="search"
                    outlined
                    dense
                    label="ค้นหา"
                    bg-color="white"
                    :class="getclass()"
                    @update:model-value="filterTxt"
                  >
                    <template v-slot:append>
                      <q-icon v-if="search == ''" name="search" />
                      <q-icon
                        v-if="search !== ''"
                        name="clear"
                        class="cursor-pointer"
                        @click="(search = ''), (listTarget = listTargetMain)"
                      />
                    </template>
                  </q-input>
                </div>
                <div class="col-12">
                  <q-card bordered flat class="no-shadow bg-white col-12">
                    <div class="row q-px-md q-py-sm items-center bg-grey-1">
                      <div class="col-12">
                        <span>ชื่อสมรรถนะ</span>
                      </div>
                    </div>

                    <q-separator />
                    <q-card-section class="q-pa-none">
                      <div v-if="listTarget.length > 0">
                        <q-list separator dense>
                          <q-item
                            v-for="(item, index) in listTarget"
                            :key="item.name"
                            clickable
                            v-ripple
                            :active="listCheck === item.name"
                            active-class="my-menu-link"
                            @click="clickList(item.name, item)"
                          >
                            <q-item-section class="q-pa-none">
                              <div class="row items-center">
                                <div class="col-12">
                                  <span>{{ item.name }}</span>
                                </div>
                              </div>
                            </q-item-section>
                          </q-item>
                        </q-list>
                      </div>

                      <div v-else class="q-pa-md">
                        <span>ไม่พบข้อมูล</span>
                      </div>
                    </q-card-section>
                  </q-card>
                </div>
              </div>
            </div>

            <div
              :class="
                competencyType == 'HEAD' || competencyType == 'GROUP'
                  ? `col-xs-12 col-md-12 q-pa-md q-col-gutter-sm`
                  : `col-xs-12 col-md-9 q-pa-md q-col-gutter-sm`
              "
            >
              <span class="text-body2 text-weight-medium"
                >รายละเอียดสมรรถนะ</span
              >

              <div class="row q-col-gutter-sm">
                <div class="col-xs-12 col-md-5 row">
                  <q-card bordered class="fit q-pa-sm no-shadow">
                    <div
                      v-for="(field, index) in Object.keys(fieldDetailLabels)"
                      :key="index + 1"
                    >
                      <div class="row q-pa-sm q-col-gutter-lg col-12">
                        <div class="col-4 text-grey-6">
                          {{
                            fieldDetailLabels[
                              field as keyof typeof fieldDetailLabels
                            ]
                          }}
                        </div>
                        <div class="col-8">
                          <span v-if="field == 'type'">{{
                            formDetail[field]
                              ? store.convertCompetencyType(formDetail[field])
                              : "-"
                          }}</span>
                          <span
                            v-else-if="field == 'definition'"
                            v-html="formDetail[field]"
                          ></span>
                          <span v-else>{{
                            formDetail[field] ? formDetail[field] : "-"
                          }}</span>
                        </div>
                      </div>
                    </div>
                    <div class="row q-col-gutter-sm q-pa-sm">
                      <div class="col-4 text-grey-6">น้ำหนัก (ร้อยละ)</div>
                      <div class="col-8">
                        <q-input
                          readonly
                          v-model="weight"
                          dense
                          outlined
                          lazy-rules
                          :rules="[(val:string) => !!val || `${'กรุณากรอกน้ำหนัก (ร้อยละ)'}`,]"
                          hide-bottom-space
                          class="inputgreen"
                          mask="###"
                        />
                      </div>
                      <div class="col-4 text-grey-6">ระดับที่คาดหวัง</div>
                      <div class="col-8">
                        <q-select
                          :readonly="type == 'HEAD' || type == 'GROUP'"
                          v-model="expectedLevel"
                          :options="expectedLevelOp"
                          dense
                          emit-value
                          outlined
                          lazy-rules
                          :rules="[(val:string) => !!val || `${'กรุณาเลือกระดับที่คาดหวัง'}`,]"
                          hide-bottom-space
                          class="inputgreen"
                        />
                      </div>
                    </div>
                  </q-card>
                </div>
                <div class="col-xs-12 col-md-7">
                  <d-table
                    flat
                    bordered
                    dense
                    :paging="true"
                    row-key="level"
                    virtual-scroll
                    :rows="dataListCapacityDetails"
                    hide-pagination
                    :columns="columns"
                    :visible-columns="visibleColumns"
                    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"
                          class="bg-grey-2"
                        >
                          <span class="text-weight-bold">{{ 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.name"
                          :props="props"
                        >
                          <div v-if="(col.name = 'description')">
                            <span v-html="col.value"></span>
                          </div>
                          <div v-else>
                            {{ col.value }}
                          </div>
                        </q-td>
                      </q-tr>
                    </template>
                    <template #item="props">
                      <div class="q-pa-xs col-xs-12 col-sm-6 col-md-4 col-lg-3">
                        <q-card bordered flat>
                          <q-list>
                            <q-item
                              v-for="col in props.cols.filter((col:any) => col.name !== 'desc')"
                              :key="col.name"
                            >
                              <q-item-section>
                                <q-item-label caption>{{
                                  col.label
                                }}</q-item-label>

                                <q-item-label v-if="(col.name = 'description')">
                                  <span v-html="col.value"></span
                                ></q-item-label>

                                <q-item-label v-else>{{
                                  col.value ?? "-"
                                }}</q-item-label>
                              </q-item-section>
                            </q-item>
                          </q-list>
                        </q-card>
                      </div>
                    </template>
                    <template v-slot:no-data="{ icon, message }">
                      <div
                        class="q-pa-md text-weight-bold full-width text-center"
                      >
                        <span style="font-size: 16px">ไม่พบข้อมูลสมรรถนะ</span>
                      </div>
                    </template>
                  </d-table>
                </div>
              </div>
            </div>
          </div>
        </q-card-section>
        <q-separator
          v-if="competencyType !== 'HEAD' && competencyType !== 'GROUP'"
        />

        <q-card-actions
          v-if="competencyType !== 'HEAD' && competencyType !== 'GROUP'"
          align="right"
          class="bg-white text-teal"
        >
          <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>
.my-menu-link {
  background: #ebf9f7 !important;
  color: #1bb19ab8 !important;
}
.no-shadow {
  box-shadow: none !important;
}
.lineRight {
  border-right: 1px solid #ededed !important;
}
.lineTop {
  border-top: 1px solid #ededed !important;
}
.card-box {
  border: 1px solid #ededed !important;
  border-radius: 8px;
}
.custom-table2 {
  .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>
