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

import { PURCHASE_OLD_APPLY_DATE } from "/@/utils/constants"

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 isOldTime = ref(false)
const isCommon = ref(false)


const isOld = computed(() => isOldTime.value || isCommon.value)

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

function handleCreate() {
  const invInfo = reconciliationRef.value?.getOpenInvInfo();
  const { data = {}, orderArr  = []} = invInfo
  const { payNo } = data
  const cgdNos = orderArr.map(({ currentTotal: rela_fee,  sequenceNo}) => ({ rela_fee,  sequenceNo }))

  if(cgdNos.length === 0 && !isOld.value){
    ElMessage.warning('至少选择一条采购单')
    return
  }

  let parameter = {}
  if(isOld.value){
    parameter = { payNo: formData.value.payNo, pay_fee: formData.value.pay_fee }
  }else{
    parameter = { cgdNos, payNo }
  }

  formRef.value.validate(isValid => isValid && emit("create", parameter, isOld.value));
}


function handleAddRecord(data = {}){
  const { payNo, is_comon } = data
  const date = payNo.slice(3, 9)
  isOldTime.value = Number(date) < Number(PURCHASE_OLD_APPLY_DATE)
  isCommon.value = is_comon == '1'
  console.log(isOldTime.value, isCommon.value, is_comon)
  formData.value.payNo = payNo
}
</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"
          :cover="true"
          @choose="handleChoose"
          :isChoosePurchaseOrder="!isOld"
        />
      </ElFormItem>

      <ElFormItem label="付款金额" prop="pay_fee" v-if="isOld">
        <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="handleAddRecord" />
  </div>
</template>
