1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
<template>
  <view class="account-detail">
    <!-- 使用通用页面头部组件 -->
    <PageHeader title="编辑来票台账"
                @back="goBack" />
    <up-form @submit="submitForm"
             ref="formRef"
             label-width="120"
             :model="form">
      <up-form-item label="采购合同号"
                    prop="purchaseContractNumber">
        <up-input v-model="form.purchaseContractNumber"
                  placeholder="自动生成"
                  disabled />
      </up-form-item>
      <up-form-item label="销售合同号"
                    prop="salesContractNo">
        <up-input v-model="form.salesContractNo"
                  placeholder="自动生成"
                  disabled />
      </up-form-item>
      <up-form-item label="含税单价(元)"
                    prop="taxInclusiveUnitPrice">
        <up-input v-model="form.taxInclusiveUnitPrice"
                  placeholder="自动生成"
                  disabled />
      </up-form-item>
      <up-form-item label="创建时间"
                    prop="createdAt">
        <up-input v-model="form.createdAt"
                  placeholder="自动生成"
                  disabled />
      </up-form-item>
      <up-form-item label="发票号"
                    prop="invoiceNumber">
        <up-input v-model="form.invoiceNumber"
                  placeholder="请输入"
                  disabled />
      </up-form-item>
      <up-form-item label="来票数"
                    prop="ticketsNum"
                    required
                    :rules="rules.ticketsNum">
        <up-input v-model="form.ticketsNum"
                  type="number"
                  placeholder="请输入"
                  @blur="inputTicketsNum" />
      </up-form-item>
      <up-form-item label="本次来票金额(元)"
                    prop="ticketsAmount"
                    required
                    :rules="rules.ticketsAmount">
        <up-input v-model="form.ticketsAmount"
                  type="number"
                  placeholder="请输入"
                  @blur="inputTicketsAmount" />
      </up-form-item>
      <view class="tip-text">未来票数:{{ formatAmount(form.futureTickets) }} </view>
      <!-- 使用公共底部按钮组件 -->
      <FooterButtons show
                     cancelText="取消"
                     confirmText="保存"
                     @cancel="goBack"
                     @confirm="onSubmit" />
    </up-form>
  </view>
</template>
 
<script setup>
  import { ref, onMounted } from "vue";
  import dayjs from "dayjs";
  import useUserStore from "@/store/modules/user";
  import { getToken } from "@/utils/auth";
  import { invoiceLedgerSaveOrUpdate } from "@/api/salesManagement/invoiceLedger.js";
  import config from "@/config.js";
  import {
    getProductRecordById,
    updateRegistration,
  } from "@/api/procurementManagement/procurementInvoiceLedger";
  import PageHeader from "@/components/PageHeader.vue";
  import FooterButtons from "@/components/FooterButtons.vue";
 
  const userStore = useUserStore();
 
  const formRef = ref();
  let form = ref({
    salesLedgerId: "",
    customerId: "",
    invoiceNo: "",
    invoiceTotal: "",
    taxRate: "",
    invoicePerson: "",
    invoiceDate: "",
    customerName: "",
    fileList: [],
    createTime: "",
    taxInclusiveTotalPrice: "",
    taxInclusiveUnitPrice: "",
  });
  const fileList = ref([]);
  const currentId = ref("");
  const temFutureTickets = ref(0);
  const originalTicketsNum = ref(0); // 保存原始来票数
 
  // 表单校验规则
  const rules = {
    ticketsNum: [{ required: true, message: "请输入来票数", trigger: "blur" }],
    ticketsAmount: [
      { required: true, message: "请输入本次来票金额", trigger: "blur" },
    ],
  };
 
  const goBack = () => {
    uni.removeStorageSync("invoiceLedgerEditRow");
    uni.navigateBack();
  };
  const inputTicketsNum = () => {
    // 处理空值情况
    if (!form.value.ticketsNum || form.value.ticketsNum === "") {
      form.value.ticketsNum = 0;
      return;
    }
    
    // 确保含税单价存在且不为零
    if (
      !form.value.taxInclusiveUnitPrice ||
      Number(form.value.taxInclusiveUnitPrice) === 0
    ) {
      uni.showToast({
        title: "含税单价不能为零或未定义",
        icon: "none",
      });
      return;
    }
    
    const newTicketsNum = Number(form.value.ticketsNum) || 0;
    // 计算总可用票数:原始未来票数 + 原始来票数
    const totalAvailableTickets = Number(temFutureTickets.value) + Number(originalTicketsNum.value);
    
    // 验证来票数不能大于总可用票数
    if (newTicketsNum > totalAvailableTickets) {
      uni.showToast({
        title: "来票数不得大于总可用票数",
        icon: "none",
      });
      form.value.ticketsNum = totalAvailableTickets;
      // 重新计算未来票数
      const futureTickets = totalAvailableTickets - totalAvailableTickets;
      form.value.futureTickets = Number(futureTickets.toFixed(2));
      form.value.ticketsAmount = Number((totalAvailableTickets * Number(form.value.taxInclusiveUnitPrice)).toFixed(2));
      return;
    }
 
    // 确保所有数值都转换为数字类型进行计算
    const ticketsAmount =
      newTicketsNum * Number(form.value.taxInclusiveUnitPrice);
    // 计算未来票数:总可用票数 - 新来票数
    const futureTickets = totalAvailableTickets - newTicketsNum;
    form.value.futureTickets = Number(futureTickets.toFixed(2));
    form.value.ticketsAmount = Number(ticketsAmount.toFixed(2));
  };
  const inputTicketsAmount = () => {
    // 处理空值情况
    if (!form.value.ticketsAmount || form.value.ticketsAmount === "") {
      form.value.ticketsAmount = 0;
    }
    
    // 确保含税单价存在且不为零
    if (
      !form.value.taxInclusiveUnitPrice ||
      Number(form.value.taxInclusiveUnitPrice) === 0
    ) {
      uni.showToast({
        title: "含税单价不能为零或未定义",
        icon: "none",
      });
      return;
    }
 
    const newTicketsAmount = Number(form.value.ticketsAmount) || 0;
    // 计算总可用金额:原始未来票数 + 原始来票数
    const totalAvailableTickets = Number(temFutureTickets.value) + Number(originalTicketsNum.value);
    const totalAvailableAmount = totalAvailableTickets * Number(form.value.taxInclusiveUnitPrice);
 
    if (newTicketsAmount > totalAvailableAmount) {
      uni.showToast({
        title: "本次来票金额不得大于总金额",
        icon: "none",
      });
      form.value.ticketsAmount = totalAvailableAmount.toFixed(2);
      const ticketsNum =
        Number(form.value.ticketsAmount) /
        Number(form.value.taxInclusiveUnitPrice);
      form.value.ticketsNum = Number(ticketsNum.toFixed(2));
      // 更新未来票数
      const futureTickets = totalAvailableTickets - form.value.ticketsNum;
      form.value.futureTickets = Number(futureTickets.toFixed(2));
      return;
    }
 
    // 确保所有数值都转换为数字类型进行计算
    const ticketsNum =
      newTicketsAmount / Number(form.value.taxInclusiveUnitPrice);
    form.value.ticketsNum = Number(ticketsNum.toFixed(2));
    // 更新未来票数
    const futureTickets = totalAvailableTickets - form.value.ticketsNum;
    form.value.futureTickets = Number(futureTickets.toFixed(2));
  };
  const formatAmount = val => {
    if (val === undefined || val === null || val === "") return "0.00";
    const num = Number(val);
    if (Number.isNaN(num)) return "0.00";
    return num.toFixed(2);
  };
 
  const loadDetail = async (id, purchaseLedgerId, productModelId) => {
    try {
      uni.showLoading({
        title: "加载中...",
      });
      const res = await getProductRecordById({
        id: id,
        purchaseLedgerId: purchaseLedgerId,
        productModelId: productModelId,
      });
      const data = res?.data || res;
      form.value = { ...data };
      temFutureTickets.value = data.futureTickets;
      originalTicketsNum.value = Number(data.ticketsNum) || 0; // 保存原始来票数
      fileList.value = data?.fileList || [];
      if (!form.value.invoicePerson) {
        form.value.invoicePerson = userStore.nickName;
      }
      if (!form.value.invoiceDate) {
        form.value.invoiceDate = dayjs().format("YYYY-MM-DD");
      }
      uni.hideLoading();
    } catch (e) {
      uni.hideLoading();
      uni.showToast({
        title: "加载失败",
        icon: "none",
      });
    }
  };
 
  const submitForm = async () => {
    try {
      // 提交表单的具体逻辑
      await updateRegistration(form.value);
      uni.showToast({
        title: "提交成功",
        icon: "success",
      });
      setTimeout(() => {
        goBack();
      }, 800);
    } catch (e) {
      uni.showToast({
        title: "提交失败,请重试",
        icon: "none",
      });
    }
  };
 
  // 表单提交
  const onSubmit = async () => {
    if (!formRef.value) {
      console.log("表单引用不存在");
      return;
    }
    
    try {
      // 先调用 validate 方法
      const validateResult = formRef.value.validate();
      
      // 如果 validate 返回 undefined 或 null,直接提交
      if (validateResult === undefined || validateResult === null) {
        submitForm();
        return;
      }
      
      // 如果返回 Promise,使用 await 和 catch
      if (validateResult && typeof validateResult.then === 'function') {
        const valid = await validateResult.catch(() => false);
        if (valid) {
          // 表单验证通过,提交表单
          submitForm();
        } else {
          // 表单验证失败
          console.log("表单验证失败");
        }
      } else {
        // 如果返回布尔值,直接判断
        if (validateResult) {
          submitForm();
        } else {
          console.log("表单验证失败");
        }
      }
    } catch (error) {
      // 如果 validate 方法不存在或抛出错误,直接提交
      console.log("表单验证失败", error);
      submitForm();
    }
  };
  const purchaseLedgerId = ref("");
  const productModelId = ref({});
 
  onMounted(() => {
    const rowStr = uni.getStorageSync("invoiceLedgerEditRow");
    if (rowStr) {
      try {
        const row = JSON.parse(rowStr);
        currentId.value = row.id;
        purchaseLedgerId.value = row.purchaseLedgerId;
        productModelId.value = row.productModelId;
        loadDetail(currentId.value, purchaseLedgerId.value, productModelId.value);
      } catch (e) {
        // ignore
      }
    }
  });
</script>
 
<style scoped lang="scss">
  @import "@/static/scss/form-common.scss";
</style>