modify.vue 43.3 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 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
<template>
    <view class="page">
        <scroll-view class="scroll" scroll-y>
            <uni-list>
                <!-- 编号(只读) -->
                <uni-list-item class="select-item" :class="form.code ? 'is-filled' : 'is-empty'">
                    <template v-slot:body>
                        <view class="item-title"><text class="required">*</text><text>编号</text></view>
                    </template>
                    <template v-slot:footer>
                        <text class="readonly-text value-code">{{ form.code || '-' }}</text>
                    </template>
                </uni-list-item>

                <!-- 类型 -->
                <uni-list-item class="select-item" :class="form.type ? 'is-filled' : 'is-empty'">
                    <template v-slot:body>
                        <view class="item-title"><text class="required">*</text><text>类型</text></view>
                    </template>
                    <template v-slot:footer>
                        <picker mode="selector" :range="typeLabels" @change="onTypeChange">
                            <view class="picker-value" :class="{ placeholder: !form.type }">
                                {{ getTypeLabel() || '请选择类型' }}
                            </view>
                        </picker>
                    </template>
                </uni-list-item>

                <!-- 计划编号(弹窗多选计划) -->
                <uni-list-item class="select-item" :class="form.planCode ? 'is-filled' : 'is-empty'" clickable
                    @click="openPlanSheet" :rightText="form.planCode || '请选择计划'" 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.unit" :inputBorder="false" disabled />
                    </template>
                </uni-list-item>

                <!-- 供料单位(带出,禁用) -->
                <uni-list-item title="供料单位">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.supplierName" :inputBorder="false" disabled placeholder="选择计划后自动带出" />
                    </template>
                </uni-list-item>

                <!-- 收料单位(带出,禁用) -->
                <uni-list-item title="收料单位">
                    <template v-slot:footer>
                        <uni-easyinput v-model="form.companyShortName" :inputBorder="false" disabled placeholder="选择计划后自动带出" />
                    </template>
                </uni-list-item>
            </uni-list>

            <!-- 计划单明细(只读) -->
            <view class="sub-table">
                <view class="header">
                    <image class="opCollapse" src="/static/images/title.png" />
                    <text class="title">计划单明细</text>
                </view>
                <view class="add-list">
                    <view v-if="!planList.length" class="empty-tip">选择计划后自动带出</view>
                    <view v-for="(item, idx) in planList" :key="'p-' + (item.id || idx)" class="block">
                        <uni-list>
                            <uni-list-item title="计划品种">
                                <template v-slot:footer>
                                    <uni-easyinput :value="item.productName" :inputBorder="false" disabled />
                                </template>
                            </uni-list-item>
                            <uni-list-item title="计划数量">
                                <template v-slot:footer>
                                    <uni-easyinput :value="item.quantity" :inputBorder="false" disabled />
                                </template>
                            </uni-list-item>
                            <uni-list-item title="计划编号">
                                <template v-slot:footer>
                                    <uni-easyinput :value="item.planCode" :inputBorder="false" disabled />
                                </template>
                            </uni-list-item>
                        </uni-list>
                    </view>
                </view>
            </view>

            <!-- 过磅明细(可编辑) -->
            <view class="sub-table">
                <view class="header">
                    <image class="opCollapse" src="/static/images/title.png" />
                    <text class="title">过磅明细</text>
                    <view class="ops">
                        <image class="opAdd" @click="addWeightRow" src="/static/images/plus.png" />
                    </view>
                </view>
                <view class="add-list">
                    <view v-if="!weighList.length" class="empty-tip">暂无明细,请添加</view>
                    <view v-for="(item, idx) in weighList" :key="'w-' + (item.id || idx)" class="block">
                        <uni-list>
                            <uni-list-item class="select-item" :class="item.productId ? 'is-filled' : 'is-empty'">
                                <template v-slot:body>
                                    <view class="item-title"><text class="required">*</text><text>过磅品种</text></view>
                                </template>
                                <template v-slot:footer>
                                    <picker mode="selector" :range="weightProductLabels"
                                        @change="(e) => handleWeightProductChange(idx, Number(e.detail.value))">
                                        <view class="picker-value" :class="{ placeholder: !item.productId }">
                                            {{ getWeightProductLabel(item) || '请选择过磅品种' }}
                                        </view>
                                    </picker>
                                </template>
                            </uni-list-item>
                            <uni-list-item title="开票品名">
                                <template v-slot:footer>
                                    <uni-easyinput v-model="item.invoiceProductName" :inputBorder="false" disabled />
                                </template>
                            </uni-list-item>
                            <uni-list-item title="过磅数量">
                                <template v-slot:body>
                                    <view class="item-title"><text class="required">*</text><text>过磅数量</text></view>
                                </template>
                                <template v-slot:footer>
                                    <uni-easyinput v-model="item.quantity" type="digit" :inputBorder="false" placeholder="请输入过磅数量" />
                                </template>
                            </uni-list-item>
                            <uni-list-item title="计划编号">
                                <template v-slot:footer>
                                    <uni-easyinput v-model="item.planCode" :inputBorder="false" disabled />
                                </template>
                            </uni-list-item>
                        </uni-list>
                        <view class="block-ops">
                            <div class="del" @click="removeRow('weigh', idx)">
                                <image src="/static/images/delete.png" class="icon" />删除
                            </div>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 申请数量明细(仅买断展示) -->
            <view v-if="isBuyout" class="sub-table">
                <view class="header">
                    <image class="opCollapse" src="/static/images/title.png" />
                    <text class="title">申请数量明细</text>
                    <view class="ops">
                        <image class="opAdd" @click="addApplyRow" src="/static/images/plus.png" />
                    </view>
                </view>
                <view class="add-list">
                    <view v-if="!applyList.length" class="empty-tip">暂无明细,请添加</view>
                    <view v-for="(item, idx) in applyList" :key="'a-' + (item.id || idx)" class="block">
                        <uni-list>
                            <uni-list-item class="select-item" :class="item.breedRelationshipId ? 'is-filled' : 'is-empty'">
                                <template v-slot:body>
                                    <view class="item-title"><text class="required">*</text><text>类别</text></view>
                                </template>
                                <template v-slot:footer>
                                    <picker mode="selector" :range="varietyLabels"
                                        @change="(e) => handleVarietyChange(idx, Number(e.detail.value))">
                                        <view class="picker-value" :class="{ placeholder: !item.breedRelationshipId }">
                                            {{ getVarietyLabel(item) || '请选择类别' }}
                                        </view>
                                    </picker>
                                </template>
                            </uni-list-item>
                            <uni-list-item title="数量">
                                <template v-slot:body>
                                    <view class="item-title"><text class="required">*</text><text>数量</text></view>
                                </template>
                                <template v-slot:footer>
                                    <uni-easyinput v-model="item.quantity" type="digit" :inputBorder="false" placeholder="请输入数量" />
                                </template>
                            </uni-list-item>
                        </uni-list>
                        <view class="block-ops">
                            <div class="del" @click="removeRow('apply', idx)">
                                <image src="/static/images/delete.png" class="icon" />删除
                            </div>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 其他信息 -->
            <view class="remark-section">
                <view class="header">
                    <image class="opCollapse" src="/static/images/title.png" />
                    <text class="title">其他信息</text>
                </view>
                <view class="section-content">
                    <uni-list>
                        <uni-list-item title="物料名称">
                            <template v-slot:footer>
                                <uni-easyinput :value="materialName" :inputBorder="false" disabled />
                            </template>
                        </uni-list-item>
                        <uni-list-item>
                            <template v-slot:body>
                                <view class="item-title"><text class="required">*</text><text>过磅总重</text></view>
                            </template>
                            <template v-slot:footer>
                                <uni-easyinput v-model="form.totalGrossWeight" type="digit" :inputBorder="false" placeholder="请输入过磅总重" />
                            </template>
                        </uni-list-item>
                        <uni-list-item>
                            <template v-slot:body>
                                <view class="item-title"><text class="required">*</text><text>实际伙重</text></view>
                            </template>
                            <template v-slot:footer>
                                <uni-easyinput v-model="form.actualImpurityWeight" type="digit" :inputBorder="false" placeholder="请输入实际伙重" />
                            </template>
                        </uni-list-item>
                        <uni-list-item title="货物净重">
                            <template v-slot:footer>
                                <uni-easyinput :value="computedNetWeight" :inputBorder="false" disabled />
                            </template>
                        </uni-list-item>
                        <uni-list-item title="净重大写">
                            <template v-slot:footer>
                                <uni-easyinput :value="computedNetWeightUpper" :inputBorder="false" disabled />
                            </template>
                        </uni-list-item>
                    </uni-list>

                    <view class="form-group">
                        <view class="item-title"><text class="required">*</text><text>来料扣杂类型</text></view>
                        <uni-data-checkbox
                            mode="tag"
                            :multiple="true"
                            :value-field="'value'"
                            :text-field="'text'"
                            v-model="form.deductionTypes"
                            :localdata="deductionTypeOptions"
                        />
                    </view>

                    <uni-list>
                        <uni-list-item>
                            <template v-slot:body>
                                <view class="item-title"><text class="required">*</text><text>供应存欠料</text></view>
                            </template>
                            <template v-slot:footer>
                                <uni-easyinput v-model="form.supplierStockMaterial" :inputBorder="false" placeholder="请输入供应存欠料" />
                            </template>
                        </uni-list-item>
                        <uni-list-item>
                            <template v-slot:body>
                                <view class="item-title"><text class="required">*</text><text>物流存欠料</text></view>
                            </template>
                            <template v-slot:footer>
                                <uni-easyinput v-model="form.logisticsStockMaterial" :inputBorder="false" placeholder="请输入物流存欠料" />
                            </template>
                        </uni-list-item>
                        <uni-list-item>
                            <template v-slot:body>
                                <view class="item-title"><text class="required">*</text><text>车牌号</text></view>
                            </template>
                            <template v-slot:footer>
                                <uni-easyinput v-model="form.plateNumber" :inputBorder="false" placeholder="请输入车牌号" />
                            </template>
                        </uni-list-item>
                    </uni-list>
                </view>
            </view>

            <!-- 备注模块 -->
            <view class="remark-section">
                <view class="header">
                    <image class="opCollapse" src="/static/images/title.png" />
                    <text class="title">备注</text>
                </view>
                <view class="section-content">
                    <view class="remark-group">
                        <view class="remark-label">业务摘要</view>
                        <uni-easyinput :value="computedBusinessSummary" type="textarea" :inputBorder="false" disabled autoHeight />
                    </view>
                    <view class="remark-group">
                        <view class="remark-label">特别说明</view>
                        <uni-easyinput v-model="form.specialNote" type="textarea" :inputBorder="false" placeholder="请输入特别说明" maxlength="2000" />
                    </view>
                    <view class="remark-group">
                        <view class="remark-label">单据备注</view>
                        <uni-easyinput :value="computedDocumentRemark" type="textarea" :inputBorder="false" disabled autoHeight />
                    </view>
                </view>
            </view>

            <view class="footer">
                <button class="btn submit" type="primary" @click="onSubmit">保存</button>
            </view>
        </scroll-view>

        <RelateSelectSheet :visible.sync="planSheet.visible" title="选择计划" :multiple="true"
            :fetchFn="planSheet.fetchFn" :display-fields="planSheet.displayFields"
            row-key="id" :selectedKeys.sync="planSheet.selectedKeys" @confirm="onPlanConfirm" />
    </view>
</template>

<script>
import RelateSelectSheet from '@/components/relate-select/index.vue'
import {
    weighingTicketPlansApi,
    weighTicketPlanLinesApi,
    weighTicketDetailApi,
    weighTicketUpdateApi
} from '@/api/procure-manage/weighTicket.js'
import { breedRelationshipQueryApi } from '@/api/procure-manage/salesmanQuotation.js'
import { getDicByCodes, getDicName } from '@/utils/dic.js'

export default {
    name: 'ModifyWeightTicket',
    components: { RelateSelectSheet },
    data() {
        return {
            id: '',
            form: {
                code: '',
                type: '',
                planCode: '',
                unit: '公斤',
                supplierName: '',
                companyShortName: '',
                totalGrossWeight: '',
                actualImpurityWeight: '',
                deductionTypes: [],
                supplierStockMaterial: '',
                logisticsStockMaterial: '',
                plateNumber: '',
                specialNote: ''
            },
            dicOptions: { TYPE: [], DEDUCTION_TYPE: [] },
            // 选中计划行(多选)
            selectedPlanRows: [],
            // 计划单明细(只读)
            planList: [],
            // 过磅明细(可编辑)
            weighList: [],
            // 申请数量明细(买断时)
            applyList: [],
            varietyOptions: [],
            planSheet: {
                visible: false,
                fetchFn: null,
                displayFields: [
                    { label: '计划编号', field: 'code' },
                    { label: '是否买断', field: 'buyout', format: v => (v ? '是' : '否') },
                    { label: '收料单位', field: 'companyName' },
                    { label: '供料单位', field: 'supplierName' },
                    { label: '总数量', field: 'totalQuantity' },
                    { label: '创建人', field: 'createBy' }
                ],
                selectedKeys: []
            }
        }
    },
    computed: {
        typeLabels() {
            return (this.dicOptions.TYPE || []).map(it => it.name)
        },
        deductionTypeOptions() {
            return (this.dicOptions.DEDUCTION_TYPE || []).map(it => ({
                value: it.code != null ? String(it.code) : '',
                text: it.name || ''
            })).filter(it => it.value)
        },
        isBuyout() {
            const first = (this.selectedPlanRows || [])[0]
            return !!(first && first.buyout)
        },
        // 过磅品种下拉:数据来自计划单明细
        weightProductLabels() {
            return (this.planList || []).map(item =>
                [item.productName, item.planCode].filter(Boolean).join(' ')
            )
        },
        varietyLabels() {
            return (this.varietyOptions || []).map(item =>
                [item.productName, item.code].filter(Boolean).join(' ')
            )
        },
        // 物料名称:过磅明细开票品名去重顿号拼接
        materialName() {
            const names = (this.weighList || [])
                .map(item => item.invoiceProductName)
                .filter(name => !!name)
            return Array.from(new Set(names)).join('、')
        },
        // 货物净重 = 过磅总重 - 实际伙重(保留两位)
        computedNetWeight() {
            const gross = this.form.totalGrossWeight
            if (gross === undefined || gross === null || gross === '') return ''
            const num = Number(gross) - Number(this.form.actualImpurityWeight || 0)
            return String(Math.round(num * 100) / 100)
        },
        // 净重大写:中文大写
        computedNetWeightUpper() {
            const net = this.computedNetWeight
            if (net === '' || net === null || net === undefined) return ''
            return numberToChineseUpper(net)
        },
        // 业务摘要
        computedBusinessSummary() {
            const parts = []
            const weightItems = (this.weighList || [])
                .map(item => {
                    const name = item.productName || ''
                    const qty = item.quantity === null || item.quantity === undefined ? '' : item.quantity
                    if (!name && qty === '') return ''
                    return `${name}${qty}公斤`
                })
                .filter(text => !!text)
            if (weightItems.length) parts.push(weightItems.join('、'))
            const deductionNames = (this.form.deductionTypes || [])
                .map(code => getDicName('DEDUCTION_TYPE', code, this.dicOptions.DEDUCTION_TYPE))
                .filter(name => !!name)
            if (deductionNames.length) parts.push(deductionNames.join('、'))
            if (this.form.supplierStockMaterial) parts.push(`供应存欠料:${this.form.supplierStockMaterial}`)
            if (this.form.logisticsStockMaterial) parts.push(`物流存欠料:${this.form.logisticsStockMaterial}`)
            if (this.form.plateNumber) parts.push(`车牌号:${this.form.plateNumber}`)
            return parts.join(',')
        },
        // 单据备注 = 业务摘要 + 特别说明
        computedDocumentRemark() {
            const summary = this.computedBusinessSummary || ''
            const note = this.form.specialNote || ''
            return [summary, note].filter(text => !!text).join('\n')
        }
    },
    onLoad(query) {
        this.id = (query && query.id) || ''
    },
    created() {
        this.planSheet.fetchFn = this.fetchPlans.bind(this)
        this.loadDicData()
        this.loadVarietyOptions()
        this.loadDetail()
    },
    methods: {
        async loadDicData() {
            try {
                const results = await getDicByCodes(['TYPE', 'DEDUCTION_TYPE'])
                this.dicOptions.TYPE = (results.TYPE && results.TYPE.data) || []
                this.dicOptions.DEDUCTION_TYPE = (results.DEDUCTION_TYPE && results.DEDUCTION_TYPE.data) || []
            } catch (e) {
                this.dicOptions = { TYPE: [], DEDUCTION_TYPE: [] }
            }
        },
        async loadVarietyOptions() {
            try {
                const res = await breedRelationshipQueryApi({ pageIndex: 1, pageSize: 9999 })
                const _data = (res && res.data) || {}
                this.varietyOptions = _data.datas || _data.list || _data.records || []
            } catch (e) {
                this.varietyOptions = []
            }
        },
        loadDetail() {
            if (!this.id) {
                uni.showToast({ title: '缺少单据ID', icon: 'none' })
                return
            }
            uni.showLoading({ title: '加载中...', mask: true })
            weighTicketDetailApi({ id: this.id })
                .then(res => {
                    const data = res && res.data ? (res.data.data || res.data) : {}
                    const buyout = !!data.buyout
                    this.form = {
                        code: data.code || '',
                        type: data.type != null ? String(data.type) : '',
                        planCode: data.planCode || data.planCodes || '',
                        unit: data.unit || '',
                        supplierName: data.supplierName || '',
                        companyShortName: data.companyShortName || '',
                        totalGrossWeight: data.totalGrossWeight == null ? '' : String(data.totalGrossWeight),
                        actualImpurityWeight: data.actualImpurityWeight == null ? '' : String(data.actualImpurityWeight),
                        deductionTypes: data.deductionTypes ? String(data.deductionTypes).split(',').filter(Boolean) : [],
                        supplierStockMaterial: data.supplierStockMaterial || '',
                        logisticsStockMaterial: data.logisticsStockMaterial || '',
                        plateNumber: data.plateNumber || '',
                        specialNote: data.specialNote || ''
                    }
                    // 计划选择回显:行对象缓存供提交 planIds 使用(id 取计划明细行上的计划 id)
                    this.planList = (Array.isArray(data.planLines) ? data.planLines : []).map(it => ({ ...it }))
                    this.selectedPlanRows = this.planList.map(item => ({
                        id: item.procurementPlanId || item.id,
                        code: item.planCode || '',
                        buyout: buyout,
                        supplierName: data.supplierName || '',
                        companyName: data.companyShortName || '',
                        workshopName: ''
                    }))
                    this.weighList = (Array.isArray(data.weighLines) ? data.weighLines : []).map(it => ({ ...it, id: it.id || genRowId() }))
                    this.applyList = (Array.isArray(data.applyLines) ? data.applyLines : []).map(it => ({ ...it, id: it.id || genRowId() }))
                })
                .catch(() => {
                    uni.showToast({ title: '加载详情失败', icon: 'none' })
                })
                .finally(() => {
                    uni.hideLoading()
                })
        },
        getTypeLabel() {
            const found = (this.dicOptions.TYPE || []).find(it => String(it.code) === String(this.form.type))
            return found ? found.name : ''
        },
        onTypeChange(e) {
            const idx = Number(e.detail.value)
            const opt = (this.dicOptions.TYPE || [])[idx]
            this.form.type = opt && opt.code != null ? String(opt.code) : ''
        },
        // 计划选择弹窗数据源
        fetchPlans({ pageIndex, pageSize, extra }) {
            const keyword = (extra && extra.keyword) || ''
            const params = {
                pageIndex,
                pageSize,
                code: keyword || undefined
            }
            return weighingTicketPlansApi(params).then(res => {
                const _data = (res && res.data) || {}
                const records = _data.datas || _data.list || _data.records || []
                const totalCount = _data.totalCount || _data.count || 0
                const hasNext = _data.hasNext || false
                return { records, totalCount, hasNext }
            }).catch(() => ({ records: [], totalCount: 0, hasNext: false }))
        },
        openPlanSheet() {
            this.planSheet.selectedKeys = this.selectedPlanRows.map(it => it.id)
            this.planSheet.visible = true
        },
        onPlanConfirm({ items }) {
            const list = items || []
            if (!list.length) {
                this.selectedPlanRows = []
                this.form.planCode = ''
                this.form.supplierName = ''
                this.form.companyShortName = ''
                this.planList = []
                this.weighList = []
                return
            }
            // 校验:所选计划的「是否买断、供料单位、收料单位、车间」必须一致
            const first = list[0]
            const isSame = list.every(item =>
                item.buyout === first.buyout &&
                item.supplierName === first.supplierName &&
                item.companyName === first.companyName &&
                item.workshopName === first.workshopName
            )
            if (!isSame) {
                uni.showToast({ title: '是否买断,供料单位,收料单位应保持一致', icon: 'none' })
                this.planSheet.selectedKeys = this.selectedPlanRows.map(it => it.id)
                return
            }
            this.selectedPlanRows = list.map(it => ({ ...it }))
            this.form.planCode = list.map(it => it.code).filter(Boolean).join(',')
            this.form.supplierName = first.supplierName || ''
            this.form.companyShortName = (first.companyName || '') + (first.workshopName || '')
            // 查询计划明细行,填充计划单明细;过磅明细初始化为计划明细拷贝
            weighTicketPlanLinesApi(list.map(it => it.id)).then(res => {
                const lines = (res && res.data) || []
                this.planList = lines.map(it => ({ ...it }))
                this.weighList = lines.map(it => ({ ...it, id: it.id || genRowId() }))
            }).catch(() => {
                this.planList = []
                this.weighList = []
            })
        },
        getWeightProductLabel(item) {
            if (!item.productId) return ''
            const found = (this.planList || []).find(it => it.productId === item.productId)
            return found ? [found.productName, found.planCode].filter(Boolean).join(' ') : ''
        },
        // 过磅品种改选:整行替换为选中计划明细数据
        handleWeightProductChange(idx, optIdx) {
            const raw = (this.planList || [])[optIdx]
            if (!raw) return
            const rowId = this.weighList[idx].id
            this.weighList.splice(idx, 1, { ...raw, id: rowId })
        },
        getVarietyLabel(item) {
            if (!item.breedRelationshipId) return ''
            const found = (this.varietyOptions || []).find(it => it.id === item.breedRelationshipId)
            return found ? [found.productName, found.code].filter(Boolean).join(' ') : ''
        },
        handleVarietyChange(idx, optIdx) {
            const raw = (this.varietyOptions || [])[optIdx]
            if (!raw) return
            const row = this.applyList[idx]
            row.category = raw.code || ''
            row.breedRelationshipId = raw.id || ''
        },
        addWeightRow() {
            this.weighList.push({
                id: genRowId(),
                procurementPlanId: '',
                planCode: '',
                productId: '',
                invoiceProductName: '',
                quantity: ''
            })
        },
        addApplyRow() {
            this.applyList.push({
                id: genRowId(),
                category: '',
                breedRelationshipId: '',
                quantity: ''
            })
        },
        removeRow(type, idx) {
            if (type === 'weigh') this.weighList.splice(idx, 1)
            else if (type === 'apply') this.applyList.splice(idx, 1)
        },
        validate() {
            const f = this.form
            if (!f.code) return this.tip('缺少编号')
            if (!f.type) return this.tip('请选择类型')
            if (!this.selectedPlanRows.length) return this.tip('请选择计划编号')
            if (f.totalGrossWeight === '' || f.totalGrossWeight == null) return this.tip('请输入过磅总重')
            if (f.actualImpurityWeight === '' || f.actualImpurityWeight == null) return this.tip('请输入实际伙重')
            if (!f.deductionTypes || !f.deductionTypes.length) return this.tip('请选择来料扣杂类型')
            if (!f.supplierStockMaterial) return this.tip('请输入供应存欠料')
            if (!f.logisticsStockMaterial) return this.tip('请输入物流存欠料')
            if (!f.plateNumber) return this.tip('请输入车牌号')
            // 过磅明细:品种、数量必填
            const weightList = this.weighList || []
            for (let i = 0; i < weightList.length; i++) {
                const row = weightList[i]
                if (!row.productId) return this.tip(`过磅明细第${i + 1}行:请选择过磅品种`)
                if (row.quantity === '' || row.quantity == null) return this.tip(`过磅明细第${i + 1}行:请输入过磅数量`)
            }
            // 申请数量明细:类别、数量必填(买断时)
            if (this.isBuyout) {
                const applyList = this.applyList || []
                for (let i = 0; i < applyList.length; i++) {
                    const row = applyList[i]
                    if (!row.breedRelationshipId) return this.tip(`申请数量明细第${i + 1}行:请选择类别`)
                    if (row.quantity === '' || row.quantity == null) return this.tip(`申请数量明细第${i + 1}行:请输入数量`)
                }
            }
            return true
        },
        tip(msg) {
            uni.showToast({ title: msg, icon: 'none' })
            return false
        },
        buildSubmitData() {
            return {
                id: this.id,
                code: this.form.code,
                type: this.form.type,
                planIds: this.selectedPlanRows.map(it => it.id),
                weighLines: (this.weighList || []).map(row => ({
                    procurementPlanId: row.procurementPlanId || '',
                    planCode: row.planCode || '',
                    productId: row.productId || '',
                    invoiceProductName: row.invoiceProductName || '',
                    quantity: row.quantity === null || row.quantity === undefined ? '' : String(row.quantity),
                    itemId: row.id
                })),
                applyLines: (this.applyList || []).map(row => ({
                    category: row.category || '',
                    breedRelationshipId: row.breedRelationshipId || '',
                    quantity: row.quantity === null || row.quantity === undefined ? '' : String(row.quantity),
                    itemId: row.breedRelationshipId
                })),
                unit: this.form.unit,
                materialName: this.materialName || null,
                totalGrossWeight: this.form.totalGrossWeight === '' ? null : Number(this.form.totalGrossWeight),
                actualImpurityWeight: this.form.actualImpurityWeight === '' ? null : Number(this.form.actualImpurityWeight),
                netWeight: this.computedNetWeight === '' ? null : Number(this.computedNetWeight),
                netWeightUpper: this.computedNetWeightUpper || null,
                deductionTypes: (this.form.deductionTypes || []).join(',') || null,
                supplierStockMaterial: this.form.supplierStockMaterial || null,
                logisticsStockMaterial: this.form.logisticsStockMaterial || null,
                plateNumber: this.form.plateNumber || null,
                businessSummary: this.computedBusinessSummary || null,
                specialNote: this.form.specialNote || null,
                documentRemark: this.computedDocumentRemark || null
            }
        },
        async onSubmit() {
            if (!this.validate()) return
            const confirmRes = await new Promise(resolve => {
                uni.showModal({ title: '提示', content: '确定保存修改吗?', confirmText: '确定', cancelText: '取消', success: resolve })
            })
            if (!(confirmRes && confirmRes.confirm)) return
            uni.showLoading({ title: '保存中...', mask: true })
            weighTicketUpdateApi(this.buildSubmitData())
                .then(() => {
                    uni.hideLoading()
                    uni.showToast({ title: '保存成功', icon: 'none' })
                    try {
                        uni.setStorageSync('WEIGHT_TICKET_LIST_NEED_REFRESH', '1')
                        uni.setStorageSync('WEIGHT_TICKET_DETAIL_NEED_REFRESH', '1')
                    } catch (e) {}
                    setTimeout(() => { uni.navigateBack() }, 400)
                })
                .catch(e => {
                    uni.hideLoading()
                    uni.showToast({ title: (e && (e.msg || e.message)) || '保存失败', icon: 'none' })
                })
        }
    }
}

// 生成前端临时行 id
function genRowId() {
    return 'row_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8)
}

// 数字转中文大写(对齐 PC 端 useWeightTicketForm.ts)
function numberToChineseUpper(num) {
    if (num === null || num === undefined || num === '' || isNaN(Number(num))) return '零'
    const n = Number(num)
    if (!isFinite(n)) return '零'

    const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
    const smallUnits = ['', '拾', '佰', '仟']
    const bigUnits = ['', '万', '亿', '兆']

    const negative = n < 0
    const abs = Math.abs(n)
    const parts = abs.toString().split('.')
    const intStrRaw = parts[0]
    const decStrRaw = parts[1] || ''
    const s = intStrRaw
    const len = s.length

    let intPart = ''
    let zeroFlag = false
    for (let i = 0; i < len; i++) {
        const d = parseInt(s[i], 10)
        const pos = len - 1 - i
        const unitIdx = pos % 4
        const groupIdx = Math.floor(pos / 4)
        if (d !== 0) {
            if (zeroFlag) {
                intPart += digit[0]
                zeroFlag = false
            }
            intPart += digit[d] + smallUnits[unitIdx]
        } else {
            zeroFlag = true
        }
        if (unitIdx === 0) {
            const start = Math.max(0, len - (groupIdx + 1) * 4)
            const end = len - groupIdx * 4
            const groupDigits = s.slice(start, end)
            if (!/^0+$/.test(groupDigits)) {
                intPart += bigUnits[groupIdx] || ''
            }
        }
    }
    if (intPart === '') intPart = digit[0]

    let result = intPart
    if (decStrRaw) {
        const decChars = decStrRaw
            .split('')
            .map(c => digit[parseInt(c, 10)])
            .join('')
        result += '点' + decChars
    }
    return (negative ? '负' : '') + result
}
</script>

<style lang="scss" scoped>
.page {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.scroll {
    flex: 1;
    padding: 12rpx 0 200rpx !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;
    }
}

::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: 240rpx;
                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;
                }
            }

            .serial-number-row {
                display: flex;
                align-items: center;

                .generate-btn {
                    margin-left: 24rpx;
                    height: 48rpx;
                    line-height: 48rpx;
                    padding: 0 24rpx;
                    font-size: 24rpx;
                    border-radius: 8rpx;
                    background: $theme-primary;
                    color: #fff;
                }
            }
        }
    }
}

.readonly-text {
    color: rgba(0, 0, 0, 0.9);
    font-size: 32rpx;
    line-height: 48rpx;
    text-align: right;
    white-space: pre-wrap;
    word-break: break-all;
}

.value-code {
    width: 260rpx;
    text-align: left;
}

.picker-value {
    font-size: 32rpx;
    color: rgba(0, 0, 0, 0.9);
    line-height: 48rpx;
    text-align: right;
    min-height: 48rpx;

    &.placeholder {
        color: rgba(0, 0, 0, 0.4);
    }
}

.sub-table,
.remark-section {
    margin-top: 20rpx;
    background: #fff;
}

.header {
    display: flex;
    align-items: center;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .opCollapse {
        width: 32rpx;
        height: 28rpx;
        margin-right: 16rpx;
        margin-top: 8rpx;
    }

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

    .ops {
        display: flex;
        align-items: center;

        .opAdd {
            width: 40rpx;
            height: 40rpx;
        }
    }
}

.add-list {
    padding: 0 0 16rpx;

    .empty-tip {
        text-align: center;
        padding: 60rpx 0;
        color: rgba(0, 0, 0, 0.4);
        font-size: 28rpx;
    }

    .block {
        border-bottom: 1rpx solid #f0f0f0;

        &:last-child {
            border-bottom: none;
        }

        .block-ops {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 48rpx;
            padding: 20rpx 32rpx;
            background: #f8f8f8;

            .del,
            .toggle {
                display: flex;
                align-items: center;
                font-size: 28rpx;
                color: rgba(0, 0, 0, 0.6);

                .icon {
                    width: 32rpx;
                    height: 32rpx;
                    margin-right: 8rpx;
                }
            }

            .del {
                color: #d54941;
            }
        }
    }
}

.section-content {
    padding: 32rpx;
}

.form-group {
    margin: 24rpx 0 32rpx;

    .item-title {
        display: flex;
        align-items: center;
        font-size: 32rpx;
        color: rgba(0, 0, 0, 0.9);
        margin-bottom: 20rpx;
        position: relative;
        padding-left: 16rpx;

        .required {
            color: red;
            position: absolute;
            left: 0;
        }
    }
}

.remark-group {
    margin-bottom: 32rpx;

    &:last-child {
        margin-bottom: 0;
    }

    .remark-label {
        display: flex;
        align-items: center;
        font-size: 32rpx;
        color: rgba(0, 0, 0, 0.9);
        margin-bottom: 16rpx;
    }
}
</style>