modify.vue 37.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
<template>
  <view class="page">
    <scroll-view scroll-y class="scroll">
      <uni-list>
        <uni-list-item class="select-item" :class="form.planCode ? '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">{{ form.planCode || '-' }}</text>
          </template>
        </uni-list-item>

        <uni-list-item title="公司名称">
          <template v-slot:footer>
            <uni-easyinput v-model="companyNameDisplay" :inputBorder="false" disabled 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="detail.supplierName" :inputBorder="false" placeholder="请输入供应商名称" />
          </template>
        </uni-list-item>

        <uni-list-item title="采购处">
          <template v-slot:footer>
            <uni-easyinput v-model="purchaseDepartmentDisplay" :inputBorder="false" disabled placeholder="-" />
          </template>
        </uni-list-item>

        <uni-list-item title="区域">
          <template v-slot:footer>
            <uni-easyinput v-model="regionDisplay" :inputBorder="false" disabled placeholder="-" />
          </template>
        </uni-list-item>

        <uni-list-item title="日期">
          <template v-slot:footer>
            <uni-easyinput v-model="dateDisplay" :inputBorder="false" disabled 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="detail.validityPeriod" :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="detail.quoterName" :inputBorder="false" placeholder="请输入报价人" />
          </template>
        </uni-list-item>

        <uni-list-item class="select-item" :class="typeof detail.longTermOperation === 'boolean' ? 'is-filled' : 'is-empty'" clickable
          @click="toggleBool('longTermOperation')" :rightText="boolText(detail.longTermOperation) || '请选择'" 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="typeof detail.terminalCustomer === 'boolean' ? 'is-filled' : 'is-empty'" clickable
          @click="toggleBool('terminalCustomer')" :rightText="boolText(detail.terminalCustomer) || '请选择'" 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="typeof detail.priced === 'boolean' ? 'is-filled' : 'is-empty'" clickable
          @click="toggleBool('priced')" :rightText="boolText(detail.priced) || '请选择'" showArrow>
          <template v-slot:body>
            <view class="item-title"><text class="required">*</text><text>是否未点价</text></view>
          </template>
        </uni-list-item>

        <uni-list-item v-if="detail.priced === true">
          <template v-slot:body>
            <view class="item-title"><text class="required">*</text><text>点价截止日期</text></view>
          </template>
          <template v-slot:footer>
            <uni-datetime-picker type="date" v-model="detail.pricingDeadline" return-type="string" />
          </template>
        </uni-list-item>

        <uni-list-item v-if="detail.priced === true" class="select-item" :class="typeof detail.temporaryPrice === 'boolean' ? 'is-filled' : 'is-empty'" clickable
          @click="toggleBool('temporaryPrice')" :rightText="boolText(detail.temporaryPrice) || '请选择'" 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="typeof detail.otherExpenseSettlement === 'boolean' ? 'is-filled' : 'is-empty'" clickable
          @click="toggleBool('otherExpenseSettlement')" :rightText="boolText(detail.otherExpenseSettlement) || '请选择'" 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="detail.deliveryMode ? 'is-filled' : 'is-empty'" clickable
          @click="openDeliverySheet" :rightText="getDeliveryMethodLabel()" 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="typeof detail.commodityBuyout === 'boolean' ? 'is-filled' : 'is-empty'" clickable
          @click="toggleBool('commodityBuyout')" :rightText="boolText(detail.commodityBuyout) || '请选择'" 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="typeof detail.qualityBuyout === 'boolean' ? 'is-filled' : 'is-empty'" clickable
          @click="toggleBool('qualityBuyout')" :rightText="boolText(detail.qualityBuyout) || '请选择'" 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="typeof detail.quantityBuyout === 'boolean' ? 'is-filled' : 'is-empty'" clickable
          @click="toggleBool('quantityBuyout')" :rightText="boolText(detail.quantityBuyout) || '请选择'" 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="typeof detail.doorDelivery === 'boolean' ? 'is-filled' : 'is-empty'" clickable
          @click="toggleBool('doorDelivery')" :rightText="boolText(detail.doorDelivery) || '请选择'" 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="shippingCostDisplay" :inputBorder="false" disabled 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="detail.loadingFee"
              type="digit"
              :inputBorder="false"
              placeholder="请输入装车费"
              @input="onNonNegativeInput('loadingFee')"
              @blur="onNonNegativeBlur('loadingFee', 2)"
            />
          </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="detail.invoiceProductName" :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-datetime-picker type="date" v-model="detail.deliveryDate" return-type="string" />
          </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="detail.settlementMethod" :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="detail.settlementRatio"
              type="digit"
              :inputBorder="false"
              placeholder="请输入结算比例"
              @input="onNonNegativeInput('settlementRatio')"
              @blur="onNonNegativeBlur('settlementRatio', 4)"
            />
          </template>
        </uni-list-item>

        <uni-list-item title="价格表编号">
          <template v-slot:footer>
            <uni-easyinput v-model="priceTableDisplay" :inputBorder="false" disabled 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="detail.coordinationReason" :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="detail.invoiceTypeStatus" :inputBorder="false" placeholder="请输入票类状况" />
          </template>
        </uni-list-item>

        <uni-list-item v-if="attachmentList.length" title="附件">
          <template v-slot:footer>
            <view class="attach-list">
              <view v-for="(at, idx) in attachmentList" :key="idx" class="attach-item">
                <text class="attach-name">{{ at.name }}</text>
                <text class="attach-view" @click.stop="onPreviewAttachment(at)">查看</text>
              </view>
            </view>
          </template>
        </uni-list-item>

        <ProductRel
          ref="productRel"
          mode="edit"
          :list="lineList"
          :product-options="productOptions"
          :workshop-options="workshopOptions"
          @change="onLineChange"
        />
      </uni-list>

      <view class="material-condition-section">
        <view class="section-header">
          <image class="opCollapse" src="/static/images/title.png" />
          <text class="section-title">料质状况</text>
        </view>
        <view class="section-content">
          <view class="form-row">
            <text class="form-label">是否启用料质状况</text>
            <text class="form-value toggle-link" @click="toggleBool('materialConditionEnabled')">{{ boolText(detail.materialConditionEnabled) || '请选择' }}</text>
          </view>
          <template v-if="detail.materialConditionEnabled">
            <view v-for="mc in materialConditionConfigs" :key="mc.field" class="material-group">
              <text class="material-label">{{ mc.label }}</text>
              <view class="tag-list">
                <view
                  v-for="opt in getDictOptions(mc.dictCode)"
                  :key="opt.code"
                  class="tag-btn"
                  :class="{ active: isTagSelected(mc.field, opt.code) }"
                  @click="toggleTag(mc.field, opt.code)"
                >
                  {{ opt.name }}
                </view>
              </view>
            </view>
          </template>
        </view>
      </view>

      <view class="remark-section">
        <view class="section-header">
          <image class="opCollapse" src="/static/images/title.png" />
          <text class="section-title">备注</text>
        </view>
        <view class="section-content">
          <uni-easyinput type="textarea" v-model="detail.remark" :inputBorder="false" placeholder="请输入备注" />
        </view>
      </view>

      <view class="remark-section">
        <view class="section-header">
          <image class="opCollapse" src="/static/images/title.png" />
          <text class="section-title"><text class="required">*</text>变更事由</text>
        </view>
        <view class="section-content">
          <uni-easyinput type="textarea" v-model="detail.changeReason" :inputBorder="false" placeholder="请输入变更事由" />
        </view>
      </view>
    </scroll-view>

    <view class="bottom-bar">
      <button class="btn btn-outline" @click="onBack">取消</button>
      <button class="btn btn-primary" @click="onSubmit">保存</button>
    </view>

    <SingleSelectSheet
      :visible.sync="deliverySheetVisible"
      title="交提货方式"
      :options="deliveryOptions"
      v-model="deliverySheetValue"
      @confirm="onDeliveryConfirm"
    />
  </view>
</template>

<script>
import ProductRel from './productRel.vue'
import SingleSelectSheet from '@/components/single-select/index.vue'
import { procurementPlanChangeFindByIdApi, procurementPlanChangeUpdateApi } from '@/api/procure-manage/procurementPlan.js'
import {
  breedRelationshipQueryApi,
  workshopQueryApi
} from '@/api/devManage.js'
import { getDicByCodes } from '@/utils/dic.js'

export default {
  name: 'SchedulePlanModify',
  components: { ProductRel, SingleSelectSheet },
  data() {
    return {
      id: '',
      form: {
        planId: '',
        planCode: ''
      },
      detail: {},
      attachmentList: [],
      materialConditionConfigs: [
        { field: 'materialConditionCopperRice', label: '铜米', dictCode: 'COPPER_RICE' },
        { field: 'materialConditionBrightCopper', label: '光亮铜', dictCode: 'BRIGHT_COPPER' },
        { field: 'materialConditionFirstClass', label: '一特', dictCode: 'FIRST_CLASS' },
        { field: 'materialConditionSecondClass', label: '二特', dictCode: 'SECOND_CLASS' },
        { field: 'materialConditionTinCoated', label: '镀锡紫', dictCode: 'TIN_COATED' },
        { field: 'materialConditionScrap', label: '角料', dictCode: 'SCRAP' },
        { field: 'materialConditionWhiteYellow', label: '镀白黄', dictCode: 'WHITE_YELLOW' },
        { field: 'materialConditionPhosphorCopper', label: '磷铜', dictCode: 'PHOSPHOR_COPPER' }
      ],
      dicOptions: {
        DELIVERY_METHOD: []
      },
      dictData: {},
      lineList: [],
      productOptions: [],
      workshopOptions: [],
      deliverySheetVisible: false,
      deliverySheetValue: '',
      deliveryOptions: []
    }
  },
  computed: {
    companyNameDisplay() {
      var d = this.detail || {}
      return d.companyShortName != null ? d.companyShortName : (d.companyName != null ? d.companyName : '')
    },
    purchaseDepartmentDisplay() {
      var d = this.detail || {}
      return d.purchaseDepartmentName != null ? d.purchaseDepartmentName : (d.purchaseDepartment != null ? d.purchaseDepartment : '')
    },
    regionDisplay() {
      var d = this.detail || {}
      return d.regionName != null ? d.regionName : (d.region != null ? d.region : '')
    },
    dateDisplay() {
      var d = this.detail || {}
      var s = d.date == null ? '' : String(d.date).trim()
      return s.length >= 10 ? s.slice(0, 10) : s
    },
    shippingCostDisplay() {
      var v = (this.detail || {}).shippingCost
      if (v == null || v === '') return ''
      var n = Number(v)
      if (isNaN(n)) return String(v)
      return n.toLocaleString('zh-CN', { maximumFractionDigits: 4 })
    },
    priceTableDisplay() {
      var d = this.detail || {}
      var code = d.priceTableCode != null ? d.priceTableCode : (d.priceId != null ? d.priceId : '')
      var name = d.priceTableName || ''
      return name ? (name + (code ? ' (' + code + ')' : '')) : code
    }
  },
  onLoad(query) {
    this.id = (query && query.id) || ''
    this.loadDictData()
    this.loadRefData()
    if (this.id) {
      this.loadDetailById(this.id)
    }
  },
  methods: {
    safeText(v) {
      var s = v == null ? '' : String(v)
      return s.trim() ? s : '-'
    },
    boolText(v) {
      if (typeof v !== 'boolean') return ''
      return v ? '是' : '否'
    },
    toNumber(v) {
      if (v == null || v === '') return 0
      var n = Number(v)
      return isNaN(n) ? 0 : n
    },
    toFixed(v, n) {
      var num = Number(v)
      if (isNaN(num)) return ''
      return num.toFixed(n)
    },
    async loadDictData() {
      var codes = [].concat(
        this.materialConditionConfigs.map(function (mc) { return mc.dictCode }),
        ['DELIVERY_METHOD']
      )
      try {
        var results = await getDicByCodes(codes)
        var d = results || {}
        this.dictData = d
        this.dicOptions.DELIVERY_METHOD = (d.DELIVERY_METHOD && d.DELIVERY_METHOD.data) || []
        this.deliveryOptions = this.dicOptions.DELIVERY_METHOD.map(function (o) {
          return { label: o.name || o.label || '', value: o.code != null ? o.code : o.value }
        })
      } catch (e) {
        this.dictData = {}
      }
    },
    async loadRefData() {
      try {
        var results = await Promise.all([
          this.$pCall(breedRelationshipQueryApi, { pageIndex: 1, pageSize: 1000 }),
          this.$pCall(workshopQueryApi, { pageIndex: 1, pageSize: 1000 })
        ])
        var r1 = (results[0] && results[0].data) ? results[0].data : {}
        var r2 = (results[1] && results[1].data) ? results[1].data : {}
        this.productOptions = (r1.datas && Array.isArray(r1.datas)) ? r1.datas : ((r1.list && Array.isArray(r1.list)) ? r1.list : ((r1.records && Array.isArray(r1.records)) ? r1.records : []))
        this.workshopOptions = (r2.datas && Array.isArray(r2.datas)) ? r2.datas : ((r2.list && Array.isArray(r2.list)) ? r2.list : ((r2.records && Array.isArray(r2.records)) ? r2.records : []))
        this.fillLineNames()
      } catch (e) {
        this.productOptions = []
        this.workshopOptions = []
      }
    },
    $pCall(fn, params) {
      try { return Promise.resolve(fn(params)) } catch (e) { return Promise.reject(e) }
    },
    getDictOptions(dictCode) {
      var data = this.dictData[dictCode]
      return (data && data.data) ? data.data : []
    },
    getDeliveryMethodLabel() {
      var opts = this.dicOptions.DELIVERY_METHOD || []
      var v = String(this.detail.deliveryMode != null ? this.detail.deliveryMode : '')
      if (!v) return '请选择'
      for (var i = 0; i < opts.length; i++) {
        var o = opts[i]
        var code = o.code != null ? String(o.code) : (o.value != null ? String(o.value) : '')
        if (code === v) return o.name || o.label || v
      }
      return v
    },
    async loadDetailById(id) {
      if (!id) return
      try {
        var res = await procurementPlanChangeFindByIdApi({ id: id })
        var d = (res && res.data) ? res.data : {}
        var boolFields = ['longTermOperation', 'terminalCustomer', 'priced', 'temporaryPrice', 'otherExpenseSettlement', 'commodityBuyout', 'qualityBuyout', 'quantityBuyout', 'doorDelivery', 'materialConditionEnabled']
        boolFields.forEach(function (f) {
          var v = d[f]
          if (typeof v === 'string') {
            d[f] = v === 'true' || v === '1'
          } else if (typeof v === 'number') {
            d[f] = v === 1
          } else {
            d[f] = !!v
          }
        })
        this.materialConditionConfigs.forEach(function (mc) {
          var v = d[mc.field]
          if (typeof v === 'string' && v) {
            d[mc.field] = v.split(',').filter(Boolean)
          } else if (!Array.isArray(v)) {
            d[mc.field] = []
          }
        })
        d.pricingDeadline = this.trimDate(d.pricingDeadline)
        d.deliveryDate = this.trimDate(d.deliveryDate)
        this.detail = d
        this.form.planId = d.procurementPlanId != null ? d.procurementPlanId : (d.planId != null ? d.planId : (d.id || ''))
        this.form.planCode = d.procurementPlanCode != null ? d.procurementPlanCode : (d.planCode != null ? d.planCode : d.code)
        var lines = d.lines || d.procurementPlanLineList || d.lineList || []
        this.lineList = Array.isArray(lines) ? lines.slice() : []
        this.buildAttachmentList()
        this.fillLineNames()
      } catch (e) {
        uni.showToast({ title: '加载详情失败', icon: 'none' })
      }
    },
    trimDate(v) {
      if (v == null || v === '') return ''
      var s = String(v).trim()
      return s.length >= 10 ? s.slice(0, 10) : s
    },
    buildAttachmentList() {
      var ids = this.detail.attachmentFileIds
      var names = this.detail.attachmentFileNames
      var idArr = (typeof ids === 'string' && ids) ? ids.split(',').filter(Boolean) : (Array.isArray(ids) ? ids : [])
      var nameArr = (typeof names === 'string' && names) ? names.split(',').filter(Boolean) : (Array.isArray(names) ? names : [])
      var len = Math.max(idArr.length, nameArr.length)
      var list = []
      for (var i = 0; i < len; i++) {
        list.push({ id: idArr[i] || '', name: nameArr[i] || ('附件' + (i + 1)) })
      }
      this.attachmentList = list
    },
    onPreviewAttachment(at) {
      if (!at || !at.id) {
        uni.showToast({ title: '无法查看', icon: 'none' })
        return
      }
      uni.showToast({ title: '查看附件 ' + at.name, icon: 'none' })
    },
    fillLineNames() {
      var list = Array.isArray(this.lineList) ? this.lineList : []
      if (!list.length) return
      var pOpts = Array.isArray(this.productOptions) ? this.productOptions : []
      var wOpts = Array.isArray(this.workshopOptions) ? this.workshopOptions : []
      this.lineList = list.map(function (row) {
        var r = Object.assign({}, row)
        var pid = r.productId != null ? String(r.productId) : ''
        var wid = r.workshopId != null ? String(r.workshopId) : ''
        if ((r.productName == null || String(r.productName).trim() === '') && pid) {
          var p = pOpts.find(function (o) {
            var id = o.id != null ? String(o.id) : (o.productId != null ? String(o.productId) : (o.value != null ? String(o.value) : ''))
            return id === pid
          })
          if (p) {
            r.productName = p.name != null ? p.name : (p.productName != null ? p.productName : (p.label != null ? p.label : ''))
          }
        }
        if ((r.workshopName == null || String(r.workshopName).trim() === '') && wid) {
          var w = wOpts.find(function (o) {
            var id = o.id != null ? String(o.id) : (o.workshopId != null ? String(o.workshopId) : (o.value != null ? String(o.value) : ''))
            return id === wid
          })
          if (w) {
            r.workshopName = w.name != null ? w.name : (w.workshopName != null ? w.workshopName : (w.label != null ? w.label : ''))
          }
        }
        return r
      })
    },
    onLineChange(list) {
      this.lineList = Array.isArray(list) ? list.slice() : []
    },
    toggleBool(field) {
      var cur = this.detail[field]
      this.$set(this.detail, field, cur !== true)
    },
    onNonNegativeInput(field) {
      var v = String(this.detail[field] != null ? this.detail[field] : '')
      v = v.replace(/[^0-9.]/g, '')
      v = v.replace(/(\..*)\./g, '$1')
      this.$set(this.detail, field, v)
    },
    onNonNegativeBlur(field, digits) {
      var raw = this.detail[field]
      if (raw === '' || raw === null || raw === undefined) {
        this.$set(this.detail, field, '')
        return
      }
      var val = parseFloat(raw)
      if (isNaN(val)) val = 0
      var m = Math.pow(10, digits)
      var rounded = Math.round(val * m) / m
      this.$set(this.detail, field, rounded)
    },
    openDeliverySheet() {
      var cur = this.detail.deliveryMode != null ? this.detail.deliveryMode : ''
      var match = this.deliveryOptions.find(function (o) { return String(o.value) === String(cur) })
      this.deliverySheetValue = match ? match.value : ''
      this.deliverySheetVisible = true
    },
    onDeliveryConfirm(e) {
      this.$set(this.detail, 'deliveryMode', e.value != null ? e.value : '')
    },
    isTagSelected(field, code) {
      var selected = this.detail ? this.detail[field] : undefined
      if (Array.isArray(selected)) return selected.indexOf(code) >= 0
      if (typeof selected === 'string' && selected) {
        return selected.split(',').indexOf(code) >= 0
      }
      return false
    },
    toggleTag(field, code) {
      var selected = this.detail[field]
      var arr = Array.isArray(selected) ? selected.slice() : []
      var idx = arr.indexOf(code)
      if (idx >= 0) {
        arr.splice(idx, 1)
      } else {
        arr.push(code)
      }
      this.$set(this.detail, field, arr)
    },
    validateForm() {
      if (!this.form.planId) {
        uni.showToast({ title: '请选择计划', icon: 'none' })
        return false
      }
      var d = this.detail || {}
      var textChecks = [
        { key: 'supplierName', title: '供应商名称' },
        { key: 'validityPeriod', title: '报价时效' },
        { key: 'quoterName', title: '报价人' },
        { key: 'deliveryMode', title: '交提货方式' },
        { key: 'loadingFee', title: '装车费' },
        { key: 'invoiceProductName', title: '开票品名' },
        { key: 'deliveryDate', title: '交货日期' },
        { key: 'settlementMethod', title: '结算方式' },
        { key: 'settlementRatio', title: '结算比例' },
        { key: 'coordinationReason', title: '协调事由' },
        { key: 'invoiceTypeStatus', title: '票类状况' },
        { key: 'changeReason', title: '变更事由' }
      ]
      for (var i = 0; i < textChecks.length; i++) {
        var tc = textChecks[i]
        var tv = d[tc.key]
        if (tv === '' || tv === null || tv === undefined) {
          uni.showToast({ title: '请填写' + tc.title, icon: 'none' })
          return false
        }
      }
      var boolChecks = [
        { key: 'longTermOperation', title: '是否长单操作' },
        { key: 'terminalCustomer', title: '是否终端客户' },
        { key: 'priced', title: '是否未点价' },
        { key: 'otherExpenseSettlement', title: '其他费用凭票到厂另行结算' },
        { key: 'commodityBuyout', title: '是否通货买断' },
        { key: 'qualityBuyout', title: '是否质量买断' },
        { key: 'quantityBuyout', title: '是否数量买断' },
        { key: 'doorDelivery', title: '是否送货上门' }
      ]
      if (d.priced === true) {
        boolChecks.push({ key: 'temporaryPrice', title: '是否暂定价' })
        var pd = d.pricingDeadline
        if (pd === '' || pd === null || pd === undefined) {
          uni.showToast({ title: '请选择点价截止日期', icon: 'none' })
          return false
        }
      }
      for (var j = 0; j < boolChecks.length; j++) {
        var bc = boolChecks[j]
        if (typeof d[bc.key] !== 'boolean') {
          uni.showToast({ title: '请选择' + bc.title, icon: 'none' })
          return false
        }
      }
      var pr = this.$refs.productRel
      if (pr && typeof pr.validate === 'function') {
        if (!pr.validate()) return false
      }
      return true
    },
    onBack() {
      uni.navigateBack({ delta: 1 })
    },
    joinStr(arr) {
      if (Array.isArray(arr)) return arr.filter(Boolean).join(',')
      if (typeof arr === 'string') return arr
      return ''
    },
    pickId(v) {
      if (v == null || v === '') return ''
      if (typeof v === 'string' || typeof v === 'number') return String(v)
      if (typeof v === 'object') {
        return String(v.id != null ? v.id : (v.value != null ? v.value : (v.code != null ? v.code : '')))
      }
      return String(v)
    },
    boolToStr(v) {
      return v === true ? 'true' : 'false'
    },
    buildPayload() {
      var self = this
      var d = this.detail || {}
      var lines = Array.isArray(this.lineList) ? this.lineList.slice() : []
      var workshopId = d.workshopId != null ? d.workshopId : ''
      var lineList = lines.map(function (row, i) {
        var r = row || {}
        var itemId = r.itemId != null ? r.itemId : (r.id != null ? String(r.id) : (r._key != null ? r._key : ('line-' + Date.now() + '-' + i)))
        if (!workshopId && r.workshopId != null) workshopId = r.workshopId
        return {
          productId: self.pickId(r.productId),
          materialType: r.materialType != null ? String(r.materialType) : '',
          quantity: r.quantity != null ? String(r.quantity) : '',
          actualPurchasePrice: r.actualPurchasePrice != null ? String(r.actualPurchasePrice) : '',
          includingShippingPrice: r.includingShippingPrice != null ? String(r.includingShippingPrice) : '',
          priceListPrices: r.priceListPrices != null ? String(r.priceListPrices) : '',
          coordinationRange: r.coordinationRange != null ? String(r.coordinationRange) : '',
          estimatedLoss: r.estimatedLoss != null ? String(r.estimatedLoss) : '',
          applicationAttrition: r.applicationAttrition != null ? String(r.applicationAttrition) : '',
          paintDamageRatio: r.paintDamageRatio != null ? String(r.paintDamageRatio) : '',
          workshopId: self.pickId(r.workshopId),
          itemId: itemId
        }
      })
      var body = {
        id: this.id || d.id || '',
        procurementPlanId: this.form.planId || d.id || '',
        changeReason: d.changeReason != null ? String(d.changeReason) : '',
        code: d.code != null ? String(d.code) : '',
        companyShortId: this.pickId(d.companyShortId || d.companyId),
        supplierId: this.pickId(d.supplierId),
        purchaseDepartment: this.pickId(d.purchaseDepartment),
        region: this.pickId(d.region),
        date: d.date != null ? String(d.date).slice(0, 10) : '',
        validityPeriod: d.validityPeriod != null ? String(d.validityPeriod) : '',
        quoterId: this.pickId(d.quoterId),
        workshopId: this.pickId(workshopId),
        quoterName: d.quoterName != null ? String(d.quoterName) : '',
        longTermOperation: this.boolToStr(d.longTermOperation),
        terminalCustomer: this.boolToStr(d.terminalCustomer),
        priced: this.boolToStr(d.priced),
        pricingDeadline: d.pricingDeadline != null ? String(d.pricingDeadline) : '',
        temporaryPrice: this.boolToStr(d.temporaryPrice),
        otherExpenseSettlement: this.boolToStr(d.otherExpenseSettlement),
        deliveryMode: d.deliveryMode != null ? String(d.deliveryMode) : '',
        commodityBuyout: this.boolToStr(d.commodityBuyout),
        qualityBuyout: this.boolToStr(d.qualityBuyout),
        quantityBuyout: this.boolToStr(d.quantityBuyout),
        doorDelivery: this.boolToStr(d.doorDelivery),
        shippingCost: d.shippingCost != null ? String(d.shippingCost) : '',
        loadingFee: d.loadingFee != null ? String(d.loadingFee) : '',
        invoiceProductName: d.invoiceProductName != null ? String(d.invoiceProductName) : '',
        deliveryDate: d.deliveryDate != null ? String(d.deliveryDate) : '',
        settlementMethod: d.settlementMethod != null ? String(d.settlementMethod) : '',
        settlementRatio: d.settlementRatio != null ? String(d.settlementRatio) : '',
        priceId: this.pickId(d.priceId),
        coordinationReason: d.coordinationReason != null ? String(d.coordinationReason) : '',
        invoiceTypeStatus: d.invoiceTypeStatus != null ? String(d.invoiceTypeStatus) : '',
        totalQuantity: d.totalQuantity != null ? String(d.totalQuantity) : '',
        remark: d.remark != null ? String(d.remark) : '',
        materialConditionEnabled: this.boolToStr(d.materialConditionEnabled),
        lines: lineList
      }
      this.materialConditionConfigs.forEach(function (mc) {
        body[mc.field] = self.joinStr(d[mc.field])
      })
      return body
    },
    async onSubmit() {
      if (!this.validateForm()) return
      var payload = this.buildPayload()
      try {
        await procurementPlanChangeUpdateApi(payload)
        uni.showToast({ title: '保存成功', icon: 'none' })
        try {
          uni.setStorageSync('SCHEDULE_PLAN_LIST_NEED_REFRESH', '1')
        } catch (e) {}
        var self = this
        setTimeout(function () {
          uni.navigateTo({ url: '/pages/schedule-plan/index' })
        }, 400)
      } catch (e) {
        uni.showToast({ title: (e && (e.msg || e.message)) ? (e.msg || e.message) : '保存失败', icon: 'none' })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.scroll {
  flex: 1;
  padding: 12rpx 0 392rpx !important;
}
.bottom-bar {
  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);
  display: flex;
  gap: 24rpx;
  .btn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 12rpx;
    font-size: 32rpx;
  }
  .btn-outline {
    background: #fff;
    color: $theme-primary;
    border: 2rpx solid $theme-primary;
  }
  .btn-primary {
    background: $theme-primary;
    color: #fff;
    border: 2rpx solid $theme-primary;
  }
}

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

.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;
}

.attach-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8rpx;
}
.attach-item {
  display: flex;
  align-items: center;
  gap: 16rpx;
  .attach-name { font-size: 26rpx; color: rgba(0,0,0,0.9); }
  .attach-view { font-size: 26rpx; color: $theme-primary; }
}

.material-condition-section,
.remark-section {
  margin-top: 20rpx;
  background: #fff;
}
.section-header {
  display: flex;
  align-items: center;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
}
.section-title {
  position: relative;
  font-size: 32rpx;
  color: rgba(0, 0, 0, 0.9);
  font-weight: 600;
  .required {
    color: red;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: -16rpx;
  }
}
.opCollapse {
  width: 32rpx;
  height: 28rpx;
  margin-right: 16rpx;
  margin-top: 8rpx;
}
.section-content {
  padding: 32rpx;
}
.form-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
}
.form-row:last-child { margin-bottom: 0; }
.form-label {
  font-size: 32rpx;
  color: rgba(0, 0, 0, 0.9);
}
.form-value {
  font-size: 32rpx;
  color: rgba(0, 0, 0, 0.9);
}
.toggle-link {
  color: $theme-primary;
}
.material-group {
  margin-top: 32rpx;
}
.material-label {
  display: block;
  font-size: 30rpx;
  color: rgba(0, 0, 0, 0.9);
  margin-bottom: 20rpx;
}
.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}
.tag-btn {
  padding: 12rpx 24rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #666;
  background: #fff;
}
.tag-btn.active {
  background: $theme-primary;
  border-color: $theme-primary;
  color: #fff;
}

::v-deep .uni-easyinput {
  width: 100%;
  &__content {
    background: #f8f8f8 !important;
    border-radius: 8rpx;
    &-input { font-size: 30rpx; }
  }
}
</style>