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

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 formData = ref({ companyNo: '', supplierNo: '' })
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 parameter = {
      id, 
      InvCode,
      invoice_code, 
      invoice_number, 
      invoice_type, 
      invoice_total, 
      open_date, 
      invoice_subtotal,
      check_code,
      status,
      companyNo: formData.value.companyNo,
      supplierNo: formData.value.supplierNo
    }

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

const handleClose = () => formData.value = { companyNo: '', supplierNo: '' }
</script>


<template>
  <ElDialog 
    v-model="visible" 
    center 
    title="绑定公司" 
    @close="handleClose" 
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <ElForm :rules="rules" ref="formRef" :model="formData">
      <ElFormItem label="买入方公司" prop="companyNo">
        <BusinessQuery 
          v-model="formData.companyNo" 
          placeholder="买入方公司" 
        />
      </ElFormItem>


      <ElFormItem label="卖出方公司" prop="supplierNo">
        <SupplierQuery 
          v-model="formData.supplierNo" 
          placeholder="卖出方公司" 
        />
      </ElFormItem>

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