gaoluyang
6 天以前 adeb8b768926ed50a3fb0857f366d6a0308d2cc0
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
<template>
  <view class="account-detail">
    <!-- 使用通用页面头部组件 -->
        <PageHeader title="台账详情" @back="goBack" />
 
         <!-- 表单区域 -->
        <u-form @submit="onSubmit" label-width="110" input-align="right" style="margin-top: 10px" error-message-align="right">
            <u-form-item label="销售合同号" prop="salesContractNo" border-bottom>
                <u-input v-model="form.salesContractNo" placeholder="自动生成" disabled />
            </u-form-item>
            <u-form-item
                label="业务员"
                prop="salesman"
                required
                border-bottom
            >
                <u-input
                    v-model="form.salesman"
                    readonly
                    placeholder="点击选择业务员"
                    @click="showPicker = true"
                />
            </u-form-item>
            <u-form-item label="客户合同号" prop="customerContractNo" required border-bottom>
                <u-input
                    v-model="form.customerContractNo"
                    placeholder="请输入客户合同号"
                />
            </u-form-item>
            <u-form-item
                label="客户名称"
                prop="customerName"
                required
                border-bottom
            >
                <u-input
                    v-model="form.customerName"
                    readonly
                    placeholder="点击选择客户"
                    @click="showCustomerPicker = true"
                />
            </u-form-item>
            <u-form-item label="项目名称" prop="projectName" required border-bottom>
                <u-input v-model="form.projectName" placeholder="请输入项目名称" />
            </u-form-item>
            <u-form-item
                label="签订日期"
                prop="executionDate"
                required
                border-bottom
            >
                <u-input
                    v-model="form.executionDate"
                    readonly
                    placeholder="点击选择时间"
                    @click="showDatePicker = true"
                />
            </u-form-item>
            <u-popup v-model="showDatePicker" mode="bottom">
                <u-datetime-picker
                    v-model="pickerDateValue"
                    @confirm="onDateConfirm"
                    @cancel="showDatePicker = false"
                />
            </u-popup>
            <u-form-item label="付款方式" prop="paymentMethod" border-bottom>
                <u-input v-model="form.paymentMethod" placeholder="请输入付款方式" />
            </u-form-item>
            <u-form-item label="录入人" prop="entryPersonName" border-bottom>
                <u-input v-model="form.entryPersonName" placeholder="请输入" disabled />
            </u-form-item>
            <u-form-item label="录入日期" prop="entryDate" border-bottom>
                <u-input v-model="form.entryDate" placeholder="请输入" disabled />
            </u-form-item>
            <!-- 业务员选择弹窗 -->
            <u-popup v-model="showPicker" mode="bottom">
                <view class="picker-header">
                    <view class="picker-cancel" @click="showPicker = false">取消</view>
                    <view class="picker-title">选择业务员</view>
                    <view class="picker-confirm" @click="confirmSalesman">确定</view>
                </view>
                <u-picker
                    :columns="userList"
                    v-model="pickerValue"
                    @change="onPickerChange"
                />
            </u-popup>
            
            <!-- 客户选择弹窗 -->
            <u-popup v-model="showCustomerPicker" mode="bottom">
                <view class="picker-header">
                    <view class="picker-cancel" @click="showCustomerPicker = false">取消</view>
                    <view class="picker-title">选择客户</view>
                    <view class="picker-confirm" @click="confirmCustomer">确定</view>
                </view>
                <u-picker
                    :columns="customerOption"
                    v-model="pickerCustomerValue"
                    @change="onCustomerPickerChange"
                />
            </u-popup>
            
            <!-- 产品大类选择器 -->
            <u-popup v-model="showCategoryPicker" mode="bottom">
                <!-- 头部按钮区域 -->
                <view class="popup-header">
                    <view @click="showCategoryPicker = false" class="cancelButton">取消</view>
                    <view @click="confirmCategorySelection" class="confirmButton">确定</view>
                </view>
                <up-tree
                    :data="productOptions"
                    :props="defaultProps"
                    show-checkbox
                    default-expand-all
                    check-strictly
                    @check-change="onCategoryConfirm"
                />
            </u-popup>
            
            <!-- 规格型号选择器 -->
            <u-popup v-model="showSpecificationPicker" mode="bottom">
                <u-picker
                    :columns="modelOptions"
                    v-model="pickerSpecificationValue"
                    @confirm="onSpecificationConfirm"
                    @cancel="showSpecificationPicker = false"
                />
            </u-popup>
            
            <!-- 税率选择器 -->
            <u-popup v-model="showTaxRatePicker" mode="bottom">
                <u-picker
                    :columns="taxRateOptions"
                    v-model="pickerTaxRateValue"
                    @confirm="onTaxRateConfirm"
                    @cancel="showTaxRatePicker = false"
                />
            </u-popup>
            
            <!-- 发票类型选择器 -->
            <u-popup v-model="showInvoiceTypePicker" mode="bottom">
                <u-picker
                    :columns="invoiceTypeOptions"
                    v-model="pickerInvoiceTypeValue"
                    @confirm="onInvoiceTypeConfirm"
                    @cancel="showInvoiceTypePicker = false"
                />
            </u-popup>
            <!-- 产品信息 -->
            <view class="product-section">
                <view class="section-header">
                    <text class="section-title">产品信息</text>
                    <u-button type="primary" size="small" @click="addProduct" class="add-btn" v-if="operationType !== 'view'">
                        <u-icon name="plus" size="14" />
                        新增
                    </u-button>
                </view>
                <view class="product-card" v-for="(product, idx) in productData" :key="idx">
                    <!-- 产品类 -->
                    <view class="product-header">
                        <view class="product-title">
                            <u-icon name="file-text" color="#2979ff" size="15" />
                            <text class="product-productCategory">产品 {{ idx + 1 }}</text>
                        </view>
                        <!-- 操作按钮 -->
                        <view class="product-actions" v-if="operationType !== 'view'">
                            <u-button type="error" size="mini" @click="removeProduct(idx)" class="del-btn">
                                <u-icon name="trash" size="12" />
                                删除
                            </u-button>
                        </view>
                    </view>
                    
                    <!-- 产品信息表单 -->
                    <view class="product-form">
                        <!-- 产品大类 -->
                        <u-form-item
                            label="产品大类"
                            prop="productCategory"
                            required
                            border-bottom
                        >
                            <u-input
                                v-model="product.productCategory"
                                readonly
                                placeholder="请选择"
                                @click="openCategoryPicker(idx)"
                            />
                        </u-form-item>
                        
                        <!-- 规格型号 -->
                        <u-form-item
                            label="规格型号"
                            prop="specificationModel"
                            required
                            border-bottom
                        >
                            <u-input
                                v-model="product.specificationModel"
                                readonly
                                placeholder="请选择"
                                @click="openSpecificationPicker(idx)"
                            />
                        </u-form-item>
                        
                        <!-- 单位 -->
                        <u-form-item
                            label="单位"
                            prop="unit"
                            required
                            border-bottom
                        >
                            <u-input
                                v-model="product.unit"
                                placeholder="请输入"
                            />
                        </u-form-item>
                        
                        <!-- 税率 -->
                        <u-form-item
                            label="税率(%)"
                            prop="taxRate"
                            required
                            border-bottom
                        >
                            <u-input
                                v-model="product.taxRate"
                                readonly
                                placeholder="请选择"
                                @click="openTaxRatePicker(idx)"
                            />
                        </u-form-item>
                        
                        <!-- 含税单价 -->
                        <u-form-item
                            label="含税单价(元)"
                            prop="taxInclusiveUnitPrice"
                            required
                            border-bottom
                        >
                            <u-input
                                v-model="product.taxInclusiveUnitPrice"
                                type="number"
                                placeholder="请输入"
                                @blur="formatTaxPrice(idx)"
                            />
                        </u-form-item>
                        
                        <!-- 数量 -->
                        <u-form-item
                            label="数量"
                            prop="quantity"
                            required
                            border-bottom
                        >
                            <u-input
                                v-model="product.quantity"
                                type="number"
                                placeholder="请输入"
                                @blur="formatAmount(idx)"
                            />
                        </u-form-item>
                        
                        <!-- 含税总价 -->
                        <u-form-item
                            label="含税总价(元)"
                            prop="taxInclusiveTotalPrice"
                            required
                            border-bottom
                        >
                            <u-input
                                v-model="product.taxInclusiveTotalPrice"
                                type="number"
                                placeholder="请输入"
                                @blur="formatTaxTotal(idx)"
                            />
                        </u-form-item>
                        
                        <!-- 不含税总价 -->
                        <u-form-item
                            label="不含税总价(元)"
                            prop="taxExclusiveTotalPrice"
                            required
                            border-bottom
                        >
                            <u-input
                                v-model="product.taxExclusiveTotalPrice"
                                type="number"
                                placeholder="请输入"
                                @blur="formatNoTaxTotal(idx)"
                            />
                        </u-form-item>
                        
                        <!-- 发票类型 -->
                        <u-form-item
                            label="发票类型"
                            prop="invoiceType"
                            required
                            border-bottom
                        >
                            <u-input
                                v-model="product.invoiceType"
                                readonly
                                placeholder="请选择"
                                @click="openInvoiceTypePicker(idx)"
                            />
                        </u-form-item>
                    </view>
                </view>
            </view>
        </u-form>
        
        <!-- 使用公共底部按钮组件 -->
        <FooterButtons
            :show="operationType !== 'view'"
            cancelText="取消"
            confirmText="保存"
            @cancel="goBack"
            @confirm="onSubmit"
        />
  </view>
</template>
 
<script setup>
import {onMounted, ref} from 'vue';
import {userListNoPage} from "@/api/system/user";
import {
    addOrUpdateSalesLedger,
    addOrUpdateSalesLedgerProduct,
    customerList,
    getSalesLedgerWithProducts,
    modelList,
    productTreeList
} from "@/api/salesManagement/salesLedger";
import useUserStore from "@/store/modules/user";
import {calculateTaxExclusiveTotalPrice} from "@/utils/summarizeTable";
import PageHeader from '@/components/PageHeader.vue';
import FooterButtons from '@/components/FooterButtons.vue';
 
// 获取页面参数
const operationType = ref('');
const editData = ref(null);
 
const userStore = useUserStore()
const form = ref({
    id: '',
  salesContractNo: '',
    customerContractNo: '',
    customerId: '',
    customerName: '',
    projectName: '',
    executionDate: '',
  paymentMethod: '',
    entryPerson: '',
    entryPersonName: '',
    entryDate: '',
});
const pickerValue = ref(['']);
const pickerDateValue = ref([]);
const showPicker = ref(false);
const showDatePicker = ref(false);
const pickerCustomerValue = ref(['']);
const showCustomerPicker = ref(false);
const userList = ref([]);
const customerOption = ref([]);
const productData = ref([]);
 
// 选择器相关变量
const showCategoryPicker = ref(false);
const showSpecificationPicker = ref(false);
const showTaxRatePicker = ref(false);
const showInvoiceTypePicker = ref(false);
const pickerCategoryValue = ref(['']);
const pickerSpecificationValue = ref(['']);
const pickerTaxRateValue = ref(['']);
const pickerInvoiceTypeValue = ref(['']);
 
// 临时存储选择器选中的值
const tempSalesmanValue = ref('');
const tempCustomerValue = ref('');
const selectedSalesman = ref(null);
const selectedCustomer = ref(null);
const currentProductIndex = ref(0);
 
// 选项数据
const productOptions = ref([]);
const selectedCategoryNode = ref(null);
const defaultProps = ref({
    children: 'children',
    label: 'label',
    nodeKey: 'id'
});
 
const modelOptions = ref([]);
// 防止循环计算的标志
// const isCalculating = ref(false);
const taxRateOptions = ref([
  { text: '1', value: '1' },
  { text: '6', value: '6' },
  { text: '13', value: '13' },
]);
 
const invoiceTypeOptions = ref([
  { text: '增普票', value: '增普票' },
  { text: '增专票', value: '增专票' },
]);
 
const addProduct = () => {
    if (productData.value === null) {
        productData.value = []
    }
    productData.value.push({
    productCategory: '',
    specificationModel: '',
        productModelId: '',
    unit: '',
    taxRate: '',
    taxInclusiveUnitPrice: '',
    quantity: '',
    taxInclusiveTotalPrice: '',
    taxExclusiveTotalPrice: '',
    invoiceType: ''
  });
};
// 业务员选择器变化事件
const onPickerChange = ({ selectedValues, selectedOptions }) => {
    selectedSalesman.value = selectedOptions[0];
    tempSalesmanValue.value = {
        text: selectedOptions[0]?.text,
        value: selectedOptions[0]?.value
    };
};
 
// 确认选择业务员
const confirmSalesman = () => {
    if (selectedSalesman.value) {
        form.value.salesman = selectedSalesman.value.text;
        pickerValue.value = [selectedSalesman.value.value];
    }
    showPicker.value = false;
};
 
// 客户选择器变化事件
const onCustomerPickerChange = ({ selectedValues, selectedOptions }) => {
    selectedCustomer.value = selectedOptions[0];
    tempCustomerValue.value = {
        text: selectedOptions[0]?.text,
        value: selectedOptions[0]?.value
    };
};
 
// 确认选择客户
const confirmCustomer = () => {
    if (selectedCustomer.value) {
        form.value.customerName = selectedCustomer.value.text;
        form.value.customerId = selectedCustomer.value.value;
        pickerCustomerValue.value = [selectedCustomer.value.value];
    }
    showCustomerPicker.value = false;
};
 
// 修改原有的确认方法(保持兼容性)
const onConfirm = ({ selectedValues, selectedOptions }) => {
    if (selectedOptions && selectedOptions[0]) {
        form.value.salesman = selectedOptions[0].text;
        pickerValue.value = [selectedValues[0]];
    }
    showPicker.value = false;
};
 
const onCustomerConfirm = ({ selectedValues, selectedOptions }) => {
    if (selectedOptions && selectedOptions[0]) {
        form.value.customerName = selectedOptions[0].text;
        form.value.customerId = selectedOptions[0].value;
        pickerCustomerValue.value = [selectedValues[0]];
    }
    showCustomerPicker.value = false;
};
const onDateConfirm = ({ selectedValues }) => {
    form.value.executionDate = selectedValues.join('-');
    pickerDateValue.value = selectedValues;
    showDatePicker.value = false;
};
const removeProduct = (idx) => {
    productData.value.splice(idx, 1);
};
 
// 显示选择器
const openCategoryPicker = (idx) => {
  currentProductIndex.value = idx;
  showCategoryPicker.value = true;
};
 
const openSpecificationPicker = (idx) => {
  currentProductIndex.value = idx;
  showSpecificationPicker.value = true;
};
 
const openTaxRatePicker = (idx) => {
  currentProductIndex.value = idx;
  showTaxRatePicker.value = true;
};
 
const openInvoiceTypePicker = (idx) => {
  currentProductIndex.value = idx;
  showInvoiceTypePicker.value = true;
};
 
// 选择器确认事件
const onCategoryConfirm = (node) => {
    // 获取选中的节点信息
    console.log('selected node---', node);
    // 存储选中的节点,用于确认时获取数据
    selectedCategoryNode.value = node;
};
 
// 确认产品大类选择
const confirmCategorySelection = () => {
    if (selectedCategoryNode.value) {
        // 设置选中的产品大类
        productData.value[currentProductIndex.value].productCategory = selectedCategoryNode.value.label;
        const id = selectedCategoryNode.value.id
        // 重置选中的节点
        selectedCategoryNode.value = null;
        productData.value[currentProductIndex.value].specificationModel = ''
        productData.value[currentProductIndex.value].productModelId = ''
        productData.value[currentProductIndex.value].pickerSpecificationValue = ['']
        getModels(id)
    }
    showCategoryPicker.value = false;
};
// 获取规格型号
const getModels = (value) => {
    modelList({ id: value }).then((res) => {
        modelOptions.value = res.map(user => ({
            text: user.model,
            value: user.id,
            unit: user.unit,
        }));
    });
};
// 选择规格型号
const onSpecificationConfirm = ({ selectedValues, selectedOptions }) => {
    productData.value[currentProductIndex.value].specificationModel = selectedOptions[0]?.text;
    productData.value[currentProductIndex.value].productModelId = selectedOptions[0]?.value;
    productData.value[currentProductIndex.value].unit = selectedOptions[0]?.unit;
  pickerSpecificationValue.value = [selectedValues[0]];
  showSpecificationPicker.value = false;
};
// 选择税率
const onTaxRateConfirm = ({ selectedValues, selectedOptions }) => {
    productData.value[currentProductIndex.value].taxRate = selectedOptions[0]?.value;
  pickerTaxRateValue.value = [selectedValues[0]];
  showTaxRatePicker.value = false;
    // if (isCalculating.value) return;
    const inclusiveTotalPrice = parseFloat(productData.value[currentProductIndex.value].taxInclusiveTotalPrice);
    const taxRate = parseFloat(productData.value[currentProductIndex.value].taxRate);
    if (!inclusiveTotalPrice || !taxRate) {
        return;
    }
    // isCalculating.value = true;
    // 计算不含税总价
    productData.value[currentProductIndex.value].taxExclusiveTotalPrice =
        calculateTaxExclusiveTotalPrice(
            inclusiveTotalPrice,
            taxRate
        );
    // isCalculating.value = false;
};
 
const onInvoiceTypeConfirm = ({ selectedValues, selectedOptions }) => {
    productData.value[currentProductIndex.value].invoiceType = selectedOptions[0]?.text;
  pickerInvoiceTypeValue.value = [selectedValues[0]];
  showInvoiceTypePicker.value = false;
};
 
// 格式化函数 - 固定两位小数
const formatTaxPrice = (idx) => {
  if (productData.value[idx].taxInclusiveUnitPrice) {
    const value = parseFloat(productData.value[idx].taxInclusiveUnitPrice);
    if (!isNaN(value)) {
            productData.value[idx].taxInclusiveUnitPrice = value.toFixed(2);
    }
  }
    if (!productData.value[currentProductIndex.value].taxRate) {
        uni.showToast({
            title: '请先选择税率',
            icon: 'none'
        });
        return;
    }
    const quantity = parseFloat(productData.value[currentProductIndex.value].quantity);
    const unitPrice = parseFloat(productData.value[currentProductIndex.value].taxInclusiveUnitPrice);
    
    if (!quantity || quantity <= 0 || !unitPrice) {
        return;
    }
    // 计算含税总价
    productData.value[currentProductIndex.value].taxInclusiveTotalPrice = (unitPrice * quantity).toFixed(2);
    
    // 如果有税率,计算不含税总价
    if (productData.value[currentProductIndex.value].taxRate) {
        productData.value[currentProductIndex.value].taxExclusiveTotalPrice =
            calculateTaxExclusiveTotalPrice(
                productData.value[currentProductIndex.value].taxInclusiveTotalPrice,
                productData.value[currentProductIndex.value].taxRate
            );
    }
};
// 数量输入框失焦
const formatAmount = (idx) => {
  if (productData.value[idx].quantity) {
    const value = parseFloat(productData.value[idx].quantity);
    if (!isNaN(value)) {
            productData.value[idx].quantity = value.toFixed(2);
    }
  }
    if (!productData.value[currentProductIndex.value].taxRate) {
        uni.showToast({
            title: '请先选择税率',
            icon: 'none'
        });
        return;
    }
    const quantity = parseFloat(productData.value[currentProductIndex.value].quantity);
    const unitPrice = parseFloat(productData.value[currentProductIndex.value].taxInclusiveUnitPrice);
    
    if (!quantity || quantity <= 0 || !unitPrice) {
        return;
    }
    // 计算含税总价
    productData.value[currentProductIndex.value].taxInclusiveTotalPrice = (unitPrice * quantity).toFixed(2);
    // 如果有税率,计算不含税总价
    if (productData.value[currentProductIndex.value].taxRate) {
        productData.value[currentProductIndex.value].taxExclusiveTotalPrice =
            calculateTaxExclusiveTotalPrice(
                productData.value[currentProductIndex.value].taxInclusiveTotalPrice,
                productData.value[currentProductIndex.value].taxRate
            );
    }
};
// 含税总价失焦,根据含税总价计算含税单价和数量
const formatTaxTotal = (idx) => {
  if (productData.value[idx].taxInclusiveTotalPrice) {
    const value = parseFloat(productData.value[idx].taxInclusiveTotalPrice);
    if (!isNaN(value)) {
            productData.value[idx].taxInclusiveTotalPrice = value.toFixed(2);
    }
  }
    const totalPrice = parseFloat(productData.value[currentProductIndex.value].taxInclusiveTotalPrice);
    const quantity = parseFloat(productData.value[currentProductIndex.value].quantity);
    
    if (!totalPrice || !quantity || quantity <= 0) {
        return;
    }
    // 计算含税单价 = 含税总价 / 数量
    productData.value[currentProductIndex.value].taxInclusiveUnitPrice = (totalPrice / quantity).toFixed(2);
    // 如果有税率,计算不含税总价
    if (productData.value[currentProductIndex.value].taxRate) {
        productData.value[currentProductIndex.value].taxExclusiveTotalPrice =
            calculateTaxExclusiveTotalPrice(
                totalPrice,
                productData.value[currentProductIndex.value].taxRate
            );
    }
};
// 不含税总价失焦, 根据不含税总价计算含税单价和数量
const formatNoTaxTotal = (idx) => {
  if (productData.value[idx].taxExclusiveTotalPrice) {
    const value = parseFloat(productData.value[idx].taxExclusiveTotalPrice);
    if (!isNaN(value)) {
            productData.value[idx].taxExclusiveTotalPrice = value.toFixed(2);
    }
  }
    if (!productData.value[currentProductIndex.value].taxRate) {
        uni.showToast({
            title: '请先选择税率',
            icon: 'none'
        });
        return;
    }
    const exclusiveTotalPrice = parseFloat(productData.value[currentProductIndex.value].taxExclusiveTotalPrice);
    const quantity = parseFloat(productData.value[currentProductIndex.value].quantity);
    const taxRate = parseFloat(productData.value[currentProductIndex.value].taxRate);
    if (!exclusiveTotalPrice || !quantity || quantity <= 0 || !taxRate) {
        return;
    }
    // 先计算含税总价 = 不含税总价 / (1 - 税率/100)
    const taxRateDecimal = taxRate / 100;
    const inclusiveTotalPrice = exclusiveTotalPrice / (1 - taxRateDecimal);
    productData.value[currentProductIndex.value].taxInclusiveTotalPrice = inclusiveTotalPrice.toFixed(2);
    // 计算含税单价 = 含税总价 / 数量
    productData.value[currentProductIndex.value].taxInclusiveUnitPrice = (inclusiveTotalPrice / quantity).toFixed(2);
};
const goBack = () => {
    // 清理本地存储的数据
    uni.removeStorageSync('operationType');
    uni.removeStorageSync('editData');
    uni.navigateBack();
};
const onSubmit = () => {
    if (productData.value !== null && productData.value.length > 0) {
        form.value.productData = JSON.parse(JSON.stringify(productData.value));
    } else {
        uni.showToast({
            title: '请添加产品信息',
            icon: 'none'
        });
        return
    }
    form.value.type = 1;
    addOrUpdateSalesLedger(form.value).then((res) => {
        uni.showToast({
            title: '提交成功',
            icon: 'success',
        });
        goBack();
    });
};
const setUserInfo = () => {
    form.value.entryPerson = userStore.id;
    form.value.entryPersonName = userStore.nickName;
    // 设置当天日期
    const today = new Date()
    const year = today.getFullYear()
    const month = String(today.getMonth() + 1).padStart(2, '0')
    const day = String(today.getDate()).padStart(2, '0')
    form.value.entryDate = `${year}-${month}-${day}`
    pickerDateValue.value = [year.toString(), month.toString(), day.toString()]
}
// 填充表单数据(编辑模式)
const fillFormData = () => {
  if (!editData.value) return;
    getSalesLedgerWithProducts({ id: editData.value.id, type: 1 }).then((res) => {
        productData.value = res.productData;
    });
    console.log(editData.value)
  // 填充基本信息
  form.value.salesContractNo = editData.value.salesContractNo || '';
  form.value.customerContractNo = editData.value.customerContractNo || '';
  form.value.customerName = editData.value.customerName || '';
  form.value.projectName = editData.value.projectName || '';
  form.value.executionDate = editData.value.executionDate || '';
  form.value.paymentMethod = editData.value.paymentMethod || '';
  form.value.salesman = editData.value.salesman || '';
  form.value.entryPerson = editData.value.entryPerson || '';
  form.value.entryPersonName = editData.value.entryPersonName || '';
  form.value.entryDate = editData.value.entryDate || '';
  form.value.id = editData.value.id || '';
  form.value.customerId = editData.value.customerId || '';
    
  // 设置业务员选择器的值
  if (editData.value.salesman) {
    const salesmanIndex = userList.value.findIndex(user => user.text === editData.value.salesman);
    if (salesmanIndex !== -1) {
      pickerValue.value = [userList.value[salesmanIndex].value];
    }
  }
  
  // 设置客户选择器的值
  if (editData.value.customerName) {
    const customerIndex = customerOption.value.findIndex(customer => customer.text === editData.value.customerName);
    if (customerIndex !== -1) {
      pickerCustomerValue.value = [customerOption.value[customerIndex].value]
    }
  }
  
  // 设置日期选择器的值
  if (editData.value.executionDate) {
        pickerDateValue.value = editData.value.executionDate.split('-').map(num => parseInt(num, 10))
        console.log(pickerDateValue.value)
    }
};
const getUserList = () => {
    userListNoPage().then((res) => {
        // 确保数据格式正确
        userList.value = [res.data.map(user => ({
            text: user.nickName,
            value: user.nickName
        }))];
    })
}
const getCustomerList = () => {
    customerList().then((res) => {
        // 确保数据格式正确
        customerOption.value = [res.map(item => ({
            text: item.customerName,
            value: item.id
        }))];
    })
}
const convertIdToValue = (data) => {
    // 如果传入的不是数组,则返回空数组
    if (!Array.isArray(data)) {
        return [];
    }
    // 递归映射函数
    return data.map(item => {
        // 创建新对象,映射字段
        const mappedItem = {
            label: item.label, // 关键:将 label 映射为 text
            id: item.id,       // 保留 id
        };
        // 如果存在 children 数组,则递归处理
        if (item.children && Array.isArray(item.children) && item.children.length > 0) {
            mappedItem.children = convertIdToValue(item.children);
        }
        return mappedItem;
    });
};
// 获取产品大类tree数据
const getProductOptions = () => {
    productTreeList().then((res) => {
        productOptions.value = convertIdToValue(res);
    });
};
onMounted(() => {
    // 获取页面参数
    operationType.value = uni.getStorageSync('operationType') || '';
    
    // 获取人员列表
    getUserList()
    // 获取客户列表
    getCustomerList()
    // 获取产品大类tree数据
    getProductOptions()
    // 赋值默认信息
    if (operationType.value === 'add') {
        setUserInfo()
    }
    
    // 获取编辑数据并填充表单
    const editDataStr = uni.getStorageSync('editData');
    if (editDataStr) {
        try {
            editData.value = JSON.parse(editDataStr);
            // 如果是编辑模式,等待数据加载完成后填充表单数据
            if (operationType.value !== 'add' && editData.value) {
                // 使用 nextTick 确保数据加载完成后再填充
                setTimeout(() => {
                    fillFormData();
                }, 100);
            }
        } catch (error) {
            console.error('解析编辑数据失败:', error);
        }
    }
});
</script>
 
<style scoped lang="scss">
.account-detail {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 5rem;
}
 
.header {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 1rem 1.25rem;
  border-bottom: 0.0625rem solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
    /* 兼容 iOS 刘海/灵动岛安全区 */
    padding-top: env(safe-area-inset-top);
}
 
.title {
  flex: 1;
  text-align: center;
  font-size: 1.125rem;
  font-weight: 600;
  color: #333;
}
 
.form-section {
    margin-top: 1rem;
}
.van-field {
    height: 3.4rem;
}
.van-cell {
    align-items: center;
}
.product-section {
  background: #fff;
    margin-top: 1rem;
  padding: 1rem;
  box-shadow: 0 0.125rem 0.5rem rgba(0,0,0,0.04);
}
 
.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1rem;
}
 
.section-title {
  font-size: 1rem;
  font-weight: 600;
  color: #333;
}
 
.product-card {
    background: #FFFFFF;
    box-shadow: 0 0 1.25rem 0 rgba(0,57,117,0.08);
    border-radius: 0.5rem 0.5rem 0.5rem 0.5rem;
  padding: 1rem 0.5rem 0 0.5rem;
  position: relative;
}
 
.product-header {
  display: flex;
  align-items: center;
    justify-content: space-between;
  padding: 0 0.5rem 0.75rem 0.5rem;
  border-bottom: 0.0625rem solid #e8e8e8;
}
 
.product-productCategory {
  margin-left: 0.5rem;
  font-size: 0.875rem;
  font-weight: 500;
  color: #333;
}
 
.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.75rem;
  margin-bottom: 1rem;
}
 
.info-item {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}
 
.info-label {
  font-size: 0.75rem;
  color: #666;
  font-weight: 400;
}
 
.info-value {
  font-size: 0.875rem;
  color: #333;
  font-weight: 500;
}
 
.info-value.highlight {
  color: #2979ff;
  font-weight: 600;
}
 
.product-form {
  margin-bottom: 1rem;
}
 
.popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem;
    background: #fff;
    position: sticky;
    top: 0;
    z-index: 10;
}
 
.cancelButton {
    color: #969799
}
 
.confirmButton {
    color: #1989FA
}
 
.u-tree {
    height: 13rem;
}
 
/* 移除 input 边框的样式 */
:deep(.u-input) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
}
 
:deep(.u-input__content) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
}
 
:deep(.u-input__content__field-wrapper) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
}
 
:deep(.u-input__content__field-wrapper__field) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
  outline: none !important;
}
 
/* 移除 textarea 边框的样式 */
:deep(.u-textarea) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
}
 
:deep(.u-textarea__content) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
}
 
:deep(.u-textarea__content__field) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
  outline: none !important;
}
 
/* 移除 form-item 的边框 */
:deep(.u-form-item) {
  border: none !important;
}
 
:deep(.u-form-item__body) {
  border: none !important;
}
 
/* 保持分割线样式 */
:deep(.u-form-item--border-bottom) {
  border-bottom: 1px solid #ebeef5 !important;
}
 
/* 选择器头部样式 */
.picker-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: #fff;
    border-bottom: 1px solid #ebeef5;
}
 
.picker-cancel {
    color: #909399;
    font-size: 16px;
}
 
.picker-title {
    color: #303133;
    font-size: 16px;
    font-weight: 500;
}
 
.picker-confirm {
    color: #2979ff;
    font-size: 16px;
}
</style>