<script setup lang="ts">
import { ref, watch, reactive } from "vue";
import DialogHeader from "@/components/DialogHeader.vue";
import { useCounterMixin } from "@/stores/mixin";

import http from "@/plugins/http";
import config from "@/app.config";

import type {
  FormComment,
  FormCommentByRole,
} from "@/modules/14_KPI/interface/request/Index";
import { useRoute } from "vue-router";
import { useQuasar } from "quasar";

import { useKpiDataStore } from "@/modules/14_KPI/store";

const store = useKpiDataStore();
const $q = useQuasar();
const route = useRoute();
const id = ref<string>(route.params.id as string);
const mixin = useCounterMixin();
const {
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  dialogMessageNotify,
  success,
} = mixin;

const modal = defineModel<boolean>("modal", { required: true });
const type = defineModel<string>("type", { required: true });
const idList = defineModel<string>("idList", { required: true });
const modalAdd = ref<boolean>(false);
const sendId = ref<string>("");

const splitterModel = ref<number>(40);
const listTarget = ref<any>([]);
const listCheck = ref<string>("");

const reasonEvaluator = ref<string>(""); //ผู้ประเมิน
const reasonCommander = ref<string>(""); //ผู้บังคับบัญชาเหนือขึ้นไป
const reasonCommanderHigh = ref<string>(""); //ผู้บังคับบัญชาเหนือขึ้นไปอีกขั้นหนึ่ง

const reasonEvaluatorRef = ref<any>();
const reasonCommanderRef = ref<any>();
const reasonCommanderHighRef = ref<any>();
const sendType = ref<string>("");
const formDataAdd = reactive<FormComment>({
  topic: "",
  reason: "",
});

const formDataView = reactive<FormCommentByRole>({
  id: "",
  topic: "",
  reason: "",
  reasonEvaluator: "",
  reasonCommander: "",
  reasonCommanderHigh: "",
});

let count = ref<number>(0);
function clickList(index: string, data: any) {
  listCheck.value = index as string;

  formDataView.id = data.id;
  formDataView.topic = data.topic;
  formDataView.reason = data.reason;

  formDataView.reasonEvaluator = data.reasonEvaluator;
  formDataView.reasonCommander = data.reasonCommander;
  formDataView.reasonCommanderHigh = data.reasonCommanderHigh;

  reasonEvaluator.value = data.reasonEvaluator ?? "";
  reasonCommander.value = data.reasonCommander ?? "";
  reasonCommanderHigh.value = data.reasonCommanderHigh ?? "";

  if (count.value >= 1) {
    reasonEvaluatorRef.value.reset();
    reasonCommanderRef.value.reset();
    reasonCommanderHighRef.value.reset();
  }
  count.value++;
  showLoader();
  setTimeout(() => {
    hideLoader();
  }, 100);
}

/** แก้ไขแบบร่างรายงาน */
function onEdit(data: any) {
  modalAdd.value = true;
  sendId.value = data.id;
  formDataAdd.topic = data.topic;
  formDataAdd.reason = data.reason;
}

function onSubmitAdd() {
  dialogConfirm($q, () => {
    showLoader();
    http
      .put(
        config.API.kpiCommentP(
          "problem",
          type.value + sendType.value,
          store.rolePerson.toLowerCase(),
          sendId.value ? sendId.value : idList.value
        ),
        {
          reason: formDataAdd.reason,
          topic: formDataAdd.topic,
        }
      )
      .then(async (res) => {
        success($q, "บันทึกข้อมูลสำเร็จ");
        if (sendId.value) {
          const id = res.data.result;
          await closeAdd();
          const data = listTarget.value.find((item: any) => item.id == id);
          clickList(id, data);
        } else {
          sendId.value = res.data.result;
          getList();
        }
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function onSubmit() {}

function close() {
  count.value = 0;
  modal.value = false;

  reasonEvaluator.value = "";
  reasonCommander.value = "";
  reasonCommanderHigh.value = "";

  listTarget.value = [];
  listCheck.value = "";
}

function closeAdd() {
  modalAdd.value = false;
  formDataAdd.topic = "";
  formDataAdd.reason = "";
  sendId.value = "";
  getList();
}

function getList() {
  showLoader();
  http
    .get(
      config.API.kpiCommentP(
        "problem",
        type.value,
        store.rolePerson.toLowerCase(),
        idList.value
      )
    )
    .then((res) => {
      const data = res.data.result;
      listTarget.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function onSubmitComment(role: string) {
  dialogConfirm($q, () => {
    const body = {
      reason:
        role == "evaluator"
          ? reasonEvaluator.value
          : role == "commander"
          ? reasonCommander.value
          : role == "commanderhigh"
          ? reasonCommanderHigh.value
          : null,
    };
    showLoader();
    http
      .put(
        config.API.kpiCommentP(
          "problem",
          type.value,
          store.rolePerson.toLowerCase(),
          formDataView.id
        ),
        body
      )
      .then((res) => {
        success($q, "บันทึกข้อมูลสำเร็จ");

        getList();
        setTimeout(() => {
          if (listCheck.value) {
            const idCheck = listCheck.value;
            const data = listTarget.value.find(
              (item: any) => item.id == idCheck
            );
            clickList(idCheck, data);
          }
        }, 200);
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function statusText(val: string) {
  switch (val) {
    case "DRAFT":
      return "แบบร่าง";
    case "EVALUATOR":
      return "ผู้ประเมิน";
    case "COMMANDER":
      return "ผู้บังคับบัญชาเหนือขึ้นไป";
    case "COMMANDERHIGH":
      return "ผู้บังคับบัญชาเหนือขึ้นไปอีกขั้นหนึ่ง";
    case "DONE":
      return "เสร็จสิ้น";

    default:
      return "";
  }
}

function onNoti() {
  listCheck.value = "";
  count.value = 0;
}
watch(
  () => modal.value,
  () => {
    if (modal.value == true) {
      getList();
    }
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 70vw">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader tittle="รายงานปัญหา" :close="close" />
        <q-separator />
        <q-card-section class="q-pa-none">
          <q-splitter
            v-model="splitterModel"
            disable
            separator-class="bg-gray"
            separator-style="width: 1px"
          >
            <template v-slot:before>
              <div class="q-pa-sm">
                <q-btn
                  v-if="store.rolePerson === 'USER'"
                  icon="add"
                  color="teal"
                  flat
                  round
                  @click="
                    () => {
                      modalAdd = true;
                    }
                  "
                >
                  <q-tooltip>เพิ่มหัวข้อรายงานปัญหา</q-tooltip>
                </q-btn>

                <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.id"
                          clickable
                          v-ripple
                          :active="listCheck === item.id"
                          active-class="my-menu-link"
                          @click="
                            item.status == 'DRAFT'
                              ? onNoti()
                              : clickList(item.id, item)
                          "
                        >
                          <q-item-section class="q-pa-none">
                            <div class="row items-center">
                              <div class="col-12 row justify-between">
                                <span>{{ item.topic }}</span>
                                <q-badge
                                  v-if="item.status == 'DRAFT'"
                                  outline
                                  color="grey"
                                  label="แบบร่าง"
                                  @click="onEdit(item)"
                                />
                              </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>
            </template>

            <template v-slot:after>
              <div
                v-if="!listCheck"
                class="row col-12 items-center"
                style="height: 30vh"
              >
                <q-banner class="q-pa-lg col-12 text-center">
                  <q-icon
                    name="mdi-hand-pointing-left"
                    size="lg"
                    color="primary"
                  />
                  <p class="text-grey-9 q-pt-sm">กรุณาเลือกหัวข้อรายงานปัญหา</p>
                </q-banner>
              </div>
              <div v-else>
                <div class="row q-pa-md q-col-gutter-sm">
                  <div class="row col-12 text-weight-medium">
                    <div class="col-4 text-grey-6">หัวข้อปัญหา</div>
                    <div class="col-8">{{ formDataView.topic }}</div>
                  </div>
                  <div class="row col-12 text-weight-medium">
                    <div class="col-4 text-grey-6">รายละเอียดปัญหา</div>
                    <div class="col-8">{{ formDataView.reason }}</div>
                  </div>
                  <div class="col-12">
                    <q-separator />
                  </div>

                  <!-- ความคิดเห็นของผู้ประเมิน -->
                  <q-form
                    v-if="store.dataEvaluation.evaluatorId"
                    ref="reasonEvaluatorRef"
                    greedy
                    @submit.prevent
                    @validation-success="onSubmitComment('evaluator')"
                    class="full-width q-mt-sm"
                  >
                    <div class="row col-12 q-col-gutter-sm">
                      <div class="col-12">
                        <span class="text-weight-medium text-grey-6"
                          >ความคิดเห็นของผู้ประเมิน</span
                        >
                      </div>
                      <div class="col-12">
                        <q-input
                          outlined
                          dense
                          :readonly="
                            formDataView.reasonEvaluator !== null ||
                            store.rolePerson !== 'EVALUATOR'
                          "
                          label="ความคิดเห็นของผู้ประเมิน"
                          v-model="reasonEvaluator"
                          type="textarea"
                          class="inputgreen"
                          lazy-rules
                          hide-bottom-space
                          :rules="[(val:string) => !!val || `${'กรุณากรอกความคิดเห็นของผู้ประเมิน'}`,]"
                        ></q-input>
                      </div>

                      <div
                        v-if="
                          formDataView.reasonEvaluator == null &&
                          store.rolePerson == 'EVALUATOR'
                        "
                        class="col-12"
                        align="right"
                      >
                        <q-btn
                          label="บันทึกความคิดเห็น"
                          color="secondary"
                          type="submit"
                          ><q-tooltip>บันทึกความคิดเห็น</q-tooltip></q-btn
                        >
                      </div>
                    </div>
                  </q-form>

                  <!-- ความคิดเห็นของผู้บังคับบัญชาเหนือขึ้นไป -->
                  <q-form
                    v-if="store.dataEvaluation.commanderId"
                    class="full-width q-mt-sm"
                    ref="reasonCommanderRef"
                    greedy
                    @submit.prevent
                    @validation-success="onSubmitComment('commander')"
                  >
                    <div class="row col-12 q-col-gutter-sm">
                      <div class="col-12">
                        <span class="text-weight-medium text-grey-6"
                          >ความคิดเห็นของผู้บังคับบัญชาเหนือขึ้นไป</span
                        >
                      </div>
                      <div class="col-12">
                        <q-input
                          outlined
                          dense
                          label="ความคิดเห็นของผู้บังคับบัญชาเหนือขึ้นไป"
                          v-model="reasonCommander"
                          type="textarea"
                          class="inputgreen"
                          lazy-rules
                          :readonly="
                            formDataView.reasonCommander !== null ||
                            store.rolePerson !== 'COMMANDER'
                          "
                          hide-bottom-space
                          :rules="[(val:string) => !!val || `${'กรุณากรอกความคิดเห็นของผู้บังคับบัญชาเหนือขึ้นไป'}`,]"
                        ></q-input>
                      </div>

                      <div
                        v-if="
                          formDataView.reasonCommander == null &&
                          store.rolePerson == 'COMMANDER'
                        "
                        class="col-12"
                        align="right"
                      >
                        <q-btn
                          label="บันทึกความคิดเห็น"
                          color="secondary"
                          type="submit"
                          ><q-tooltip>บันทึกความคิดเห็น</q-tooltip></q-btn
                        >
                      </div>
                    </div>
                  </q-form>

                  <q-form
                    v-if="store.dataEvaluation.commanderHighId"
                    class="full-width q-mt-sm"
                    ref="reasonCommanderHighRef"
                    greedy
                    @submit.prevent
                    @validation-success="onSubmitComment('commanderhigh')"
                  >
                    <div class="row col-12 q-col-gutter-sm">
                      <div class="col-12">
                        <span class="text-weight-medium text-grey-6"
                          >ความคิดเห็นของผู้บังคับบัญชาเหนือขึ้นไปอีกขั้นหนึ่ง</span
                        >
                      </div>
                      <div class="col-12">
                        <q-input
                          outlined
                          dense
                          label="ความคิดเห็นของผู้บังคับบัญชาเหนือขึ้นไปอีกขั้นหนึ่ง"
                          v-model="reasonCommanderHigh"
                          type="textarea"
                          class="inputgreen"
                          lazy-rules
                          :readonly="
                            formDataView.reasonCommanderHigh !== null ||
                            store.rolePerson !== 'COMMANDERHIGH'
                          "
                          hide-bottom-space
                          :rules="[(val:string) => !!val || `${'กรุณากรอกความคิดเห็นของผู้บังคับบัญชาเหนือขึ้นไปอีกขั้นหนึ่ง'}`,]"
                        ></q-input>
                      </div>

                      <div
                        v-if="
                          formDataView.reasonCommanderHigh == null &&
                          store.rolePerson == 'COMMANDERHIGH'
                        "
                        class="col-12"
                        align="right"
                      >
                        <q-btn
                          label="บันทึกความคิดเห็น"
                          color="secondary"
                          type="submit"
                          ><q-tooltip>บันทึกความคิดเห็น</q-tooltip></q-btn
                        >
                      </div>
                    </div>
                  </q-form>
                </div>
              </div>
            </template>
          </q-splitter>
        </q-card-section>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="modalAdd" persistent>
    <q-card style="min-width: 30vw">
      <q-form greedy @submit.prevent @validation-success="onSubmitAdd">
        <DialogHeader
          :tittle="`${sendId ? 'แก้ไข' : 'เพิ่ม'}หัวข้อรายงานปัญหา`"
          :close="closeAdd"
        />
        <q-separator />

        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <q-input
                v-model="formDataAdd.topic"
                outlined
                class="inputgreen"
                label="หัวข้อรายงานปัญหา"
                dense
                lazy-rules
                hide-bottom-space
                :rules="[(val:string) => !!val || `${'กรุณากรอกหัวข้อรายงานปัญหา'}`,]"
              />
            </div>
            <div class="col-12">
              <q-input
                v-model="formDataAdd.reason"
                outlined
                class="inputgreen"
                label="รายละเอียดปัญหา"
                dense
                lazy-rules
                hide-bottom-space
                :rules="[(val:string) => !!val || `${'กรุณากรอกรายละเอียดปัญหา'}`,]"
                type="textarea"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn
            label="บันทึกแบบร่าง"
            color="info"
            type="submit"
            @click="
              () => {
                sendType = '';
              }
            "
            ><q-tooltip>บันทึกแบบร่าง</q-tooltip></q-btn
          >
          <q-btn
            v-if="sendId !== ''"
            label="ส่งไปยังผู้ประเมิน"
            color="secondary"
            type="submit"
            @click="
              () => {
                sendType = 'send';
              }
            "
            ><q-tooltip>ส่งไปยังผู้ประเมิน</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
<style scoped>
.border-right {
  border-right: 1px solid #000;
}
.my-menu-link {
  background: #ebf9f7 !important;
  color: #1bb19ab8 !important;
}
</style>
