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

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<Record<string, any>>({
  payNo: "",
  invArr: []
});

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

function handleCreate() {
  formRef.value.validate(isValid => isValid && emit("create", unref(formData)));
}

const handleChange = invArr => {
  invArr.forEach(inv => {
    const origin = inv.invoiceType;
    if (!origin) return;
    const target = cg_inv_type_list.find(({ scanValue }) => scanValue === origin);
    if (target) { inv.invoiceType = target.value; }
  });
  formData.value.invArr = invArr;
};
</script>

<template>
  <div w-full>
    <ElForm
      ref="formRef"
      label-width="100px"
      :model="formData"
      :rules="createRules"
    >
      <ElFormItem label="订单对账" prop="payNo">
        <ReconciliationForm
          ref="reconciliationRef"
          :showTicketColumn="true"
          :is-purch-pay="true"
          :id="formData.payNo"
          :readonly="!!formData.payNo"
          @choose="handleChoose"
        />
      </ElFormItem>

      <ElFormItem label="发票" prop="invArr">
        <InvoiceTable @change="handleChange" />
      </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>
