<script setup lang="ts">
import { ref, watch, nextTick } from "vue"
import { useVModel } from "@vueuse/core"
import { httpBindCompany } from "/@/api/purchase/inputInvoicePool";
import { ElForm, ElMessage } from "element-plus"

import InvoiceCompanyUpdate from "/@/components/InvoiceCompanyUpdate"

import { useTask } from "/@/hooks/core"


const props = defineProps<{ visible: boolean, data: any }>()
const emit = defineEmits(['refresh'])


const visible = useVModel(props, 'visible')

const bindTask = useTask({ 
  success(){
    ElMessage.success('绑定成功!')
    visible.value = false
    emit('refresh')
  }
})


const invoiceCompanyUpdateRef = ref(null)

const formData = ref({ companyNo: '', supplierNo: '', companyName: '', supplierName: '' })
const formRef = ref<InstanceType<typeof ElForm> | null>(null)

const rules = {
  companyNo: [{ required: true,  message: '买入方公司不能为空', trigger: 'change'}],
  supplierNo: [{ required: true, message: '卖出方公司不能为空', trigger: 'change'}] 
}

async function onSubmit(){
  // try{
    // await formRef.value?.validate()
    const { 
      id,
      InvCode,
      invoice_code,
      invoice_type, 
      invoice_total, 
      invoice_number, 
      invoice_subtotal,
      check_code,
      open_date, 
      status
    } = props.data


    const { companyNo, supplierNo } = formData.value

    if(!companyNo || !supplierNo){
      ElMessage.warning('请选择购买方公司和销售方公司')
      return
    }

    const parameter = {
      id, 
      InvCode,
      invoice_code, 
      invoice_number, 
      invoice_type, 
      invoice_total, 
      open_date, 
      invoice_subtotal,
      check_code,
      status,
      companyNo,
      supplierNo
    }

    bindTask.run(httpBindCompany(parameter))
  // }catch(err){
  //   console.log(err)
  // }
}

const handleClose = () => formData.value = { companyNo: '', supplierNo: '', companyName: '', supplierName: '' }


watch(() => visible.value, () => {
  if(!visible.value) return
  const { companyNo, supplierNo, companyName, supplierName } = props.data || {}
  formData.value.companyNo = companyNo
  formData.value.supplierNo = supplierNo
  formData.value.companyName = companyName
  formData.value.supplierName = supplierName
  nextTick(() => invoiceCompanyUpdateRef.value.initialData())
}, {
  immediate: true
})
</script>


<template>
  <ElDialog 
    v-model="visible" 
    center 
    @close="handleClose" 
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <InvoiceCompanyUpdate
      ref="invoiceCompanyUpdateRef"
      v-model:data="formData"
      :invNumber="data.invoice_number" 
      type="purchase" 
    />


    <div class="flex w-full justify-end mt-[10px]">
      <ElButton type="primary" size="small" @click="onSubmit">
        保存
      </ElButton>
    </div>
  </ElDialog>
</template>
