<script setup lang="ts">
import { ref, unref } from "vue";
import ReconciliationForm from "/@/components/ReconciliationForm";
import { ElForm, ElMessage } from "element-plus";
import { createRules } from "../config/_rules";
import ChooseModal from "./choose-modal.vue";

const emit = defineEmits(["create"]);

const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const chooseModalRef = ref<InstanceType<typeof ChooseModal> | null>(null);
const reconciliationRef = ref<InstanceType<typeof ReconciliationForm> | null>(
  null
);

const formData = ref({ payNo: "", pay_fee: "" });

const handleChoose = () => chooseModalRef.value.onDisplay();

function handleCreate() {
  const { detail } = reconciliationRef.value;
  if (Number(formData.value.pay_fee) > Number(detail?.wpay_fee)) {
    return ElMessage.error("付款金额不能超过未付款金额");
  }

  formRef.value.validate(isValid => isValid && emit("create", unref(formData)));
}
</script>

<template>
  <div w-full>
    <ElForm ref="formRef" :model="formData" :rules="createRules">
      <ElFormItem label="订单对账" prop="payNo">
        <ReconciliationForm
          ref="reconciliationRef"
          isPurchPay
          :id="formData.payNo"
          :readonly="!!formData.payNo"
          @choose="handleChoose"
        />
      </ElFormItem>

      <ElFormItem label="付款金额" prop="pay_fee">
        <ElInput v-model="formData.pay_fee" placeholder="请输入付款金额" />
      </ElFormItem>

      <ElFormItem>
        <div class="flex w-full justify-end">
          <ElButton type="primary" @click="handleCreate">保存</ElButton>
        </div>
      </ElFormItem>
    </ElForm>

    <ChooseModal
      ref="chooseModalRef"
      @choose="payNo => (formData.payNo = payNo)"
    />
  </div>
</template>
