<script setup lang="ts">
import { ref, unref } from "vue";
import { ElForm, ElMessage } from "element-plus";
import ChooseInvoiceModal from "./choose-invoice-modal/index.vue" 
import BasicDescriptions from "/@/components/BasicDescriptions";
import { httpDetail, httpAdd } from "/@/api/purchase/invoiceRelation";
import { invoicePoolColumns } from "/@/utils/details/_purchase";
import { useTask } from "/@/hooks/core"
import { useRouter } from "vue-router"


const router = useRouter()
const formRef = ref<InstanceType<typeof ElForm> | null>(null)
const state = ref({ visible: false, loading: false, data: null })
const formData = ref<Record<string, any>>({ InvCode: '', invoiceNumber: '' })
const rules = { InvCode: [ { required: true, message: '请选择发票号码', trigger: 'change' } ] }


const invoiceRelationTask = useTask({ success(){
    ElMessage.success('创建成功!')
    router.push('/purchase/invoiceRelation')
  } 
})


async function handleCreate() {
  try{
    await formRef.value.validate()
    const { InvCode } = formData.value
    invoiceRelationTask.run(httpAdd({ InvCode }))
  }catch(err){
    console.log(err)
  }
}

async function handleChooseInvoice(data){
  const result = await httpDetail({ InvCode: data.InvCode })
  formData.value.invoiceNumber = result.data.invoice_number
  formData.value.InvCode = result.data.InvCode
  state.value.data = result.data
}
</script>

<template>
  <div class="ticket__content w-full" v-loading="invoiceRelationTask.loading">
    <ElForm
      ref="formRef"
      :rules="rules"
      :model="formData"
      label-width="110px"
    >
      <ElFormItem label="进项发票号码" prop="InvCode" v-loading="state.loading">
        <div class="w-full flex flex-col">
          <ElInput 
            v-model="formData.invoiceNumber" 
            @click="state.visible = true"
            placeholder="进项发票号码" 
          />
          
          <BasicDescriptions 
            class="mt-[10px]" 
            v-if="state.data" 
            :data="state.data"  
            :columns="invoicePoolColumns" 
          />
        </div>
      </ElFormItem>
  
      <ElFormItem>
        <div class="flex w-full justify-end mt-[10px]">
          <ElButton type="primary" @click="handleCreate">
            保存
          </ElButton>
        </div>
      </ElFormItem>
    </ElForm>

    <ChooseInvoiceModal v-model:visible="state.visible" @submit="handleChooseInvoice" />
  </div>
</template>
