add.vue 35.9 KB
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
<template>
    <view class="page">
        <scroll-view class="scroll" scroll-y>
            <uni-list>
                <uni-list-item title="编号">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.code" :inputBorder="false" disabled />
                    </template>
                </uni-list-item>

                <uni-list-item class="select-item" :class="form.supplier ? 'is-filled' : 'is-empty'" clickable
                    @click="openSheet('supplier')" :rightText="displayLabel('supplierName')" showArrow>
                    <template v-slot:body>
                        <view class="item-title"><text class="required">*</text><text>供方</text></view>
                    </template>
                </uni-list-item>

                <uni-list-item class="select-item" :class="form.buyer ? 'is-filled' : 'is-empty'" clickable
                    @click="openRelate('buyer')" :rightText="form.buyerName || '请选择需方'" showArrow>
                    <template v-slot:body>
                        <view class="item-title"><text class="required">*</text><text>需方</text></view>
                    </template>
                </uni-list-item>
                <uni-list-item class="select-item" :class="form.stockUpCompanyId ? 'is-filled' : 'is-empty'" clickable
                    @click="openRelate('stockUpCompanyId')" :rightText="form.stockUpCompanyName || '请选择备货单位'" showArrow>
                    <template v-slot:body>
                        <view class="item-title"><text class="required">*</text><text>备货单位/人(生产标准)</text></view>
                    </template>
                </uni-list-item>


                <uni-list-item title="订货日期">
                    <template v-slot:footer>
                        <uni-datetime-picker type="date" v-model="form.orderDate" />
                    </template>
                </uni-list-item>

                <uni-list-item title="单位">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.unit" :inputBorder="false" disabled />
                    </template>
                </uni-list-item>
				<uni-list-item class="select-item" :class="form.workshopId ? 'is-filled' : 'is-empty'" clickable
					@click="openSheet('workshopId')" :rightText="displayLabel('workshopIdName')" showArrow>
					<template v-slot:body>
						<view class="item-title"><text class="required">*</text><text>生产厂</text></view>
					</template>
				</uni-list-item>
                <uni-list-item title="办事处">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.deptName" :inputBorder="false" disabled placeholder="自动获取" />
                    </template>
                </uni-list-item>
                <uni-list-item class="select-item" :class="form.region ? 'is-filled' : 'is-empty'" clickable
                    @click="openSheet('region')" :rightText="displayLabel('regionName')" showArrow>
                    <template v-slot:body>
                        <view class="item-title"><text class="required">*</text><text>区域</text></view>
                    </template>
                </uni-list-item>
                <ProductRel ref="productRel" mode="add" :deliveryDateBase="form.deliveryDate"  :deliveryDate="form.orderDate" @change="onProductsChange" :options="productList" />
                <uni-list-item title="合计人民币金额(大写)">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.totalAmountCapital" placeholder="自动计算" :inputBorder="false" disabled />
                    </template>
                </uni-list-item>
                <uni-list-item title="交付定金、数额、时间">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.depositInfo" placeholder="请输入交付定金、数额、时间" :inputBorder="false" />
                    </template>
                </uni-list-item>
                <uni-list-item title="包装要求">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.packagingRequirements" placeholder="请输入包装要求"
                            :inputBorder="false" />
                    </template>
                </uni-list-item>
                <uni-list-item title="付款方式、付款期限">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.paymentTerms" placeholder="请输入付款方式、付款期限" :inputBorder="false" />
                    </template>
                </uni-list-item>
                <uni-list-item title="运输方式">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.transportMode" placeholder="请输入运输方式" :inputBorder="false" />
                    </template>
                </uni-list-item>
                
                <uni-list-item class="select-item" :class="(Array.isArray(form.destinationId) && form.destinationId.length) ? 'is-filled' : 'is-empty'" clickable
                    @click="openCitySelector" :rightText="form.destinationLabel || '请选择'" showArrow>
                    <template v-slot:body>
                        <view class="item-title"><text>目的地</text></view>
                        <CitySelector ref="citySelectorRef" v-model="form.destinationId" @change="onCityChange" />
                    </template>
                </uni-list-item>
                <uni-list-item class="select-item" :class="form.includesPackagingFeeName ? 'is-filled' : 'is-empty'" clickable
                    @click="openSheet('includesPackagingFee')" :rightText="form.includesPackagingFeeName || '请选择'" showArrow>
                    <template v-slot:body>
                        <view class="item-title"><text>单价中是否已包含包装费</text></view>
                    </template>
                </uni-list-item>
                <uni-list-item class="select-item" :class="form.includesTransportFeeName ? 'is-filled' : 'is-empty'" clickable
                    @click="openSheet('includesTransportFee')" :rightText="form.includesTransportFeeName || '请选择'" showArrow>
                    <template v-slot:body>
                        <view class="item-title"><text>单价中是否已包含运费</text></view>
                    </template>
                </uni-list-item>
                <uni-list-item title="需方指定收货人">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.designatedConsignee" placeholder="请输入需方指定收货人"
                            :inputBorder="false" />
                    </template>
                </uni-list-item>
                <uni-list-item class="select-item" :class="form.specialTermsName ? 'is-filled' : 'is-empty'" clickable
                    @click="openSheet('specialTerms')" :rightText="form.specialTermsName || '请选择'" showArrow>
                    <template v-slot:body>
                        <view class="item-title"><text class="required">*</text><text>特别条款要求</text></view>
                    </template>
                </uni-list-item>
                <uni-list-item class="select-item" :class="form.executionStandardName ? 'is-filled' : 'is-empty'" clickable
                    @click="openSheet('executionStandard')" :rightText="form.executionStandardName || '请选择'" showArrow>
                    <template v-slot:body>
                        <view class="item-title"><text>执行标准</text></view>
                    </template>
                </uni-list-item>
                <uni-list-item v-if="form.executionStandard === 'OTHER'" title="其他">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.executionStandardRemarks" placeholder="请输入其他标准备注"
                            :inputBorder="false" />
                    </template>
                </uni-list-item>
                <uni-list-item title="特别说明" style="margin-top: 20rpx;">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.specialInstructions" placeholder="请输入特别说明" :inputBorder="false" />
                    </template>
                </uni-list-item>    
                <uni-list-item v-if="this.customerRemarks.length" class="select-item" :class="defaultRemark ? 'is-filled' : 'is-empty'" clickable
                    @click="openSheet('historyRemarks')" :rightText="defaultRemark || '请选择'" showArrow>
                    <template v-slot:body>
                        <view class="item-title"><text>历史备注</text></view>
                    </template>
                </uni-list-item>
                <uni-list-item title="备注">
                    <template v-slot:footer>
                        <uni-easyinput type="textarea" v-model="form.remarks" placeholder="请输入备注" :inputBorder="false" maxlength="2000" />
                    </template>
                </uni-list-item>
                <view class="quality">
                    <image class="opCollapse" src="/static/images/title.png" />
                    <text class="title">具体质量要求</text>
                </view>
                <uni-list-item title="件重条头">
                    <template v-slot:footer>
                        <uni-easyinput type="textarea" v-model="form.pieceWeightHead" placeholder="请输入" :inputBorder="false" />
                    </template>
                </uni-list-item>
                <uni-list-item title="表面">
                    <template v-slot:footer>
                        <uni-easyinput type="textarea" v-model="form.surface" placeholder="请输入" :inputBorder="false" />
                    </template>
                </uni-list-item>
                <uni-list-item title="公差">
                    <template v-slot:footer>
                        <uni-easyinput type="textarea" v-model="form.tolerance" placeholder="请输入" :inputBorder="false" />
                    </template>
                </uni-list-item>
                <uni-list-item title="性能">
                    <template v-slot:footer>
                        <uni-easyinput type="textarea" v-model="form.performance" placeholder="请输入" :inputBorder="false" />
                    </template>
                </uni-list-item>
                <uni-list-item title="成分">
                    <template v-slot:footer>
                        <uni-easyinput type="textarea" v-model="form.component" placeholder="请输入" :inputBorder="false" />
                    </template>
                </uni-list-item>
                <uni-list-item title="包装">
                    <template v-slot:footer>
                        <uni-easyinput type="textarea" v-model="form.packaging" placeholder="请输入" :inputBorder="false" />
                    </template>
                </uni-list-item>
            </uni-list>

        </scroll-view>
        <view class="footer">
            <div class="total">
                <div class="total-text">
                    合计
                </div>
                <div class="total-item">
                    <div class="total-item-text">
                        数量
                    </div>
                    <div class="total-item-price">
                        {{ (totalQuantity || 0).toFixed(2) }}kg
                    </div>
                </div>
                <div class="total-item">
                    <div class="total-item-text">
                        不含税金额
                    </div>
                    <div class="total-item-price text-red">
                        ¥{{ (totalAmountExcludingTax || 0).toFixed(2) }}
                    </div>
                </div>
                <div class="total-item">
                    <div class="total-item-text">
                        总金额
                    </div>
                    <div class="total-item-price text-red">
                        ¥{{ (totalAmountIncludingTax || 0).toFixed(2) }}
                    </div>
                </div>
            </div>
            <button class="btn submit" type="primary" @click="onSubmit">提交</button>
        </view>
        <SingleSelectSheet :visible.sync="sheet.visible" :title="sheet.title" :options="sheet.options"
            v-model="sheet.value" @confirm="onSheetConfirm" />
        <RelateSelectSheet :visible.sync="relate.visible" :title="relate.title" :source="relate.source"
            :display-fields="relate.display" :multiple="relate.multiple" :row-key="relate.rowKey"
            :selectedKeys.sync="relate.selectedKeys" @confirm="onRelateConfirm" />
    </view>

</template>
<script>
import SingleSelectSheet from '@/components/single-select/index.vue'
import RelateSelectSheet from '@/components/relate-select/index.vue'
import ProductRel from './productRel.vue'
import CitySelector from '@/components/city-selector/index.vue'
import { getRetailCodeApi, createContractApi, getCustomerRemarks,getCustomerSpecificQualityRequirements, getDeptApi } from '@/api/contract'
import { getDicByCodes } from '@/utils/dic'
import { formatCurrencyToChinese } from '@/utils/common'
import { workshopQueryApi } from '@/api/devManage'
import { getArea } from '@/api/credit_manage.js'

export default {
    name: 'AddContractRetail',
    components: { SingleSelectSheet, RelateSelectSheet, ProductRel, CitySelector },
    data() {
        return {
            form: {
                code: '',
                supplier: '',
                supplierName: '',
                buyer: '',
                buyerName: '',
                stockUpCompanyId: '',
                stockUpCompanyName: '',
                orderDate: '',
                deliveryDate: '',
                designatedConsignee: '',
                specialTerms: '',
                specialTermsName: '',
                executionStandard: '',
                executionStandardName: '',
                executionStandardRemarks: '',
                includesPackagingFee: false,
                includesPackagingFeeName: '否',
                includesTransportFee: false,
                includesTransportFeeName: '否',
                unit: '元、公斤、元/公斤',
                totalAmountCapital: '',
                destinationId: [],
                destinationLabel: '',
                workshopIdName: '',
                workshopId: '',
                deptName: '',
                deptId: '',
                region: '',
                regionName: '',
                remarks: '',
                component: '',
                packaging: '',
                performance: '',
                pieceWeightHead: '',
                surface: '',
                tolerance: '',
            },
            supplierList: [],
            specialTermsList: [],
            executionStandardList: [],
            yesNoList: [{ label: '是', value: true }, { label: '否', value: false }],
            sheet: { visible: false, title: '请选择', field: '', options: [], value: '' },
            relate: { visible: false, title: '选择', source: '', display: [], multiple: false, rowKey: 'id', selectedKeys: [], fieldKey: '' },
            totalQuantity: 0,
            totalAmountExcludingTax: 0,
            totalAmountIncludingTax: 0,
            productLineList: [],
            productList: [],
            customerRemarks: [],
            defaultRemark: '',
            regionOptions: [],
        }
    },
    created() {
        this.loadSuppliers()
        this.loadExtraOptions()
        this.initCode()
        this.getDept()
        this.loadRegionOptions()
        this.form.orderDate = this.formatDate(new Date())
        this.$nextTick(() => {
            if (Array.isArray(this.form.destinationId) && this.form.destinationId.length) {
                this.initDestinationLabel()
            }
        })
    },
    watch: {
        'form.buyer': {
            handler(newVal, oldVal) {
                if (newVal) {
                    getCustomerRemarks(newVal).then(res => {
                        const remarksData = res.data || [];
                        this.customerRemarks = remarksData.map((item, index) => ({
                            label: `客户备注${index + 1}`,
                            value: item,
                        }));
                        if (remarksData.length > 0) {
                        this.defaultRemark = this.customerRemarks[0].label || '';
                        this.form.remarks = remarksData[0];
                        } else {
                        this.form.remarks = '';
                        this.defaultRemark = '';
                        }
                    })
                    this.getHistory()
                }
            }
        },
        productLineList: {
            deep: true,
            handler(newVal, oldVal) {
                const n = Array.isArray(newVal) ? newVal : []
                const o = Array.isArray(oldVal) ? oldVal : []
                const changed = []
                for (let i = 0; i < n.length; i++) {
                    const ni = n[i] && n[i].productId
                    const oi = o[i] && o[i].productId
                    if (ni !== oi && ni !== undefined) changed.push(ni)
                }
                console.log('changed', changed)
                if (changed.length  && this.form.buyer) {
                    const id = changed.join('')
                    this.fetchCustomerQualityRequirements(id)
                }
            }
        },
    },
    methods: {
        async loadRegionOptions() {
            try {
                const res = await getArea()
                const list = res.data || []
                this.regionOptions = (list || []).map(it => ({ label: it.name || '', value: it.id || '' }))
            } catch (e) {
                this.regionOptions = []
            }
        },
        // 查询当前人所在办事处
        getDept() {
            getDeptApi().then(res => {
                if (res.code === 200) {
                    this.form.deptName = res.data.name || ''
                    this.form.deptId = res.data.id || ''
                }
            })
        },
        getHistory() {
            console.log('this.productLineList', this.productLineList[0].productId)
            if (!this.productLineList.length || !this.productLineList[0].productId) {
                return;
            }
            const id = this.productLineList.map(it => it.productId).join('')
            this.fetchCustomerQualityRequirements(id)
        },
      async fetchCustomerQualityRequirements(id) {
        if (!this.form.buyer || !id) {
          return;
        }
        try {
          const result = await getCustomerSpecificQualityRequirements({
            customerId: this.form.buyer,
            productIdList:id,
          });
          this.updateFormData(result.data || {});
        } catch (error) {
          console.error('获取客户质量要求失败:', error);
          // 可以根据需要添加错误提示逻辑
          this.$message.error('获取历史数据失败,请稍后重试');
        }
      },
      // 提取公共的字段更新方法
      updateFormData(result) {
        console.log('result', result)
        const fields = [
          'component',
          'packaging',
          'performance',
          'pieceWeightHead',
          'surface',
          'tolerance',
        ];
        fields.forEach((field) => {
          this.form[field] = (this.form[field] || '') + (result[field] || '');
        });
      },
        onProductsChange(products) {
            const list = Array.isArray(products) ? products : []
            const sumQ = list.reduce((acc, it) => acc + (parseFloat(it.quantity) || 0), 0)
            const sumE = list.reduce((acc, it) => acc + (parseFloat(it.amountExcludingTax) || 0), 0)
            const sumT = list.reduce((acc, it) => acc + (parseFloat(it.totalAmount) || 0), 0)
            this.totalQuantity = sumQ
            this.totalAmountExcludingTax = sumE
            this.totalAmountIncludingTax = sumT
            this.form.totalAmountCapital = formatCurrencyToChinese(sumT)
            this.productLineList = list
        },
        formatDate(d) {
            const y = d.getFullYear()
            const m = String(d.getMonth() + 1).padStart(2, '0')
            const day = String(d.getDate()).padStart(2, '0')
            return `${y}-${m}-${day}`
        },
        async initCode() {
            try {
                const res = await getRetailCodeApi()
                const code = (res && res.data) ? res.data : ''
                this.form.code = code
            } catch (e) { this.form.code = '' }
        },
        async loadSuppliers() {
            try {
                const results = await getDicByCodes(['SUPPLIER'])
                const items = results && results.SUPPLIER && results.SUPPLIER.data ? results.SUPPLIER.data : []
                this.supplierList = items.map(it => ({ label: it.name, value: it.code }))
            } catch (e) { this.supplierList = [] }
        },
        async loadExtraOptions() {
            try {
                const results = await getDicByCodes(['CONDITIONS_REQUIRED', 'APPLICABLE_STANDARD', 'CONTRACT_PRODUCT'])
                const c1 = results && results.CONDITIONS_REQUIRED && results.CONDITIONS_REQUIRED.data ? results.CONDITIONS_REQUIRED.data : []
                const c2 = results && results.APPLICABLE_STANDARD && results.APPLICABLE_STANDARD.data ? results.APPLICABLE_STANDARD.data : []
                const c3 = results && results.CONTRACT_PRODUCT && results.CONTRACT_PRODUCT.data ? results.CONTRACT_PRODUCT.data : []
                this.specialTermsList = c1.map(it => ({ label: it.name, value: it.code }))
                this.executionStandardList = c2.map(it => ({ label: it.name, value: it.code }))
                this.productList = c3.map(it => ({ label: it.name, value: it.code }))
            } catch (e) {
                this.specialTermsList = []
                this.executionStandardList = []
                this.productList = []
            }
        },
        displayLabel(field) {
            const m = this.form
            const map = { supplierName: '请选择供方', buyerName: '请选择需方', workshopIdName: '请选择生产厂', regionName: '请选择区域' }
            const val = m[field]
            return val ? String(val) : map[field]
        },
        openCitySelector() {
            this.$refs.citySelectorRef && this.$refs.citySelectorRef.open()
        },
        async initDestinationLabel() {
            const comp = this.$refs.citySelectorRef
            if (comp && typeof comp.getLabel === 'function') {
                const label = await comp.getLabel()
                this.form.destinationLabel = label || ''
            }
        },
        onCityChange(payload) {
            const label = payload && payload.label != null ? payload.label : ''
            this.form.destinationLabel = label
        },
        async openSheet(field) {
            const setSheet = (title, options) => {
                const current = this.form[field]
                const match = (options || []).find(o => String(o.label) === String(current) || String(o.value) === String(current))
                this.sheet = { ...this.sheet, visible: true, title, options, field, value: match ? match.value : '' }
            }
            if (field === 'workshopId') {
                const res = await workshopQueryApi({ pageIndex: 1, pageSize: 9999 })
                const _data = res.data || {}
                const list = _data.datas || (Array.isArray(_data) ? _data : [])
                const opts = (list || []).map(it => ({
                    label: it.name ,
                    value: it.id
                }))
                setSheet('生产厂', opts)
            } else if (field === 'supplier') {
                setSheet('供方', this.supplierList)
            } else if (field === 'specialTerms') {
                setSheet('特别条款要求', this.specialTermsList)
            } else if (field === 'executionStandard') {
                setSheet('执行标准', this.executionStandardList)
            } else if (field === 'includesPackagingFee') {
                setSheet('单价中是否已包含包装费', this.yesNoList)
            } else if (field === 'includesTransportFee') {
                setSheet('单价中是否已包含运费', this.yesNoList)
            } else if (field === 'historyRemarks') {
                setSheet('历史备注', this.customerRemarks)
            }else if (field === 'region') {
                setSheet('区域', this.regionOptions)
            }
        },
        onSheetConfirm({ value, label }) {
            const field = this.sheet.field
            if (!field) return
            const v = (value === undefined || value === null) ? '' : value
            if (field === 'historyRemarks') {
                this.defaultRemark = label || ''
                this.form.remarks = v
            }else{
                this.form[field] = v
                this.form[field + 'Name'] = label || ''
            }
        },
        openRelate(fieldKey) {
            let config = {}
            if (fieldKey === 'buyer') {
                config = { title: '需方', source: 'customer', rowKey: 'id', multiple: false, display: [{ label: '名称', field: 'name' }, { label: '编号', field: 'code' }, { label: '状态', field: 'available', format: v => (v ? '启用' : '停用') }] }
            } else if (fieldKey === 'stockUpCompanyId') {
                config = { title: '备货单位/人(生产标准)', source: 'customer', rowKey: 'id', multiple: false, display: [{ label: '姓名', field: 'name' }, { label: '编号', field: 'code' }, { label: '状态', field: 'available', format: v => (v ? '启用' : '停用') }] }
            }
            const selectedKeys = this.form[fieldKey] ? [this.form[fieldKey]] : []
            this.sheet.visible = false
            this.relate = { ...this.relate, title: config.title, source: config.source, display: config.display, multiple: config.multiple, rowKey: config.rowKey, selectedKeys, fieldKey }
            this.$nextTick(() => { this.relate.visible = true })
        },
        onRelateConfirm({ items }) {
            const _fieldKey = this.relate.fieldKey
            const first = (items && items.length > 0) ? items[0] : null
            this.form[_fieldKey] = (first && first.id) ? first.id : ''

            if (_fieldKey === 'stockUpCompanyId') {
                 this.form.stockUpCompanyName = (first && first.name) ? first.name : ''
            } else {
                 this.form[_fieldKey + 'Name'] = (first && first.name) ? first.name : ''
            }
            
            if (_fieldKey === 'buyer') {
                this.form.stockUpCompanyId = (first && first.id) ? first.id : ''
                this.form.stockUpCompanyName = (first && first.name) ? first.name : ''
            }
        },
        onRadioSelect(field, nameField, opt) {
            const val = opt && opt.value != null ? opt.value : ''
            const label = opt && opt.label != null ? opt.label : ''
            this.form[field] = val
            this.form[nameField] = label
            if (field === 'executionStandard' && val !== 'OTHER') {
                this.form.executionStandardRemarks = ''
            }
        },
        async onSubmit() {
            if (!this.validateRequired()) return
            const confirmRes = await new Promise(resolve => {
                uni.showModal({ title: '提示', content: '确定新增经销标准合同吗?', confirmText: '确定', cancelText: '取消', success: resolve })
            })
            if (!(confirmRes && confirmRes.confirm)) return
            const clean = (obj) => {
                const out = {}
                Object.keys(obj || {}).forEach(k => {
                    const v = obj[k]
                    const isEmptyString = typeof v === 'string' && v.trim() === ''
                    const isUndef = v === undefined || v === null
                    const isNaNNumber = typeof v === 'number' && isNaN(v)
                    if (!(isEmptyString || isUndef || isNaNNumber)) out[k] = v
                })
                return out
            }
            const lines = (this.productLineList || []).map(it => clean(it))
            const { destinationLabel, destinationId, ...formForSubmit } = this.form;
            // 区id
            const destination = destinationId && destinationId.length > 0 ? destinationId[destinationId.length - 1] : '';
            const payload = clean({
                ...formForSubmit,
                destination,
                type: 'DISTRIB_STD',
                totalQuantity: this.totalQuantity,
                totalAmountExcludingTax: this.totalAmountExcludingTax,
                totalAmountIncludingTax: this.totalAmountIncludingTax,
                contractDistributorLineList: lines
            })
            console.log('onSubmit__payload', payload)
            
            try {
                await createContractApi(payload)
                uni.showToast({ title: '新增成功', icon: 'none' })
                setTimeout(() => { uni.redirectTo({ url: '/pages/contract_retail/index' }) }, 400)
            } catch (e) {
                uni.showToast({ title: e.msg ||'新增失败', icon: 'none' })
            }
        },
        validateRequired() {
            const checks = [
                { key: 'code', label: '编号' },
                { key: 'supplier', label: '供方' },
                { key: 'buyer', label: '需方' },
                { key: 'stockUpCompanyId', label: '备货单位/人(生产标准)' },
                { key: 'orderDate', label: '订货日期' },
                { key: 'unit', label: '单位' },
                { key: 'workshopId', label: '生产厂' },
                { key: 'region', label: '区域' },
                { key: 'specialTerms', label: '特别条款要求' },
            ]
            for (const it of checks) {
                const val = this.form[it.key]
                const empty = (val === undefined || val === null || (typeof val === 'string' && val.trim() === '') || (typeof val === 'number' && isNaN(val)))
                if (empty) { uni.showToast({ title: `请先选择${it.label}`, icon: 'none' }); return false }
            }
            if (this.$refs.productRel && !this.$refs.productRel.validate()) return false
            const list = Array.isArray(this.productLineList) ? this.productLineList : []
            if (list.length === 0) {
                uni.showToast({ title: '请至少添加一条产品明细', icon: 'none' }); return false
            }
            const strEmpty = (v) => (v === undefined || v === null || (typeof v === 'string' && v.trim() === ''))
            const numEmpty = (v) => (v === undefined || v === null || v === '' || (typeof v === 'number' && isNaN(v)))
            for (const [idx, it] of list.entries()) {
                if (
                    strEmpty(it.productName) ||
                    strEmpty(it.industry) ||
                    strEmpty(it.quality) ||
                    strEmpty(it.brand) ||
                    numEmpty(it.quantity) ||
                    numEmpty(it.unitPrice) ||
                    strEmpty(it.deliveryDate)
                ) {
                    uni.showToast({ title: `第${idx + 1}条明细未完整填写`, icon: 'none' }); return false
                }
            }
            return true
        }
    }
}

</script>
<style>
/* 强制提升日历层级,解决被 footer 遮挡问题 */
.uni-calendar--mask,
.uni-calendar--fixed {
    z-index: 9999 !important;
}
</style>
<style lang="scss" scoped>
.total {
    .total-text {
        font-weight: 600;
        font-size: 32rpx;
        color: rgba(0, 0, 0, 0.9);
        padding-bottom: 28rpx;
        border-bottom: 2rpx solid #E7E7E7;
    }
    .total-item {
        display: flex;
        align-items: center;
        .total-item-text {
            font-weight: 400;
            font-size: 28rpx;
            color: rgba(0, 0, 0, 0.6);
            line-height: 32rpx;
            width: 240rpx;
            padding: 12rpx 0;
        }
        .total-item-price {
            font-weight: 600;
            font-size: 32rpx;
            color: rgba(0, 0, 0, 0.9);
            line-height: 32rpx;
        }
        .text-red {
            color: #D54941;
        }
    }

}
.page {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.scroll {
  flex: 1;
  padding: 12rpx 0 392rpx !important;
}

.footer {
  z-index: 2;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 32rpx;
  padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
  background: #fff;
  box-shadow: 0 -8rpx 24rpx rgba(0, 0, 0, 0.06);

  .btn {
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 12rpx;
    font-size: 32rpx;
  }

  .submit {
    background: $theme-primary;
    color: #fff;
  }
}

.group {
    background: #fff;
    padding: 24rpx 32rpx;
    margin-bottom: 20rpx;
}

.group-title {
    color: rgba(0, 0, 0, 0.9);
    font-size: 32rpx;
    padding-bottom: 16rpx;
}

.radio-list {
    display: flex;
    flex-direction: column;
}

.radio-item {
    display: flex;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
}

.radio-item:last-child {
    border-bottom: none;
}

.radio {
    width: 32rpx;
    height: 32rpx;
    border-radius: 50%;
    border: 2rpx solid #DCDCDC;
    margin-right: 20rpx;
    box-sizing: border-box;
}

.radio.checked {
    background: $theme-primary;
    border-color: $theme-primary;
}

.radio-item .label {
    font-size: 32rpx;
    color: rgba(0, 0, 0, 0.9);
}

.quality {
    background-color: #fff;
    display: flex;
    align-items: center;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid #f0f0f0;
    margin-top: 20rpx;

    .title {
        font-size: 32rpx;
        color: rgba(0, 0, 0, 0.9);
        font-weight: 600;
    }

    .opCollapse {
        color: rgba(0, 0, 0, 0.6);
        width: 32rpx;
        height: 28rpx;
        margin-right: 16rpx;
    }
}

::v-deep .uni-list {
    .uni-easyinput {
        display: flex;

        .uni-input-input {
            color: rgba(0, 0, 0, 0.9);
        }
    }

    .uni-input-placeholder {
        z-index: 1;
    }

    .uni-input-input {
        background-color: #ffffff;
    }

    background: transparent;

    &-item {
        &__extra-text {
            font-size: 32rpx;
        }

        &__content-title {
            font-size: 32rpx;
            color: rgba(0, 0, 0, 0.9);
        }

        &__container {
            padding: 32rpx;

            .uni-easyinput {
                &__placeholder-class {
                    font-size: 32rpx;
                    color: rgba(0, 0, 0, 0.4);
                }

                &__content {
                    border: none;
                    background-color: #ffffff !important;

                    &-input {
                        padding-left: 0 !important;
                        height: 48rpx;
                        line-height: 48rpx;
                        font-size: 32rpx;
                    }

                    .content-clear-icon {
                        font-size: 44rpx !important;
                    }
                }
            }

            .item-title,
            .uni-list-item__content {
                flex: none;
                min-height: 48rpx;
                line-height: 48rpx;
                font-size: 32rpx;
                position: relative;
                width: 210rpx;
                margin-right: 32rpx;
                color: rgba(0, 0, 0, 0.9);

                .required {
                    color: red;
                    position: absolute;
                    top: 50%;
                    transform: translateY(-50%);
                    left: -16rpx;
                }
            }
        }

        &.select-item {
            &.is-empty {
                .uni-list-item__extra-text {
                    color: rgba(0, 0, 0, 0.4) !important;
                }
            }

            &.is-filled {
                .uni-list-item__extra-text {
                    color: rgba(0, 0, 0, 0.9) !important;
                }
            }
        }

        &.mgb10 {
            margin-bottom: 20rpx;
        }
    }
}
</style>