<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

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

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

/**
 * importStore
 */
import { useRequestEditStore } from "@/modules/04_registryPerson/stores/RequestEdit";
import { useCounterMixin } from "@/stores/mixin";

/**
 * use
 */
const $q = useQuasar();
const store = useRequestEditStore();
const { dialogConfirm, showLoader, hideLoader, messageError, success } =
  useCounterMixin();

/**
 *  props
 */
const modal = defineModel<boolean>("modal", { required: true });
const requestId = defineModel<string>("requestId", { required: true });
const props = defineProps({
  fetchData: { type: Function, requied: true },
});

const isReadOnly = ref<boolean>(false);
const formData = reactive({
  status: "",
  remark: "",
});
const statusOptionMain = ref<DataOption[]>(
  store.optionStatus.filter((e) => e.id !== "")
);
const statusOption = ref<DataOption[]>(statusOptionMain.value);

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

/**
 * function ปิด popup
 */
function closeDialog() {
  modal.value = false;
  formData.status = "";
  formData.remark = "";
}

function classInput(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

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

/**
 * function fetch ข้อมูลคำร้องแก้ไข
 */
function fetchDataRequest() {
  showLoader();
  http
    .get(config.API.requestEdit + `${requestId.value}`)
    .then((res) => {
      const data = res.data.result;
      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();
    });
}

watch(
  () => modal.value,
  () => {
    modal.value && fetchDataRequest();
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 700px; max-width: 80vw">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader tittle="แก้ไขสถานะคำร้อง" :close="closeDialog" />
        <q-separator />

        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-xs-12 col-md-12">
              <q-select
                :class="classInput(isReadOnly)"
                :readonly="isReadOnly"
                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)"
                :readonly="isReadOnly"
                v-model="formData.remark"
                label="หมายเหตุ"
                dense
                outlined
                type="textarea"
                hide-bottom-space
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />

        <q-card-actions align="right" v-if="!isReadOnly">
          <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></style>
