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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useCommandMainStore } from "@/modules/18_command/store/Main";
import { useCommandDetail } from "@/modules/18_command/store/DetailStore";
import DialogHeader from "@/components/DialogHeader.vue";
import CurruncyInput from "@/components/CurruncyInput.vue";

const $q = useQuasar();
const { showLoader, hideLoader, dialogConfirm, messageError, success } =
  useCounterMixin();
const store = useCommandMainStore();
const storeDetail = useCommandDetail();

const props = defineProps({
  getData: Function,
  selectPersonData: Object,
  type: {
    type: String,
    required: true,
  },
  commandCode: { type: String, required: true },
  commandSysId: { type: String, required: true },
});
const modal = defineModel<boolean>("modal", { required: true });
const titleName = defineModel<string>("titleName", { required: true });
const commandEditRecive = defineModel<string>("commandEditRecive", {
  required: true,
});

const formData = reactive<any>({
  amount: null,
  positionSalaryAmount: null,
  mouthSalaryAmount: null,
  remarkVertical: null,
  remarkHorizontal: null,
  amountSpecial: null,
});

const readonly = ref<boolean>(false);

function checkCommandSysId() {
  if (props.commandSysId === "SALARY") {
    readonly.value = true;
  }
}
function onSubmit() {
  dialogConfirm($q, () => {
    showLoader();
    http
      .put(config.API.commandEditRecive("tab2", commandEditRecive.value), {
        mouthSalaryAmount:
          typeof formData.monthSalaryAmount === "string"
            ? Number(formData.monthSalaryAmount?.replace(/,/g, ""))
            : formData.monthSalaryAmount, //เงินเดือน
        positionSalaryAmount:
          typeof formData.positionSalaryAmount === "string"
            ? Number(formData.positionSalaryAmount?.replace(/,/g, ""))
            : formData.positionSalaryAmount, //เงินประจำตำแหน่ง
        amount:
          typeof formData.amount === "string"
            ? Number(formData.amount?.replace(/,/g, ""))
            : formData.amount, //เงินค่าตอบแทนรายเดือน
        amountSpecial:
          typeof formData.amountSpecial === "string"
            ? Number(formData.amountSpecial?.replace(/,/g, ""))
            : formData.amountSpecial, //เงินค่าตอบแทนรายเดือน
        remarkVertical: formData.remarkVertical, //หมายเหตุแนวตั้ง
        remarkHorizontal: formData.remarkHorizontal, //หมายเหตุแนวนอน
      })
      .then(async () => {
        await props.getData?.();
        success($q, "บันทึกข้อมูลสำเร็จ");
        onClose();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function onClose() {
  modal.value = false;
  formData.amount = null;
  formData.positionSalaryAmount = null;
  formData.monthSalaryAmount = null;
  formData.remarkVertical = null;
  formData.remarkHorizontal = null;
}

/**
 * class จัดรูปแบบแสดงระหว่างข้อมูลที่แก้ไขหรือแสดงเฉยๆ
 * @param val ข้อมูล input สำหรับแก้ไขหรือไม่
 */
const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};

watch(
  () => modal.value,
  () => {
    if (modal.value) {
      if (props.selectPersonData) {
        checkCommandSysId();
        const list = props.selectPersonData;
        formData.amount = list.amount;
        formData.positionSalaryAmount = list.positionSalaryAmount;
        formData.amountSpecial = list.amountSpecial;
        formData.monthSalaryAmount = list.mouthSalaryAmount;
        formData.remarkVertical = list.remarkVertical;
        formData.remarkHorizontal = list.remarkHorizontal;
      }
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 40vw">
      <q-form q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader :tittle="titleName" :close="onClose" />
        <q-separator />
        <q-card-section>
          <div class="row col-12 q-col-gutter-sm">
            <div
              class="row col-12 q-col-gutter-sm"
              v-if="storeDetail.isSalary || readonly"
            >
              <div
                v-if="store.isShowSalary(type)"
                class="col-xs-6 col-sm-6 col-md-6"
              >
                <CurruncyInput
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  v-model="formData.amount"
                  :class="getClass(storeDetail.isSalary)"
                  :readonly="!storeDetail.isSalary"
                  :label="`${'เงินเดือน'}`"
                  :rules="[
                    (val:any) => !!val || 'กรุณากรอกเงินเดือน',
                    (val:any) => {
                      if (!val) return true;
                      const numVal = typeof val === 'number' ? val : Number(String(val).replace(/,/g, ''));
                      return numVal <= 10000000 || 'เงินเดือนต้องไม่เกิน 10,000,000 บาท';
                    }
                  ]"
                />
              </div>
              <div
                v-if="store.isShowSalary(type)"
                class="col-xs-6 col-sm-6 col-md-6"
              >
                <CurruncyInput
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  v-model="formData.amountSpecial"
                  :class="getClass(storeDetail.isSalary)"
                  :readonly="!storeDetail.isSalary"
                  :label="`${'เงินค่าตอบแทนพิเศษ'}`"
                  :rules="[
                    (val:any) => {
                      if (!val) return true;
                      const numVal = typeof val === 'number' ? val : Number(String(val).replace(/,/g, ''));
                      return numVal <= 10000000 || 'เงินค่าตอบแทนพิเศษต้องไม่เกิน 10,000,000 บาท';
                    }
                  ]"
                />
              </div>
              <div
                v-if="store.isShowSalary(type)"
                class="col-xs-6 col-sm-6 col-md-6"
              >
                <CurruncyInput
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  v-model="formData.positionSalaryAmount"
                  :class="getClass(storeDetail.isSalary)"
                  :readonly="!storeDetail.isSalary"
                  :label="`${'เงินประจำตำแหน่ง'}`"
                  :rules="[
                    (val:any) => {
                      if (!val) return true;
                      const numVal = typeof val === 'number' ? val : Number(String(val).replace(/,/g, ''));
                      return numVal <= 10000000 || 'เงินประจำตำแหน่งต้องไม่เกิน 10,000,000 บาท';
                    }
                  ]"
                />
              </div>

              <div
                v-if="store.isShowSalary(type)"
                class="col-xs-6 col-sm-6 col-md-6"
              >
                <CurruncyInput
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  v-model="formData.monthSalaryAmount"
                  :class="getClass(storeDetail.isSalary)"
                  :readonly="!storeDetail.isSalary"
                  :label="`${'เงินค่าตอบแทนรายเดือน'}`"
                  :rules="[
                    (val:any) => {
                      if (!val) return true;
                      const numVal = typeof val === 'number' ? val : Number(String(val).replace(/,/g, ''));
                      return numVal <= 10000000 || 'เงินค่าตอบแทนรายเดือนต้องไม่เกิน 10,000,000 บาท';
                    }
                  ]"
                />
              </div>
            </div>

            <div class="col-xs-6 col-sm-6 col-md-12">
              <q-input
                dense
                outlined
                v-model="formData.remarkVertical"
                label="หมายเหตุแนวตั้ง"
                type="textarea"
                rows="5"
                class="inputgreen"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-12">
              <q-input
                dense
                outlined
                v-model="formData.remarkHorizontal"
                type="textarea"
                label="หมายเหตุแนวนอน"
                rows="5"
                class="inputgreen"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn label="บันทึก" color="public" type="submit">
            <q-tooltip>บันทึก</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
