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

import { useRouter, useRoute } from "vue-router";
import { useRequestEditStore } from "@/modules/04_registryPerson/stores/RequestEdit";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import type { DataOption } from "@/modules/04_registryPerson/interface/index/Main";
import type { DataRequest } from "@/modules/04_registryPerson/interface/response/Main";

import Workflow from "@/components/Workflow/Main.vue";

const $q = useQuasar();
const router = useRouter();
const route = useRoute();
const store = useRequestEditStore();
const {
  dialogConfirm,
  date2Thai,
  showLoader,
  hideLoader,
  messageError,
  success,
} = useCounterMixin();

const requestId = ref<string>(route.params.id.toString());
const dataRequest = ref<any>({
  fullname: "",
  createdAt: null,
  topic: "",
  detail: "",
});

//ฟอร์มสถานะคำร้อง
const formData = reactive({
  status: "", //สถานะ
  remark: "", //หมายเหตุ
});

const isReadOnly = ref<boolean>(false); //อ่ายได้อย่างเดียว
const workflowRef = ref<any>(null);
//ข้อมูลรายการสถานะ
const statusOptionMain = ref<DataOption[]>(
  store.optionStatus.filter((e) => e.id !== "")
);
const statusOption = ref<DataOption[]>(statusOptionMain.value); //ตัวเลือกรายการสถานะ

/** function fetch ข้อมูลคำร้องแก้ไข*/
async function fetchDataRequest() {
  showLoader();
  await http
    .get(config.API.requestEdit + `${requestId.value}`)
    .then((res) => {
      const data = res.data.result;
      dataRequest.value = {
        fullname: data.fullname,
        createdAt: data.createdAt,
        topic: data.topic,
        detail: data.detail,
      };

      formData.status = data.status;
      formData.remark = data.remark;
      if (data.status !== "PENDING") {
        isReadOnly.value = true;
      } else {
        isReadOnly.value = false;
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function บันทึกรายการคำร้อง*/
function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    await http
      .patch(config.API.requestEdit + `${requestId.value}`, {
        status: formData.status,
        remark: formData.remark,
      })
      .then(async () => {
        await fetchDataRequest();
        await success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * function ค้นหาคำใน select  สถานะคำร้อง
 * @param val คำค้น
 * @param update Function
 */
function filterOption(val: string, update: Function) {
  update(() => {
    statusOption.value = statusOptionMain.value.filter(
      (v: DataOption) => v.name.indexOf(val) > -1
    );
  });
}

/**
 * class inpui
 * @param val ค่าสถานะ
 */
function classInput(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

onMounted(async () => {
  await fetchDataRequest();
});
</script>

<template>
  <div class="row items-center">
    <div class="toptitle text-dark row items-center q-py-xs">
      <q-btn
        icon="mdi-arrow-left"
        unelevated
        round
        dense
        flat
        color="primary"
        class="q-mr-sm"
        @click="router.go(-1)"
      />
      รายละเอียดคำร้องขอแก้ไขทะเบียนประวัติของ{{ dataRequest.fullname }}
    </div>
  </div>
  <q-card>
    <q-card-section>
      <div class="row q-gutter-sm">
        <!-- รายละเอียดคำร้องขอแก้ไข -->
        <q-card bordered class="row col-12">
          <div class="bg-grey-1 q-pa-sm col-12 row items-center">
            <div class="q-pl-sm text-weight-bold text-dark">
              รายละเอียดคำร้องขอแก้ไข
            </div>
          </div>
          <div class="col-12"><q-separator /></div>
          <q-card-section class="col-12">
            <div class="row q-col-gutter-sm">
              <!-- วันที่ยื่นขอ -->
              <div class="col-md-2 col-xs-12">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="dataRequest.createdAt"
                  :locale="'th'"
                  autoApply
                  readonly
                  borderless
                  :enableTimePicker="false"
                  week-start="0"
                >
                  <template #year="{ year }">
                    {{ year + 543 }}
                  </template>
                  <template #year-overlay-value="{ value }">
                    {{ parseInt(value + 543) }}
                  </template>
                  <template #trigger>
                    <q-input
                      outlined
                      readonly
                      dense
                      hide-bottom-space
                      class="full-width"
                      :model-value="
                        dataRequest.createdAt != null
                          ? date2Thai(dataRequest.createdAt)
                          : null
                      "
                      :label="`${'วันที่ยื่นขอ'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <!-- เรื่อง -->
              <div class="col-md-10 col-xs-12">
                <q-input
                  :class="classInput(true)"
                  readonly
                  v-model="dataRequest.topic"
                  label="เรื่อง"
                  dense
                  outlined
                />
              </div>

              <!-- รายละเอียด -->
              <div class="col-12">
                <q-input
                  :class="classInput(true)"
                  readonly
                  v-model="dataRequest.detail"
                  label="รายละเอียด"
                  dense
                  outlined
                  type="textarea"
                />
              </div>
            </div>
          </q-card-section>
        </q-card>

        <!-- แก้ไขสถานะคำร้อง -->
        <q-form
          class="col-12"
          greedy
          @submit.prevent
          @validation-success="onSubmit"
        >
          <q-card bordered class="row col-12">
            <div class="bg-grey-1 q-pa-sm col-12 row items-center">
              <div class="q-pl-sm text-weight-bold text-dark">
                แก้ไขสถานะคำร้อง
              </div>
            </div>
            <div class="col-12"><q-separator /></div>
            <q-card-section class="col-12">
              <div class="row q-col-gutter-sm">
                <div class="col-xs-12 col-md-12">
                  <q-select
                    :class="
                      classInput(
                        isReadOnly || !workflowRef?.permission.isUpdate
                      )
                    "
                    :readonly="isReadOnly || !workflowRef?.permission.isUpdate"
                    v-model="formData.status"
                    label="สถานะ"
                    dense
                    outlined
                    emit-value
                    map-options
                    :options="statusOption"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกสถานะ'}`]"
                    lazy-rules
                    hide-bottom-space
                    use-input
                    option-label="name"
                    option-value="id"
                    @filter="(inputValue:string,
                          doneFn:Function) => filterOption(inputValue, doneFn
                          ) "
                  >
                    <template v-slot:no-option>
                      <q-item>
                        <q-item-section class="text-grey">
                          ไม่มีข้อมูล
                        </q-item-section>
                      </q-item>
                    </template>
                  </q-select>
                </div>

                <div class="col-xs-12 col-md-12">
                  <q-input
                    :class="
                      classInput(
                        isReadOnly || !workflowRef?.permission.isUpdate
                      )
                    "
                    :readonly="isReadOnly || !workflowRef?.permission.isUpdate"
                    v-model="formData.remark"
                    label="หมายเหตุ"
                    dense
                    outlined
                    type="textarea"
                    hide-bottom-space
                  />
                </div>

                <div
                  class="row col-12 justify-end"
                  v-if="!isReadOnly && workflowRef?.permission.isUpdate"
                >
                  <q-btn label="บันทึก" color="secondary" type="submit"
                    ><q-tooltip>บันทึก</q-tooltip></q-btn
                  >
                </div>
              </div>
            </q-card-section>
            <q-separator />
          </q-card>
        </q-form>

        <div class="col-12">
          <Workflow
            ref="workflowRef"
            :id="requestId"
            sys-name="REGISTRY_PROFILE"
          />
        </div>
      </div>
    </q-card-section>
  </q-card>
</template>

<style scoped></style>
