<script lang="ts" setup>
/**
 * 本方开票弹窗：开票方锁定为当前登录角色
 */
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Input, message } from 'ant-design-vue';

import UploadDraggerPaste from '#/components/form/components/upload-dragger-paste.vue';

import { completeMyInvoiceApi } from '../api';

const invoiceCode = ref('');
const fileUrls = ref<string[]>([]);
const partyId = ref(0);
const invoiceId = ref(0);
const amount = ref('');
const orderNo = ref('');
const partyName = ref('');
const gridApi = ref<any>();

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    const code = invoiceCode.value.trim();
    if (!code) {
      message.warning('请填写票据代码');
      return;
    }
    if (!fileUrls.value.length) {
      message.warning('请上传发票文件');
      return;
    }
    modalApi.setState({ loading: true, confirmLoading: true });
    try {
      const res: any = await completeMyInvoiceApi({
        party_id: partyId.value,
        invoice_id: invoiceId.value,
        invoice_code: code,
        invoice_files: fileUrls.value,
      });
      if (res?.subscribe_warn) {
        message.warning(String(res.subscribe_warn));
      } else if (res?.all_completed) {
        message.success('开票完成（全部方已齐）');
      } else {
        message.success('本方开票已提交');
      }
      gridApi.value?.reload?.();
      modalApi.close();
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    const data = modalApi.getData<Record<string, any>>() || {};
    partyId.value = Number(data.id || 0);
    invoiceId.value = Number(data.invoice_id || 0);
    amount.value = String(data.amount || '');
    orderNo.value = String(data.order_no || '');
    partyName.value = String(data.party_name || '本方');
    gridApi.value = data.gridApi;
    invoiceCode.value = '';
    fileUrls.value = [];
  },
});
</script>

<template>
  <Modal title="提交本方发票" class="w-[560px]">
    <div class="space-y-4 py-2">
      <div class="rounded border border-border bg-muted/40 px-3 py-2 text-sm text-foreground">
        订单 {{ orderNo || '-' }}，开票方
        <b>{{ partyName }}</b>
        ，金额 ￥{{ amount || '0' }}
        <div class="mt-1 text-muted-foreground">按登录角色自动锁定，不可更改</div>
      </div>
      <div>
        <div class="mb-1 font-medium text-foreground">票据代码</div>
        <Input v-model:value="invoiceCode" placeholder="请输入发票代码/号码" allow-clear />
      </div>
      <div>
        <div class="mb-1 font-medium text-foreground">发票文件（图片或 PDF）</div>
        <UploadDraggerPaste
          v-model="fileUrls"
          accept=".jpg,.jpeg,.png,.webp,.pdf,image/*,application/pdf"
          tip="点击或拖拽发票文件到此处"
          :max-count="9"
          :max-size-mb="20"
        />
      </div>
    </div>
  </Modal>
</template>
