From 5470429a79313630a7ddef601de1d89e7dada754 Mon Sep 17 00:00:00 2001
From: yyb <995253665@qq.com>
Date: 星期五, 22 五月 2026 09:14:12 +0800
Subject: [PATCH] Merge remote-tracking branch 'origin/dev_NEW_pro' into dev-new_pro_OA

---
 src/views/financialManagement/payable/input-invoice.vue |  918 +++++++++++++++++++++++++++++++++++++++++++++-----------
 1 files changed, 727 insertions(+), 191 deletions(-)

diff --git a/src/views/financialManagement/payable/input-invoice.vue b/src/views/financialManagement/payable/input-invoice.vue
index 660d0dd..86ebd09 100644
--- a/src/views/financialManagement/payable/input-invoice.vue
+++ b/src/views/financialManagement/payable/input-invoice.vue
@@ -1,50 +1,61 @@
 <template>
   <div class="app-container">
     <el-form :model="filters" :inline="true">
-      <el-form-item label="鍙戠エ浠g爜:">
-        <el-input v-model="filters.invoiceCode" placeholder="璇疯緭鍏ュ彂绁ㄤ唬鐮�" clearable style="width: 200px;" />
-      </el-form-item>
       <el-form-item label="鍙戠エ鍙风爜:">
-        <el-input v-model="filters.invoiceNo" placeholder="璇疯緭鍏ュ彂绁ㄥ彿鐮�" clearable style="width: 200px;" />
+        <el-input v-model="filters.invoiceNumber" placeholder="璇疯緭鍏ュ彂绁ㄥ彿鐮�" clearable style="width: 200px;" />
       </el-form-item>
       <el-form-item label="渚涘簲鍟�:">
-        <el-select v-model="filters.supplierId" placeholder="璇烽�夋嫨渚涘簲鍟�" clearable style="width: 200px;">
-          <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id" />
+        <el-select v-model="filters.supplierId" placeholder="璇烽�夋嫨渚涘簲鍟�" clearable filterable style="width: 200px;">
+          <el-option
+            v-for="item in supplierList"
+            :key="item.id"
+            :label="item.supplierName"
+            :value="item.id"
+          />
         </el-select>
       </el-form-item>
-      <el-form-item label="璁よ瘉鐘舵��:">
-        <el-select v-model="filters.certifyStatus" placeholder="璇烽�夋嫨璁よ瘉鐘舵��" clearable style="width: 150px;">
-          <el-option label="鏈璇�" value="uncertified" />
-          <el-option label="宸茶璇�" value="certified" />
-          <el-option label="璁よ瘉澶辫触" value="failed" />
+      <el-form-item label="寮�绁ㄦ棩鏈�:">
+        <el-date-picker
+          v-model="filters.dateRange"
+          type="daterange"
+          value-format="YYYY-MM-DD"
+          format="YYYY-MM-DD"
+          range-separator="鑷�"
+          start-placeholder="寮�濮嬫棩鏈�"
+          end-placeholder="缁撴潫鏃ユ湡"
+          clearable
+          style="width: 240px;"
+        />
+      </el-form-item>
+      <el-form-item label="鐘舵��:">
+        <el-select v-model="filters.status" placeholder="璇烽�夋嫨鐘舵��" clearable style="width: 150px;">
+          <el-option label="姝e父" :value="0" />
+          <el-option label="浣滃簾" :value="1" />
         </el-select>
       </el-form-item>
       <el-form-item>
-        <el-button type="primary" @click="getTableData">鎼滅储</el-button>
+        <el-button type="primary" @click="onSearch">鎼滅储</el-button>
         <el-button @click="resetFilters">閲嶇疆</el-button>
       </el-form-item>
     </el-form>
     <div class="table_list">
       <div class="actions">
-        <div>
-          <el-button type="success" @click="handleBatchCertify" icon="Check" :disabled="selectedRows.length === 0">鎵归噺璁よ瘉</el-button>
-        </div>
+        <div></div>
         <div>
           <el-button type="primary" @click="add" icon="Plus">褰曞叆鍙戠エ</el-button>
-          <el-button @click="handleOut" icon="Download">瀵煎嚭</el-button>
+          <el-button @click="handleExport" icon="Download">瀵煎嚭</el-button>
         </div>
       </div>
       <PIMTable
         rowKey="id"
-        isSelection
         :column="columns"
         :tableData="dataList"
+        :tableLoading="tableLoading"
         :page="{
           current: pagination.currentPage,
           size: pagination.pageSize,
           total: pagination.total,
         }"
-        @selection-change="handleSelectionChange"
         @pagination="changePage"
       >
         <template #amount="{ row }">
@@ -56,54 +67,123 @@
         <template #totalAmount="{ row }">
           <span class="text-success">楼{{ formatMoney(row.totalAmount) }}</span>
         </template>
-        <template #certifyStatus="{ row }">
-          <el-tag :type="getCertifyStatusType(row.certifyStatus)">{{ getCertifyStatusLabel(row.certifyStatus) }}</el-tag>
+        <template #status="{ row }">
+          <el-tag :type="getStatusType(row.status)" effect="light" round>
+            {{ getStatusLabel(row.status) }}
+          </el-tag>
         </template>
         <template #operation="{ row }">
           <el-button type="primary" link @click="view(row)">鏌ョ湅</el-button>
-          <el-button type="primary" link @click="edit(row)">缂栬緫</el-button>
-          <el-button type="success" link @click="handleCertify(row)" v-if="row.certifyStatus === 'uncertified'">璁よ瘉</el-button>
+          <el-button type="warning" link @click="handleCancel(row)" v-if="isNormalStatus(row.status)">浣滃簾</el-button>
+          <el-button type="danger" link @click="handleDelete(row)">鍒犻櫎</el-button>
         </template>
       </PIMTable>
     </div>
 
-    <FormDialog :title="dialogTitle" v-model="dialogVisible" width="800px" @confirm="submitForm" @cancel="dialogVisible = false">
+    <FormDialog
+      :title="dialogTitle"
+      v-model="dialogVisible"
+      width="800px"
+      :operation-type="isView ? 'detail' : ''"
+      @confirm="submitForm"
+      @cancel="closeDialog"
+    >
       <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
-        <el-row :gutter="20">
+        <el-row v-if="isView" :gutter="20">
           <el-col :span="12">
-            <el-form-item label="鍙戠エ浠g爜" prop="invoiceCode">
-              <el-input v-model="form.invoiceCode" placeholder="璇疯緭鍏ュ彂绁ㄤ唬鐮�" />
-            </el-form-item>
-          </el-col>
-          <el-col :span="12">
-            <el-form-item label="鍙戠エ鍙风爜" prop="invoiceNo">
-              <el-input v-model="form.invoiceNo" placeholder="璇疯緭鍏ュ彂绁ㄥ彿鐮�" />
+            <el-form-item label="鐘舵��">
+              <el-tag :type="getStatusType(form.status)" effect="light" round>
+                {{ getStatusLabel(form.status) }}
+              </el-tag>
             </el-form-item>
           </el-col>
         </el-row>
         <el-row :gutter="20">
           <el-col :span="12">
+            <el-form-item label="鍙戠エ鍙风爜" prop="invoiceNo">
+              <el-input v-model="form.invoiceNo" placeholder="璇疯緭鍏ュ彂绁ㄥ彿鐮�" :disabled="isView" />
+            </el-form-item>
+          </el-col>
+          <el-col :span="12">
             <el-form-item label="渚涘簲鍟�" prop="supplierId">
-              <el-select v-model="form.supplierId" placeholder="璇烽�夋嫨渚涘簲鍟�" style="width: 100%;">
-                <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id" />
+              <el-select
+                v-model="form.supplierId"
+                placeholder="璇烽�夋嫨渚涘簲鍟�"
+                style="width: 100%;"
+                filterable
+                :disabled="isView"
+                @change="handleSupplierChange"
+              >
+                <el-option
+                  v-for="item in supplierList"
+                  :key="item.id"
+                  :label="item.supplierName"
+                  :value="item.id"
+                />
               </el-select>
+            </el-form-item>
+          </el-col>
+        </el-row>
+        <el-row :gutter="20">
+          <el-col :span="12">
+            <el-form-item label="鍏宠仈鍏ュ簱鍗�" prop="stockInRecordIds">
+              <el-input
+                :model-value="inboundBatchDisplayText"
+                placeholder="璇峰厛閫夋嫨渚涘簲鍟�"
+                readonly
+                :disabled="!form.supplierId || isView"
+                class="inbound-batch-input"
+                @click="handleInboundInputClick"
+              >
+                <template v-if="!isView" #append>
+                  <el-button
+                    :disabled="!form.supplierId"
+                    :loading="inboundBatchLoading"
+                    @click.stop="openInboundSelectDialog"
+                  >
+                    閫夋嫨
+                  </el-button>
+                </template>
+              </el-input>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="寮�绁ㄦ棩鏈�" prop="invoiceDate">
-              <el-date-picker v-model="form.invoiceDate" type="date" placeholder="閫夋嫨鏃ユ湡" value-format="YYYY-MM-DD" style="width: 100%;" />
+              <el-date-picker
+                v-model="form.invoiceDate"
+                type="date"
+                placeholder="閫夋嫨鏃ユ湡"
+                value-format="YYYY-MM-DD"
+                style="width: 100%;"
+                :disabled="isView"
+              />
             </el-form-item>
           </el-col>
         </el-row>
         <el-row :gutter="20">
-          <el-col :span="8">
-            <el-form-item label="閲戦(涓嶅惈绋�)" prop="amount">
-              <el-input-number v-model="form.amount" :min="0" :precision="2" style="width: 100%;" @change="calculateTax" />
+          <el-col :span="12">
+            <el-form-item label="鍙戠エ绫诲瀷" prop="invoiceType">
+              <el-select
+                v-model="form.invoiceType"
+                placeholder="璇烽�夋嫨鍙戠エ绫诲瀷"
+                style="width: 100%;"
+                :disabled="isView"
+              >
+                <el-option label="澧炲�肩◣涓撶敤鍙戠エ" value="澧炲�肩◣涓撶敤鍙戠エ" />
+                <el-option label="澧炲�肩◣鏅�氬彂绁�" value="澧炲�肩◣鏅�氬彂绁�" />
+                <el-option label="鐢靛瓙鍙戠エ" value="鐢靛瓙鍙戠エ" />
+              </el-select>
             </el-form-item>
           </el-col>
-          <el-col :span="8">
+          <el-col :span="12">
             <el-form-item label="绋庣巼" prop="taxRate">
-              <el-select v-model="form.taxRate" placeholder="璇烽�夋嫨绋庣巼" style="width: 100%;" @change="calculateTax">
+              <el-select
+                v-model="form.taxRate"
+                placeholder="璇烽�夋嫨绋庣巼"
+                style="width: 100%;"
+                :disabled="isView"
+                @change="handleTaxRateChange"
+              >
                 <el-option
                   v-for="dict in tax_rate"
                   :key="dict.value"
@@ -113,47 +193,109 @@
               </el-select>
             </el-form-item>
           </el-col>
-          <el-col :span="8">
-            <el-form-item label="绋庨">
-              <el-input v-model="form.taxAmount" disabled />
-            </el-form-item>
-          </el-col>
         </el-row>
         <el-row :gutter="20">
-          <el-col :span="12">
-            <el-form-item label="璁よ瘉鐘舵��" prop="certifyStatus">
-              <el-select v-model="form.certifyStatus" placeholder="璇烽�夋嫨璁よ瘉鐘舵��" style="width: 100%;" disabled>
-                <el-option label="鏈璇�" value="uncertified" />
-                <el-option label="宸茶璇�" value="certified" />
-                <el-option label="璁よ瘉澶辫触" value="failed" />
-              </el-select>
+          <el-col :span="8">
+            <el-form-item label="閲戦(涓嶅惈绋�)" prop="amount">
+              <el-input-number
+                v-model="form.amount"
+                :min="0"
+                :precision="2"
+                style="width: 100%;"
+                :disabled="isView"
+                placeholder="鏍规嵁鍏ュ簱鍗曞惈绋庨噾棰濊嚜鍔ㄦ崲绠楋紝鍙慨鏀�"
+                @change="calculateTaxFromExclusive"
+              />
             </el-form-item>
           </el-col>
-          <el-col :span="12">
-            <el-form-item label="璁よ瘉鏃ユ湡" prop="certifyDate">
-              <el-date-picker v-model="form.certifyDate" type="date" placeholder="閫夋嫨鏃ユ湡" value-format="YYYY-MM-DD" style="width: 100%;" disabled />
+          <el-col :span="8">
+            <el-form-item label="绋庨">
+              <el-input-number
+                v-model="form.taxAmount"
+                :min="0"
+                :precision="2"
+                :controls="false"
+                style="width: 100%;"
+                disabled
+              />
+            </el-form-item>
+          </el-col>
+          <el-col :span="8">
+            <el-form-item label="浠风◣鍚堣">
+              <el-input-number
+                v-model="form.totalAmount"
+                :min="0"
+                :precision="2"
+                :controls="false"
+                style="width: 100%;"
+                disabled
+              />
             </el-form-item>
           </el-col>
         </el-row>
         <el-form-item label="鍙戠エ鍐呭" prop="content">
-          <el-input v-model="form.content" type="textarea" :rows="3" placeholder="璇疯緭鍏ュ彂绁ㄥ唴瀹�" />
+          <el-input v-model="form.content" type="textarea" :rows="3" placeholder="璇疯緭鍏ュ彂绁ㄥ唴瀹�" :disabled="isView" />
         </el-form-item>
         <el-form-item label="澶囨敞" prop="remark">
-          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="璇疯緭鍏ュ娉�" />
+          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="璇疯緭鍏ュ娉�" :disabled="isView" />
         </el-form-item>
       </el-form>
-      <template #footer>
-        <el-button type="primary" @click="submitForm">纭畾</el-button>
-        <el-button @click="dialogVisible = false">鍙栨秷</el-button>
+      <template v-if="!isView" #footer>
+        <el-button type="primary" :loading="submitLoading" @click="submitForm">纭畾</el-button>
+        <el-button @click="closeDialog">鍙栨秷</el-button>
       </template>
     </FormDialog>
+
+    <el-dialog
+      v-model="inboundSelectVisible"
+      title="閫夋嫨鍏ュ簱鍗曞彿"
+      width="1100px"
+      append-to-body
+      destroy-on-close
+      :close-on-click-modal="false"
+      @closed="handleInboundDialogClosed"
+    >
+      <el-table
+        ref="inboundTableRef"
+        v-loading="inboundBatchLoading"
+        :data="inboundBatchList"
+        row-key="id"
+        border
+        stripe
+        max-height="480"
+        @selection-change="handleInboundDialogSelectionChange"
+      >
+        <el-table-column type="selection" width="55" align="center" />
+        <el-table-column prop="inboundBatches" label="鍏ュ簱鍗曞彿" min-width="140" show-overflow-tooltip />
+        <el-table-column prop="supplierName" label="渚涘簲鍟�" min-width="120" show-overflow-tooltip />
+        <el-table-column prop="productName" label="浜у搧鍚嶇О" min-width="120" show-overflow-tooltip />
+        <el-table-column prop="specificationModel" label="瑙勬牸鍨嬪彿" min-width="140" show-overflow-tooltip />
+        <el-table-column prop="purchaseContractNumber" label="閲囪喘璁㈠崟鍙�" min-width="140" show-overflow-tooltip />
+        <el-table-column prop="inboundDate" label="鍏ュ簱鏃ユ湡" width="110" align="center" />
+        <el-table-column prop="inboundAmount" label="鍏ュ簱閲戦(鍚◣)" width="120" align="right">
+          <template #default="{ row }">楼{{ formatMoney(getInboundRowTaxInclusiveAmount(row)) }}</template>
+        </el-table-column>
+      </el-table>
+      <template #footer>
+        <el-button type="primary" @click="confirmInboundSelection">纭畾</el-button>
+        <el-button @click="inboundSelectVisible = false">鍙栨秷</el-button>
+      </template>
+    </el-dialog>
   </div>
 </template>
 
 <script setup>
-import { ref, reactive, onMounted, getCurrentInstance } from "vue";
+import { ref, reactive, computed, onMounted, nextTick, getCurrentInstance } from "vue";
 import { ElMessage, ElMessageBox } from "element-plus";
 import FormDialog from "@/components/Dialog/FormDialog.vue";
+import { getOptions } from "@/api/procurementManagement/procurementLedger.js";
+import {
+  getInboundBatchesBySupplier,
+  addAccountPurchaseInvoice,
+  listPageAccountPurchaseInvoice,
+  cancelAccountPurchaseInvoice,
+  deleteAccountPurchaseInvoice,
+} from "@/api/financialManagement/accountPurchaseInvoice.js";
 
 defineOptions({
   name: "杩涢」鍙戠エ",
@@ -163,10 +305,10 @@
 const { tax_rate } = proxy.useDict("tax_rate");
 
 const filters = reactive({
-  invoiceCode: "",
-  invoiceNo: "",
+  invoiceNumber: "",
   supplierId: "",
-  certifyStatus: "",
+  dateRange: [],
+  status: "",
 });
 
 const pagination = reactive({
@@ -176,211 +318,601 @@
 });
 
 const columns = [
-  { label: "鍙戠エ浠g爜", prop: "invoiceCode", width: "130" },
-  { label: "鍙戠エ鍙风爜", prop: "invoiceNo", width: "120" },
+  { label: "鍙戠エ鍙风爜", prop: "invoiceNo", width: "140" },
   { label: "渚涘簲鍟�", prop: "supplierName", width: "180" },
   { label: "寮�绁ㄦ棩鏈�", prop: "invoiceDate", width: "120" },
-  { label: "閲戦", prop: "amount", slot: "amount" },
-  { label: "绋庨", prop: "taxAmount", slot: "taxAmount" },
-  { label: "浠风◣鍚堣", prop: "totalAmount", slot: "totalAmount" },
-  { label: "璁よ瘉鐘舵��", prop: "certifyStatus", slot: "certifyStatus" },
-  { label: "鎿嶄綔", prop: "operation", slot: "operation", width: "180", fixed: "right" },
+  { label: "閲戦", prop: "amount", dataType: "slot", slot: "amount" },
+  { label: "绋庨", prop: "taxAmount", dataType: "slot", slot: "taxAmount" },
+  { label: "浠风◣鍚堣", prop: "totalAmount", dataType: "slot", slot: "totalAmount" },
+  { label: "鍙戠エ绫诲瀷", prop: "invoiceType", width: "130" },
+  { label: "鐘舵��", prop: "status", dataType: "slot", slot: "status", width: "90", align: "center" },
+  { label: "鎿嶄綔", prop: "operation", dataType: "slot", slot: "operation", width: "200", fixed: "right" },
 ];
 
 const dataList = ref([]);
-const selectedRows = ref([]);
+const tableLoading = ref(false);
 const dialogVisible = ref(false);
 const dialogTitle = ref("");
 const formRef = ref(null);
-const isEdit = ref(false);
-const currentId = ref(null);
+const isView = ref(false);
+const submitLoading = ref(false);
+const supplierList = ref([]);
 
-const supplierList = [
-  { id: 1, name: "鍖椾含鍘熸潗鏂欎緵搴斿晢" },
-  { id: 2, name: "涓婃捣鐢靛瓙鍏冨櫒浠跺叕鍙�" },
-  { id: 3, name: "骞垮窞鍖呰鏉愭枡鍘�" },
-  { id: 4, name: "娣卞湷浜旈噾閰嶄欢鍏徃" },
-];
+const inboundBatchList = ref([]);
+const inboundBatchOptions = ref([]);
+const inboundBatchLoading = ref(false);
+const inboundSelectVisible = ref(false);
+const inboundTableRef = ref(null);
+const dialogInboundSelection = ref([]);
+
+const STATUS_LABEL_MAP = { 0: "姝e父", 1: "浣滃簾" };
+const STATUS_TYPE_MAP = { 0: "success", 1: "info" };
 
 const form = reactive({
-  invoiceCode: "",
   invoiceNo: "",
   supplierId: "",
   invoiceDate: "",
-  amount: 0,
+  invoiceType: "澧炲�肩◣涓撶敤鍙戠エ",
   taxRate: 13,
+  amount: 0,
   taxAmount: 0,
   totalAmount: 0,
-  certifyStatus: "uncertified",
-  certifyDate: "",
   content: "",
   remark: "",
+  stockInRecordIds: [],
+  inboundBatches: "",
+  storageAttachmentId: undefined,
+  status: 0,
 });
 
 const rules = {
-  invoiceCode: [{ required: true, message: "璇疯緭鍏ュ彂绁ㄤ唬鐮�", trigger: "blur" }],
   invoiceNo: [{ required: true, message: "璇疯緭鍏ュ彂绁ㄥ彿鐮�", trigger: "blur" }],
   supplierId: [{ required: true, message: "璇烽�夋嫨渚涘簲鍟�", trigger: "change" }],
+  stockInRecordIds: [{ required: true, type: "array", min: 1, message: "璇烽�夋嫨鍏宠仈鍏ュ簱鍗�", trigger: "change" }],
   invoiceDate: [{ required: true, message: "璇烽�夋嫨寮�绁ㄦ棩鏈�", trigger: "change" }],
-  amount: [{ required: true, message: "璇疯緭鍏ラ噾棰�", trigger: "blur" }],
+  invoiceType: [{ required: true, message: "璇烽�夋嫨鍙戠エ绫诲瀷", trigger: "change" }],
   taxRate: [{ required: true, message: "璇烽�夋嫨绋庣巼", trigger: "change" }],
+  amount: [{ required: true, message: "璇疯緭鍏ラ噾棰�", trigger: "blur" }],
 };
-
-const mockData = [
-  { id: 1, invoiceCode: "0440021001", invoiceNo: "12345678", supplierId: 1, supplierName: "鍖椾含鍘熸潗鏂欎緵搴斿晢", invoiceDate: "2024-01-08", amount: 8000, taxRate: 13, taxAmount: 1040, totalAmount: 9040, certifyStatus: "certified", certifyDate: "2024-01-15", content: "鍘熸潗鏂欓噰璐�", remark: "" },
-  { id: 2, invoiceCode: "0440021002", invoiceNo: "87654321", supplierId: 2, supplierName: "涓婃捣鐢靛瓙鍏冨櫒浠跺叕鍙�", invoiceDate: "2024-01-10", amount: 12000, taxRate: 13, taxAmount: 1560, totalAmount: 13560, certifyStatus: "uncertified", certifyDate: "", content: "鐢靛瓙鍏冨櫒浠�", remark: "" },
-  { id: 3, invoiceCode: "0440021003", invoiceNo: "11112222", supplierId: 3, supplierName: "骞垮窞鍖呰鏉愭枡鍘�", invoiceDate: "2024-01-12", amount: 3500, taxRate: 13, taxAmount: 455, totalAmount: 3955, certifyStatus: "certified", certifyDate: "2024-01-18", content: "鍖呰鏉愭枡", remark: "" },
-];
 
 const formatMoney = (value) => {
   if (value === undefined || value === null) return "0.00";
   return Number(value).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
 };
 
-const calculateTax = () => {
+const normalizeStatus = (status) => {
+  if (status === undefined || status === null || status === "") return 0;
+  const num = Number(status);
+  return Number.isNaN(num) ? 0 : num;
+};
+
+const isNormalStatus = (status) => normalizeStatus(status) === 0;
+
+const getStatusLabel = (status) => STATUS_LABEL_MAP[normalizeStatus(status)] ?? "姝e父";
+
+const getStatusType = (status) => STATUS_TYPE_MAP[normalizeStatus(status)] ?? "success";
+
+const parseStockInRecordIds = (value) => {
+  if (!value) return [];
+  if (Array.isArray(value)) return value;
+  return String(value)
+    .split(/[,锛宂/)
+    .map((s) => s.trim())
+    .filter(Boolean)
+    .map((s) => (/^\d+$/.test(s) ? Number(s) : s));
+};
+
+const formatInboundBatches = (value) => {
+  if (value === undefined || value === null || value === "") return "";
+  if (Array.isArray(value)) return value.filter(Boolean).join("銆�");
+  return String(value)
+    .split(/[,锛宂/)
+    .map((s) => s.trim())
+    .filter(Boolean)
+    .join("銆�");
+};
+
+const isSameInboundId = (a, b) => String(a) === String(b);
+
+const getInboundRowId = (row) => row?.id ?? row?.stockInRecordId;
+
+/** 鍏ュ簱鍗曢噾棰濅负鍚◣浠� */
+const getInboundRowTaxInclusiveAmount = (row) =>
+  Number(row?.inboundAmount ?? row?.taxInclusivePrice ?? row?.totalAmount ?? 0);
+
+const normalizeInboundBatchOptions = (data) => {
+  const list = Array.isArray(data) ? data : [];
+  return list.map((item, index) => {
+    if (typeof item === "string" || typeof item === "number") {
+      const text = String(item);
+      return { label: text, value: text, inboundAmount: 0 };
+    }
+    const label =
+      item.inboundBatches ?? item.batchNo ?? item.inboundNo ?? item.label ?? `鍏ュ簱鍗�${index + 1}`;
+    const value = item.id ?? item.stockInRecordId ?? label;
+    return {
+      label: String(label),
+      value,
+      inboundAmount: getInboundRowTaxInclusiveAmount(item),
+    };
+  });
+};
+
+/** 涓嶅惈绋庨噾棰濆彉鏇达細绋庨銆佷环绋庡悎璁℃鍚戣绠� */
+const calculateTaxFromExclusive = () => {
   form.taxAmount = Number((form.amount * form.taxRate / 100).toFixed(2));
   form.totalAmount = Number((form.amount + form.taxAmount).toFixed(2));
 };
 
-const getCertifyStatusLabel = (status) => {
-  const map = { uncertified: "鏈璇�", certified: "宸茶璇�", failed: "璁よ瘉澶辫触" };
-  return map[status] || status;
+/** 浠风◣鍚堣鍙樻洿锛氭寜绋庣巼鍙嶇畻涓嶅惈绋庨噾棰濄�佺◣棰� */
+const calculateTaxFromInclusive = (inclusiveTotal) => {
+  const total = Number(inclusiveTotal ?? form.totalAmount ?? 0);
+  if (total <= 0) {
+    form.amount = 0;
+    form.taxAmount = 0;
+    form.totalAmount = 0;
+    return;
+  }
+  const rate = Number(form.taxRate) / 100;
+  form.totalAmount = Number(total.toFixed(2));
+  form.amount = Number((form.totalAmount / (1 + rate)).toFixed(2));
+  form.taxAmount = Number((form.totalAmount - form.amount).toFixed(2));
 };
 
-const getCertifyStatusType = (status) => {
-  const map = { uncertified: "info", certified: "success", failed: "danger" };
-  return map[status] || "";
+const handleTaxRateChange = () => {
+  if (form.totalAmount > 0) {
+    calculateTaxFromInclusive(form.totalAmount);
+  } else {
+    calculateTaxFromExclusive();
+  }
+};
+
+/** 鏍规嵁宸查�夊叆搴撳崟姹囨�诲惈绋庨噾棰濓紝鍙嶇畻涓嶅惈绋庨噾棰濅笌绋庨 */
+const syncInvoiceAmount = () => {
+  const selected = form.stockInRecordIds || [];
+  const sumFromOptions = inboundBatchOptions.value
+    .filter((opt) => selected.some((id) => isSameInboundId(id, opt.value)))
+    .reduce((acc, opt) => acc + (Number(opt.inboundAmount) || 0), 0);
+
+  let taxInclusiveSum = sumFromOptions;
+  if (taxInclusiveSum <= 0 && selected.length) {
+    taxInclusiveSum = inboundBatchList.value
+      .filter((row) => selected.some((id) => isSameInboundId(id, getInboundRowId(row))))
+      .reduce((acc, row) => acc + getInboundRowTaxInclusiveAmount(row), 0);
+  }
+
+  calculateTaxFromInclusive(taxInclusiveSum > 0 ? Number(taxInclusiveSum.toFixed(2)) : 0);
+};
+
+const inboundBatchDisplayText = computed(() => {
+  if (form.inboundBatches) return form.inboundBatches;
+  const ids = form.stockInRecordIds || [];
+  if (!ids.length) return "";
+  const labels = inboundBatchOptions.value
+    .filter((opt) => ids.some((id) => isSameInboundId(id, opt.value)))
+    .map((opt) => opt.label);
+  if (labels.length) return labels.join("銆�");
+  return ids.join("銆�");
+});
+
+const normalizeTableRow = (row) => ({
+  ...row,
+  invoiceNo: row.invoiceNumber ?? row.invoiceNo,
+  invoiceDate: row.issueDate ?? row.invoiceDate,
+  amount: row.taxExclusivelPrice ?? row.amount,
+  taxAmount: row.taxPrice ?? row.taxAmount,
+  totalAmount: row.taxInclusivePrice ?? row.totalAmount,
+  content: row.invoiceContent ?? row.content,
+  status: normalizeStatus(row.status),
+  stockInRecordIds: row.stockInRecordIds ?? "",
+  inboundBatches: formatInboundBatches(row.inboundBatches),
+});
+
+const toFormNumber = (val) => {
+  const n = Number(val);
+  return Number.isFinite(n) ? n : 0;
+};
+
+const resolveFormAmounts = (row) => {
+  let amount = toFormNumber(row.taxExclusivelPrice ?? row.amount);
+  let taxAmount = toFormNumber(row.taxPrice ?? row.taxAmount);
+  let totalAmount = toFormNumber(row.taxInclusivePrice ?? row.totalAmount);
+  const taxRate = toFormNumber(row.taxRate) || 13;
+
+  if (totalAmount > 0 && amount === 0 && taxAmount === 0) {
+    amount = Number((totalAmount / (1 + taxRate / 100)).toFixed(2));
+    taxAmount = Number((totalAmount - amount).toFixed(2));
+  } else if (totalAmount > 0 && amount > 0 && taxAmount === 0) {
+    taxAmount = Number((totalAmount - amount).toFixed(2));
+  } else if (amount > 0 && taxAmount === 0 && totalAmount === 0) {
+    taxAmount = Number((amount * taxRate / 100).toFixed(2));
+    totalAmount = Number((amount + taxAmount).toFixed(2));
+  } else if (amount > 0 && taxAmount > 0 && totalAmount === 0) {
+    totalAmount = Number((amount + taxAmount).toFixed(2));
+  }
+
+  return { amount, taxAmount, totalAmount };
+};
+
+const fillFormFromRow = (row) => {
+  const stockInRecordIds = parseStockInRecordIds(row.stockInRecordIds);
+  const { amount, taxAmount, totalAmount } = resolveFormAmounts(row);
+  Object.assign(form, {
+    invoiceNo: row.invoiceNo ?? row.invoiceNumber ?? "",
+    supplierId: row.supplierId,
+    invoiceDate: row.invoiceDate ?? row.issueDate ?? "",
+    invoiceType: row.invoiceType ?? "澧炲�肩◣涓撶敤鍙戠エ",
+    taxRate: row.taxRate ?? 13,
+    amount,
+    taxAmount,
+    totalAmount,
+    content: row.content ?? row.invoiceContent ?? "",
+    remark: row.remark ?? "",
+    stockInRecordIds,
+    inboundBatches: formatInboundBatches(row.inboundBatches),
+    storageAttachmentId: row.storageAttachmentId,
+    status: normalizeStatus(row.status),
+  });
+};
+
+const buildCancelPayload = (row) => ({
+  id: row.id,
+  invoiceNumber: row.invoiceNumber ?? row.invoiceNo,
+  taxRate: row.taxRate,
+  invoiceType: row.invoiceType,
+  issueDate: row.issueDate ?? row.invoiceDate,
+  taxExclusivelPrice: row.taxExclusivelPrice ?? row.amount,
+  taxPrice: row.taxPrice ?? row.taxAmount,
+  taxInclusivePrice: row.taxInclusivePrice ?? row.totalAmount,
+  remark: row.remark ?? "",
+  invoiceContent: row.invoiceContent ?? row.content,
+  supplierId: row.supplierId,
+  storageAttachmentId: row.storageAttachmentId,
+  stockInRecordIds: row.stockInRecordIds ?? "",
+  status: 1,
+});
+
+const buildSubmitPayload = () => ({
+  invoiceNumber: form.invoiceNo,
+  supplierId: form.supplierId,
+  issueDate: form.invoiceDate,
+  invoiceType: form.invoiceType,
+  taxRate: form.taxRate,
+  taxExclusivelPrice: form.amount,
+  taxPrice: form.taxAmount,
+  taxInclusivePrice: form.totalAmount,
+  invoiceContent: form.content,
+  remark: form.remark || "",
+  stockInRecordIds: (form.stockInRecordIds || []).join(","),
+  status: 0,
+  storageAttachmentId: form.storageAttachmentId,
+});
+
+const getSupplierList = () => {
+  getOptions().then((res) => {
+    if (res.code === 200) {
+      supplierList.value = res.data ?? [];
+    }
+  });
+};
+
+const appendFilterParams = (params) => {
+  if (filters.invoiceNumber) {
+    params.invoiceNumber = filters.invoiceNumber;
+  }
+  if (filters.supplierId) {
+    params.supplierId = filters.supplierId;
+  }
+  if (filters.dateRange?.length === 2) {
+    params.startDate = filters.dateRange[0];
+    params.endDate = filters.dateRange[1];
+  }
+  if (filters.status !== "" && filters.status != null) {
+    params.status = filters.status;
+  }
+  return params;
+};
+
+const buildListParams = () =>
+  appendFilterParams({
+    current: pagination.currentPage,
+    size: pagination.pageSize,
+  });
+
+const buildExportParams = () => appendFilterParams({});
+
+const handleExport = () => {
+  proxy.download(
+    "/accountPurchaseInvoice/exportAccountPurchaseInvoice",
+    buildExportParams(),
+    `杩涢」鍙戠エ_${Date.now()}.xlsx`
+  );
 };
 
 const getTableData = () => {
-  let result = [...mockData];
-  if (filters.invoiceCode) {
-    result = result.filter(item => item.invoiceCode.includes(filters.invoiceCode));
-  }
-  if (filters.invoiceNo) {
-    result = result.filter(item => item.invoiceNo.includes(filters.invoiceNo));
-  }
-  if (filters.supplierId) {
-    result = result.filter(item => item.supplierId === filters.supplierId);
-  }
-  if (filters.certifyStatus) {
-    result = result.filter(item => item.certifyStatus === filters.certifyStatus);
-  }
-  pagination.total = result.length;
-  dataList.value = result.slice((pagination.currentPage - 1) * pagination.pageSize, pagination.currentPage * pagination.pageSize);
+  tableLoading.value = true;
+  listPageAccountPurchaseInvoice(buildListParams())
+    .then((res) => {
+      if (res.code === 200) {
+        const records = res.data?.records ?? [];
+        dataList.value = records.map(normalizeTableRow);
+        pagination.total = res.data?.total ?? 0;
+      } else {
+        dataList.value = [];
+        pagination.total = 0;
+        ElMessage.error(res.msg || "鏌ヨ澶辫触");
+      }
+    })
+    .catch(() => {
+      dataList.value = [];
+      pagination.total = 0;
+      ElMessage.error("鏌ヨ澶辫触");
+    })
+    .finally(() => {
+      tableLoading.value = false;
+    });
 };
 
-const resetFilters = () => {
-  filters.invoiceCode = "";
-  filters.invoiceNo = "";
-  filters.supplierId = "";
-  filters.certifyStatus = "";
+const onSearch = () => {
   pagination.currentPage = 1;
   getTableData();
 };
 
-const changePage = ({ current, size }) => {
-  pagination.currentPage = current;
-  pagination.pageSize = size;
+const resetFilters = () => {
+  filters.invoiceNumber = "";
+  filters.supplierId = "";
+  filters.dateRange = [];
+  filters.status = "";
+  pagination.currentPage = 1;
   getTableData();
 };
 
-const handleSelectionChange = (selection) => {
-  selectedRows.value = selection;
+const changePage = ({ page, limit }) => {
+  pagination.currentPage = page;
+  pagination.pageSize = limit;
+  getTableData();
+};
+
+const closeDialog = () => {
+  dialogVisible.value = false;
+  isView.value = false;
+  inboundSelectVisible.value = false;
+};
+
+const resetForm = () => {
+  Object.assign(form, {
+    invoiceNo: "",
+    supplierId: "",
+    invoiceDate: new Date().toISOString().split("T")[0],
+    invoiceType: "澧炲�肩◣涓撶敤鍙戠エ",
+    taxRate: 13,
+    amount: 0,
+    taxAmount: 0,
+    totalAmount: 0,
+    content: "",
+    remark: "",
+    stockInRecordIds: [],
+    inboundBatches: "",
+    storageAttachmentId: undefined,
+    status: 0,
+  });
+  inboundBatchList.value = [];
+  inboundBatchOptions.value = [];
 };
 
 const add = () => {
-  isEdit.value = false;
+  isView.value = false;
   dialogTitle.value = "褰曞叆鍙戠エ";
-  Object.assign(form, {
-    invoiceCode: "",
-    invoiceNo: "",
-    supplierId: "",
-    invoiceDate: new Date().toISOString().split('T')[0],
-    amount: 0,
-    taxRate: 13,
-    taxAmount: 0,
-    totalAmount: 0,
-    certifyStatus: "uncertified",
-    certifyDate: "",
-    content: "",
-    remark: "",
-  });
-  dialogVisible.value = true;
-};
-
-const edit = (row) => {
-  isEdit.value = true;
-  currentId.value = row.id;
-  dialogTitle.value = "缂栬緫鍙戠エ";
-  Object.assign(form, row);
+  resetForm();
   dialogVisible.value = true;
 };
 
 const view = (row) => {
-  ElMessage.info(`鏌ョ湅鍙戠エ: ${row.invoiceCode}-${row.invoiceNo}`);
+  isView.value = true;
+  dialogTitle.value = "鏌ョ湅鍙戠エ";
+  fillFormFromRow(row);
+  if (row.supplierId) {
+    loadInboundBatches(row.supplierId, true, false);
+  }
+  dialogVisible.value = true;
 };
 
-const handleCertify = (row) => {
-  ElMessageBox.confirm("纭璁よ瘉璇ュ彂绁ㄥ悧锛�", "鎻愮ず", {
-    confirmButtonText: "纭",
+const handleCancel = (row) => {
+  ElMessageBox.confirm(`纭浣滃簾鍙戠エ銆�${row.invoiceNo ?? row.invoiceNumber}銆嶅悧锛焋, "浣滃簾纭", {
+    confirmButtonText: "纭畾",
     cancelButtonText: "鍙栨秷",
-    type: "info",
+    type: "warning",
   }).then(() => {
-    const index = mockData.findIndex(item => item.id === row.id);
-    if (index !== -1) {
-      mockData[index].certifyStatus = "certified";
-      mockData[index].certifyDate = new Date().toISOString().split('T')[0];
-    }
-    ElMessage.success("璁よ瘉鎴愬姛");
-    getTableData();
+    cancelAccountPurchaseInvoice(buildCancelPayload(row))
+      .then((res) => {
+        if (res.code === 200) {
+          ElMessage.success("浣滃簾鎴愬姛");
+          getTableData();
+        } else {
+          ElMessage.error(res.msg || "浣滃簾澶辫触");
+        }
+      })
+      .catch(() => {
+        ElMessage.error("浣滃簾澶辫触");
+      });
   });
 };
 
-const handleBatchCertify = () => {
-  ElMessageBox.confirm(`纭鎵归噺璁よ瘉閫変腑鐨� ${selectedRows.value.length} 寮犲彂绁ㄥ悧锛焋, "鎻愮ず", {
-    confirmButtonText: "纭",
+const handleDelete = (row) => {
+  ElMessageBox.confirm(`纭鍒犻櫎鍙戠エ銆�${row.invoiceNo ?? row.invoiceNumber}銆嶅悧锛焋, "鍒犻櫎纭", {
+    confirmButtonText: "纭畾",
     cancelButtonText: "鍙栨秷",
-    type: "info",
+    type: "warning",
   }).then(() => {
-    selectedRows.value.forEach(row => {
-      const index = mockData.findIndex(item => item.id === row.id);
-      if (index !== -1 && mockData[index].certifyStatus === "uncertified") {
-        mockData[index].certifyStatus = "certified";
-        mockData[index].certifyDate = new Date().toISOString().split('T')[0];
-      }
-    });
-    ElMessage.success("鎵归噺璁よ瘉鎴愬姛");
-    getTableData();
+    deleteAccountPurchaseInvoice([row.id])
+      .then((res) => {
+        if (res.code === 200) {
+          ElMessage.success("鍒犻櫎鎴愬姛");
+          getTableData();
+        } else {
+          ElMessage.error(res.msg || "鍒犻櫎澶辫触");
+        }
+      })
+      .catch(() => {
+        ElMessage.error("鍒犻櫎澶辫触");
+      });
   });
-};
-
-const handleOut = () => {
-  ElMessage.success("瀵煎嚭鎴愬姛");
 };
 
 const submitForm = () => {
-  formRef.value.validate((valid) => {
-    if (valid) {
-      const supplier = supplierList.find(item => item.id === form.supplierId);
-      if (isEdit.value) {
-        const index = mockData.findIndex(item => item.id === currentId.value);
-        if (index !== -1) {
-          mockData[index] = { ...mockData[index], ...form, supplierName: supplier?.name };
+  formRef.value?.validate((valid) => {
+    if (!valid) return;
+    submitLoading.value = true;
+    addAccountPurchaseInvoice(buildSubmitPayload())
+      .then((res) => {
+        if (res.code === 200) {
+          ElMessage.success("褰曞叆鎴愬姛");
+          closeDialog();
+          pagination.currentPage = 1;
+          getTableData();
+        } else {
+          ElMessage.error(res.msg || "褰曞叆澶辫触");
         }
-        ElMessage.success("缂栬緫鎴愬姛");
-      } else {
-        const newId = mockData.length > 0 ? Math.max(...mockData.map(item => item.id)) + 1 : 1;
-        mockData.push({ id: newId, ...form, supplierName: supplier?.name });
-        ElMessage.success("褰曞叆鎴愬姛");
-      }
-      dialogVisible.value = false;
-      getTableData();
-    }
+      })
+      .catch(() => {
+        ElMessage.error("褰曞叆澶辫触");
+      })
+      .finally(() => {
+        submitLoading.value = false;
+      });
   });
 };
 
+const ensureInboundOptionsForSelected = () => {
+  const ids = form.stockInRecordIds || [];
+  ids.forEach((id) => {
+    const exists = inboundBatchOptions.value.some((opt) => isSameInboundId(opt.value, id));
+    if (exists) return;
+    const fromList = inboundBatchList.value.find((row) => isSameInboundId(getInboundRowId(row), id));
+    if (fromList) {
+      const [option] = normalizeInboundBatchOptions([fromList]);
+      if (option) inboundBatchOptions.value.push(option);
+      return;
+    }
+    inboundBatchOptions.value.push({
+      label: String(id),
+      value: id,
+      inboundAmount: 0,
+    });
+  });
+};
+
+const restoreInboundTableSelection = () => {
+  nextTick(() => {
+    const table = inboundTableRef.value;
+    if (!table) return;
+    table.clearSelection();
+    const selectedIds = new Set((form.stockInRecordIds || []).map((id) => String(id)));
+    inboundBatchList.value.forEach((row) => {
+      const rowId = getInboundRowId(row);
+      if (rowId !== undefined && rowId !== null && selectedIds.has(String(rowId))) {
+        table.toggleRowSelection(row, true);
+      }
+    });
+  });
+};
+
+const loadInboundBatches = (supplierId, keepSelected = false, syncAmount = true) => {
+  if (!supplierId) {
+    inboundBatchList.value = [];
+    inboundBatchOptions.value = [];
+    if (!keepSelected) {
+      form.stockInRecordIds = [];
+      form.inboundBatches = "";
+      form.amount = 0;
+      form.taxAmount = 0;
+      form.totalAmount = 0;
+    }
+    return Promise.resolve();
+  }
+  inboundBatchLoading.value = true;
+  return getInboundBatchesBySupplier({ supplierId })
+    .then((res) => {
+      if (res.code === 200) {
+        const list = res.data?.records ?? res.data ?? [];
+        inboundBatchList.value = Array.isArray(list) ? list : [];
+        inboundBatchOptions.value = normalizeInboundBatchOptions(list);
+      } else {
+        inboundBatchList.value = [];
+        inboundBatchOptions.value = [];
+      }
+    })
+    .catch(() => {
+      inboundBatchList.value = [];
+      inboundBatchOptions.value = [];
+    })
+    .finally(() => {
+      inboundBatchLoading.value = false;
+      if (keepSelected) {
+        ensureInboundOptionsForSelected();
+        restoreInboundTableSelection();
+        if (syncAmount && !isView.value) {
+          syncInvoiceAmount();
+        }
+      }
+    });
+};
+
+const handleSupplierChange = (supplierId) => {
+  form.stockInRecordIds = [];
+  form.inboundBatches = "";
+  form.amount = 0;
+  form.taxAmount = 0;
+  form.totalAmount = 0;
+  loadInboundBatches(supplierId);
+};
+
+const handleInboundInputClick = () => {
+  if (isView.value) return;
+  openInboundSelectDialog();
+};
+
+const openInboundSelectDialog = () => {
+  if (!form.supplierId || isView.value) return;
+  inboundSelectVisible.value = true;
+  loadInboundBatches(form.supplierId, true).then(() => {
+    restoreInboundTableSelection();
+  });
+};
+
+const handleInboundDialogSelectionChange = (selection) => {
+  dialogInboundSelection.value = selection;
+};
+
+const confirmInboundSelection = () => {
+  if (dialogInboundSelection.value.length === 0) {
+    ElMessage.warning("璇疯嚦灏戦�夋嫨涓�鏉″叆搴撳崟");
+    return;
+  }
+  form.stockInRecordIds = dialogInboundSelection.value
+    .map((row) => getInboundRowId(row))
+    .filter((id) => id !== undefined && id !== null);
+  form.inboundBatches = dialogInboundSelection.value
+    .map((row) => row.inboundBatches ?? row.batchNo ?? "")
+    .filter(Boolean)
+    .join("銆�");
+  dialogInboundSelection.value.forEach((row) => {
+    const [option] = normalizeInboundBatchOptions([row]);
+    if (option && !inboundBatchOptions.value.some((opt) => isSameInboundId(opt.value, option.value))) {
+      inboundBatchOptions.value.push(option);
+    }
+  });
+  inboundSelectVisible.value = false;
+  syncInvoiceAmount();
+  formRef.value?.validateField("stockInRecordIds");
+};
+
+const handleInboundDialogClosed = () => {
+  dialogInboundSelection.value = [];
+};
+
 onMounted(() => {
+  getSupplierList();
   getTableData();
 });
 </script>
@@ -406,4 +938,8 @@
   color: #67c23a;
   font-weight: bold;
 }
+
+.inbound-batch-input :deep(.el-input__wrapper) {
+  cursor: pointer;
+}
 </style>

--
Gitblit v1.9.3