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

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

import DialogDevelop from "@/modules/08_KPI/components/Tab/Dialog/DialogDevelop.vue";
import DialogEvalutionDevelop from "@/modules/08_KPI/components/Tab/DialogEvaluate/03_DialogEvalutionDevelop.vue";
import DialogProgress from "@/modules/08_KPI/components/Tab/Dialog/DialogCommentProgress.vue";
import DialogProblem from "@/modules/08_KPI/components/Tab/Dialog/DialogCommentProblem.vue";

const store = useKpiDataStore();
const route = useRoute();
const evaluationId = ref<string>(route.params.id.toString());
const modalEvaluate = ref<boolean>(false);

const rows = ref<any[]>([]);
const modalDevelop = ref<boolean>(false);
const idEditDevelop = ref<string>("");

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

const isUpdate = defineModel("isUpdate", {
  type: Boolean,
  default: 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")
  );
});

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")
  );
});
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "center",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    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: "develop",
    align: "left",
    label: "วิธีการพัฒนา",
    sortable: true,
    field: "develop",
    headerStyle: "font-size: 14px",
    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: "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: "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"
    ? ["no", "name", "develop", "target", "achievement", "summary"]
    : ["no", "name", "develop", "target"]
);

function onAdd() {
  modalDevelop.value = true;
}

/**
 * เปิด dialog แก้ไข
 * @param id id
 */
function onEdit(id: string) {
  modalDevelop.value = true;
  idEditDevelop.value = id;
}

/** ดึงข้อมูลพัฒนา */
function getDevelop() {
  http
    .get(config.API.kpiAchievementDevelop + `?id=${evaluationId.value}`)
    .then((res) => {
      const data = res.data.result;
      rows.value = data;

      const totalSummary = rows.value.reduce(
        (sum: number, e: any) => sum + e.summary,
        0
      );

      store.devScoreVal =
        data.length !== 0 ? totalSummary / rows.value.length : 0;
    });
}

function onEvaluate() {
  modalEvaluate.value = true;
}

/** ลบข้อมูลตาม id
 *  @param id id row
 */
function onDelete(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.kpiAchievementDevelop + `/${id}`)
      .then((res) => {
        success($q, "ลบข้อมูลสำเร็จ");
        getDevelop();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function openPopupProgress(id: string) {
  modalProgress.value = true;
  type.value = "development";
  idList.value = id;
}

function openPopupProblem(id: string) {
  modalProblem.value = true;

  type.value = "development";
  idList.value = id;
}

onMounted(() => {
  getDevelop();
});
</script>

<template>
  <q-card bordered style="border-radius: 5px" class="no-shadow">
    <q-card-section class="bg-grey-2 q-py-sm">
      <div class="row items-center">
        <div class="col">
          <span class="text-weight-medium">การพัฒนาตนเอง</span>
          <q-btn
            v-if="isEditStep1"
            class="q-ml-xs"
            flat
            round
            icon="mdi-plus"
            color="primary"
            dense
            @click="onAdd()"
          >
            <q-tooltip>เพิ่มข้อมูล</q-tooltip>
          </q-btn>
        </div>

        <q-space />
        <q-btn
          v-if="isEditStep3 && store.rolePerson !== 'USER'"
          flat
          round
          icon="mdi-clipboard-check-outline"
          color="blue-5"
          size="12px"
          dense
          @click="onEvaluate()"
        >
          <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"
        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 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.id" class="vertical-top">
              <div v-if="col.name == 'createDate'">
                {{ col.value ? date2Thai(col.value) : "-" }}
              </div>
              <div v-else-if="col.name == 'no'" class="text-center">
                {{ props.rowIndex + 1 }}
              </div>
              <div v-else-if="col.name == 'develop'">
                <div class="column">
                  <q-checkbox
                    size="xs"
                    :model-value="props.row.isDevelopment70"
                    label="70 การลงมือปฏิบัติ (โดยผู้บังคับบัญชามอบหมาย)"
                  />
                  <q-checkbox
                    size="xs"
                    :model-value="props.row.isDevelopment20"
                    label="20 การเรียนรู้จากผู้อื่น (Coach/Mentor/Consulting)"
                  />
                  <q-checkbox
                    size="xs"
                    :model-value="props.row.isDevelopment10"
                    label="10 การฝึกอบรมอื่นๆ"
                  />
                </div>
              </div>
              <div v-else-if="col.name == 'achievement'">
                <q-btn-group outline>
                  <q-btn
                    outline
                    color="grey-6"
                    label="0"
                    :class="props.row.summary == 0 && 'active'"
                    ><q-tooltip>{{ props.row.achievement0 }}</q-tooltip></q-btn
                  >
                  <q-btn
                    outline
                    color="grey-6"
                    label="5"
                    :class="props.row.summary == 5 && 'active'"
                    ><q-tooltip>{{ props.row.achievement5 }}</q-tooltip></q-btn
                  >
                  <q-btn
                    outline
                    color="grey-6"
                    label="10"
                    :class="props.row.summary == 10 && 'active'"
                    ><q-tooltip>{{ props.row.achievement10 }}</q-tooltip></q-btn
                  >
                </q-btn-group>
              </div>
              <div v-else-if="col.name === 'summary'">
                {{ props.row.summary ? props.row.summary : 0 }}
              </div>
              <div v-else>
                {{ col.value ? 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>{{store.tabMain == '3' ? `บันทึกเหตุการณ์/พฤติกรรม/เหตุผล` :'บันทึกเหตุการณ์/พฤติกรรม'}}</q-tooltip>
                </q-btn>
              </div>

              <div v-if="isEditStep1">
                <q-btn
                  flat
                  round
                  icon="edit"
                  color="edit"
                  @click.stop.pervent="onEdit(props.row.id)"
                >
                  <q-tooltip>แก้ไข </q-tooltip>
                </q-btn>
                <q-btn
                  flat
                  round
                  icon="delete"
                  color="red"
                  @click.stop.pervent="onDelete(props.row.id)"
                >
                  <q-tooltip>ลบข้อมูล </q-tooltip>
                </q-btn>
              </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 == 'createDate'">
                      {{ col.value ? date2Thai(col.value) : "-" }}
                    </q-item-label>
                    <q-item-label v-else-if="col.name == 'develop'">
                      <div class="column">
                        <q-checkbox
                          size="xs"
                          :model-value="props.row.isDevelopment70"
                          label="70 การลงมือปฏิบัติ (โดยผู้บังคับบัญชามอบหมาย)"
                        />
                        <q-checkbox
                          size="xs"
                          :model-value="props.row.isDevelopment20"
                          label="20 การเรียนรู้จากผู้อื่น (Coach/Mentor/Consulting)"
                        />
                        <q-checkbox
                          size="xs"
                          :model-value="props.row.isDevelopment10"
                          label="10 การฝึกอบรมอื่นๆ"
                        />
                      </div>
                    </q-item-label>
                    <q-item-label v-else-if="col.name == 'achievement'">
                      <q-btn-group outline>
                        <q-btn
                          outline
                          color="grey-6"
                          label="0"
                          :class="props.row.summary == 0 && 'active'"
                          ><q-tooltip>{{
                            props.row.achievement0
                          }}</q-tooltip></q-btn
                        >
                        <q-btn
                          outline
                          color="grey-6"
                          label="5"
                          :class="props.row.summary == 5 && 'active'"
                          ><q-tooltip>{{
                            props.row.achievement5
                          }}</q-tooltip></q-btn
                        >
                        <q-btn
                          outline
                          color="grey-6"
                          label="10"
                          :class="props.row.summary == 10 && 'active'"
                          ><q-tooltip>{{
                            props.row.achievement10
                          }}</q-tooltip></q-btn
                        >
                      </q-btn-group>
                    </q-item-label>
                    <q-item-label v-else-if="col.name == 'summary'">
                      {{ props.row.summary ? props.row.summary : 0 }}
                    </q-item-label>
                    <q-item-label v-else>
                      {{ col.value ? col.value : "-" }}
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
              <q-separator />
              <q-card-actions
                align="around"
                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
                  flat
                  round
                  icon="warning"
                  color="red-5"
                  size="12px"
                  dense
                  main="problem"
                  @click="openPopupProblem(props.row.id)"
                >
                  <q-tooltip>รายงานปัญหา</q-tooltip>
                </q-btn>
              </q-card-actions>

              <q-card-actions align="around" v-if="isEditStep1">
                <q-btn
                  flat
                  round
                  icon="edit"
                  color="edit"
                  @click.stop.pervent="onEdit(props.row.id)"
                >
                  <q-tooltip>แก้ไข </q-tooltip>
                </q-btn>
                <q-btn
                  flat
                  round
                  icon="delete"
                  color="red"
                  @click.stop.pervent="onDelete(props.row.id)"
                >
                  <q-tooltip>ลบข้อมูล </q-tooltip>
                </q-btn>
              </q-card-actions>
            </q-card>
          </div>
        </template>
      </d-table>
    </q-card-section>
  </q-card>

  <DialogDevelop
    v-model:modal="modalDevelop"
    v-model:id="idEditDevelop"
    :get-all="getDevelop"
  />

  <DialogEvalutionDevelop
    v-model:modal="modalEvaluate"
    v-model:data="rows"
    :get-all="getDevelop"
  />

  <DialogProgress
    v-model:modal="modalProgress"
    v-model:type="type"
    :idList="idList"
  />
  <DialogProblem
    v-model:modal="modalProblem"
    v-model:type="type"
    :idList="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>
