schedulePlanChangeViewer.vue 36.6 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
<template>
  <view class="detail-page">
    <scroll-view class="scroll" scroll-y>
      <view class="section">
        <text class="row company">{{ safeText(form.code) }}</text>
        <view v-if="canEdit" class="row">
          <text class="label required">公司名称</text>
          <view class="value select-value" @click="openCompanySheet">
            <text :class="form.companyShortName || form.companyName ? '' : 'placeholder'">{{ form.companyShortName || form.companyName || '请选择公司名称' }}</text>
            <text class="arrow">›</text>
          </view>
        </view>
        <view v-else class="row"><text class="label">公司简称</text><text class="value">{{ safeText(form.companyShortName || form.companyName) }}</text></view>
        <view class="row"><text class="label">供应商名称</text><text class="value">{{ safeText(form.supplierName) }}</text></view>
        <view class="row"><text class="label">采购处</text><text class="value">{{ safeText(form.purchaseDepartmentName || form.purchaseDepartment) }}</text></view>
        <view class="row"><text class="label">区域</text><text class="value">{{ safeText(form.regionName || form.region) }}</text></view>
        <view v-if="canEdit" class="row">
          <text class="label required">日期</text>
          <view class="value date-value">
            <uni-datetime-picker type="date" v-model="form.date" return-type="string" />
          </view>
        </view>
        <view v-else class="row"><text class="label">日期</text><text class="value">{{ formatDateOnly(form.date) }}</text></view>
        <view class="row"><text class="label">报价时效</text><text class="value">{{ safeText(form.validityPeriod) }}</text></view>
        <view class="row"><text class="label">报价人</text><text class="value">{{ safeText(form.quoterName) }}</text></view>
        <view class="row"><text class="label">是否长单操作</text><text class="value">{{ boolText(form.longTermOperation) }}</text></view>
        <view class="row"><text class="label">是否终端客户</text><text class="value">{{ boolText(form.terminalCustomer) }}</text></view>
        <view class="row"><text class="label">是否未点价</text><text class="value">{{ boolText(form.priced) }}</text></view>
        <view v-if="form.priced === true" class="row"><text class="label">点价截止日期</text><text class="value">{{ formatDateOnly(form.pricingDeadline) }}</text></view>
        <view v-if="form.priced === true" class="row"><text class="label">是否暂定价</text><text class="value">{{ boolText(form.temporaryPrice) }}</text></view>
        <view class="row"><text class="label">其他费用凭票到厂另行结算</text><text class="value">{{ boolText(form.otherExpenseSettlement) }}</text></view>
        <view class="row"><text class="label">交提货方式</text><text class="value">{{ getDeliveryMethodLabel() }}</text></view>
        <view class="row"><text class="label">是否通货买断</text><text class="value">{{ boolText(form.commodityBuyout) }}</text></view>
        <view class="row"><text class="label">是否质量买断</text><text class="value">{{ boolText(form.qualityBuyout) }}</text></view>
        <view class="row"><text class="label">是否数量买断</text><text class="value">{{ boolText(form.quantityBuyout) }}</text></view>
        <view class="row"><text class="label">是否送货上门</text><text class="value">{{ boolText(form.doorDelivery) }}</text></view>
        <view class="row">
          <text class="label">另付运费</text>
          <input v-if="canEdit" class="value line-input" v-model="form.shippingCost" type="digit" placeholder="请输入" @input="onShippingCostInput" @blur="onShippingCostBlur" />
          <text v-else class="value">{{ formatNumber(form.shippingCost) }}</text>
        </view>
        <view class="row"><text class="label">装车费</text><text class="value">{{ formatNumber(form.loadingFee) }}</text></view>
        <view class="row"><text class="label">开票品名</text><text class="value">{{ safeText(form.invoiceProductName) }}</text></view>
        <view class="row"><text class="label">交货日期</text><text class="value">{{ formatDateOnly(form.deliveryDate) }}</text></view>
        <view class="row"><text class="label">结算方式</text><text class="value">{{ safeText(form.settlementMethod) }}</text></view>
        <view class="row"><text class="label">结算比例(%)</text><text class="value">{{ formatNumber(form.settlementRatio) }}</text></view>
        <view class="row">
          <text class="label" :class="{ required: canEdit }">价格表编号</text>
          <view v-if="canEdit" class="value select-value" @click="openPriceTableSheet">
            <text :class="priceTableCodeLabel ? '' : 'placeholder'">{{ priceTableCodeLabel || '请选择价格表编号' }}</text>
            <text class="arrow">›</text>
          </view>
          <text v-else class="value">{{ priceTableDisplay }}</text>
        </view>
        <view class="row"><text class="label">协调事由</text><text class="value">{{ safeText(form.coordinationReason) }}</text></view>
        <view class="row"><text class="label">票类状况</text><text class="value">{{ safeText(form.invoiceTypeStatus) }}</text></view>
        <view class="row"><text class="label">数量合计</text><text class="value">{{ formatNumber(form.totalQuantity) }}</text></view>
        <view class="row" v-if="attachmentList.length">
          <text class="label">附件</text>
          <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>
        </view>
      </view>

      <view class="title-header">
        <image class="title-header_icon" src="/static/images/title.png" />
        <span>明细信息</span>
      </view>
      <view v-if="lineListWithName.length" class="section">
        <view v-for="(line, idx) in lineListWithName" :key="line.itemId || idx" class="line-block">
          <view class="line-title">明细{{ idx + 1 }}</view>
          <view class="row"><text class="label">品种</text><text class="value">{{ safeText(line.productName) }}</text></view>
          <view class="row"><text class="label">料型</text><text class="value">{{ safeText(line.materialType) }}</text></view>
          <view class="row"><text class="label">数量(吨)</text><text class="value">{{ formatNumber(line.quantity) }}</text></view>
          <view class="row"><text class="label">实际采购价</text><text class="value">{{ formatNumber(line.actualPurchasePrice) }}</text></view>
          <view class="row"><text class="label">含运到厂价</text><text class="value">{{ formatNumber(line.includingShippingPrice) }}</text></view>
          <view class="row">
            <text class="label">价格表价格</text>
            <input v-if="canEdit" class="value line-input" v-model="line.priceListPrices" type="digit" placeholder="请输入" @input="onLinePriceInput(idx, $event)" @blur="onLinePriceBlur(idx)" />
            <text v-else class="value">{{ formatNumber(line.priceListPrices) }}</text>
          </view>
          <view class="row"><text class="label">协调幅度</text><text class="value">{{ formatNumber(line.coordinationRange) }}</text></view>
          <view class="row"><text class="label">买断料预计损耗</text><text class="value">{{ formatNumber(line.estimatedLoss) }}</text></view>
          <view class="row"><text class="label">申请损耗(%)</text><text class="value">{{ formatNumber(line.applicationAttrition) }}</text></view>
          <view class="row">
            <text class="label" :class="{ required: canEditWorkshop }">选择分厂</text>
            <view v-if="canEditWorkshop" class="value select-value" @click="openWorkshopSheet(idx)">
              <text :class="line.workshopName ? '' : 'placeholder'">{{ line.workshopName || '请选择分厂' }}</text>
              <text class="arrow">›</text>
            </view>
            <text v-else class="value">{{ safeText(line.workshopName) }}</text>
          </view>
        </view>
      </view>
      <view v-else class="section empty-tip">暂无明细</view>

      <view class="title-header">
        <image class="title-header_icon" src="/static/images/title.png" />
        <span>料质状况</span>
      </view>
      <view class="section">
        <view class="row"><text class="label">是否启用料质状况</text><text class="value">{{ boolText(form.materialConditionEnabled) }}</text></view>
        <template v-if="form.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) }">{{ opt.name }}</view>
            </view>
          </view>
        </template>
      </view>

      <view class="title-header">
        <image class="title-header_icon" src="/static/images/title.png" />
        <span>备注</span>
      </view>
      <view class="section">
        <text class="remark-text">{{ safeText(form.remark) }}</text>
      </view>

      <view class="title-header">
        <image class="title-header_icon" src="/static/images/title.png" />
        <span>变更事由</span>
      </view>
      <view class="section">
        <text class="remark-text">{{ safeText(form.changeReason) }}</text>
      </view>
    </scroll-view>

    <RelateSelectSheet
      v-if="companySheetVisible"
      :visible.sync="companySheetVisible"
      title="选择公司"
      :fetch-fn="fetchCompanyList"
      :display-fields="companyDisplayFields"
      :page-size="20"
      :multiple="false"
      row-key="id"
      @confirm="onCompanyConfirm"
    />
    <RelateSelectSheet
      v-if="priceSheetVisible"
      :visible.sync="priceSheetVisible"
      title="选择价格表"
      :fetch-fn="fetchPriceTableList"
      :display-fields="priceTableDisplayFields"
      :page-size="20"
      :multiple="false"
      row-key="id"
      @confirm="onPriceTableConfirm"
    />
    <SingleSelectSheet
      :visible.sync="workshopSheet.visible"
      title="请选择分厂"
      :options="workshopSheet.options"
      v-model="workshopSheet.value"
      @confirm="onWorkshopConfirm"
    />
  </view>
</template>
<script>
import { procurementPlanChangeFindByIdApi } from '@/api/procure-manage/procurementPlan.js'
import { breedRelationshipQueryApi, workshopQueryApi, companyShortQueryApi, priceTableQueryApi, priceTableDetailApi } from '@/api/devManage.js'
import { getDicByCodes } from '@/utils/dic.js'
import { getInfo } from '@/api/login.js'
import RelateSelectSheet from '@/components/relate-select/index.vue'
import SingleSelectSheet from '@/components/single-select/index.vue'
export default {
  name: 'SchedulePlanChangeViewer',
  components: { RelateSelectSheet, SingleSelectSheet },
  props: { id: { type: [String, Number], default: '' } },
  data() {
    return {
      form: {},
      lineList: [],
      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' }
      ],
      dictData: {},
      productOptions: [],
      workshopOptions: [],
      deliveryOptions: [],
      isGyglkzg: false,
      isGyglkzlglg: false,
      companySheetVisible: false,
      priceSheetVisible: false,
      workshopSheet: { visible: false, title: '请选择分厂', options: [], value: '', idx: -1 },
      companyDisplayFields: [
        { label: '公司简称', field: 'companyShortName' },
        { label: '公司名称', field: 'companyName' },
        { label: '编码', field: 'code' }
      ],
      priceTableDisplayFields: [
        { label: '价格表编号', field: 'priceTableCode' },
        { label: '名称', field: 'priceTableName' },
        { label: '日期', field: 'effectiveDate' }
      ]
    }
  },
  computed: {
    isAuditPage() {
      try {
        var pages = getCurrentPages()
        var cur = pages[pages.length - 1]
        var route = cur && cur.route ? String(cur.route) : ''
        return route === 'pages/flow/audit'
      } catch (e) {
        return false
      }
    },
    canEdit() {
      return !!this.isGyglkzg && this.isAuditPage
    },
    canEditWorkshop() {
      return !!this.isGyglkzlglg && this.isAuditPage
    },
    workshopOptsComputed() {
      var list = Array.isArray(this.workshopOptions) ? this.workshopOptions : []
      return list.map(function (o) {
        return {
          label: o.label != null ? o.label : (o.name != null ? o.name : (o.workshopName || '')),
          value: o.value != null ? o.value : (o.id != null ? o.id : o.workshopId)
        }
      })
    },
    shippingCostNumber() {
      var v = this.form.shippingCost
      if (v == null || v === '') return 0
      var n = Number(v)
      return isNaN(n) ? 0 : n
    },
    priceTableCodeLabel() {
      var d = this.form || {}
      var code = d.priceTableCode != null ? d.priceTableCode : ''
      var name = d.priceTableName || ''
      if (name || code) {
        return (name ? name + (code ? ' (' + code + ')' : '') : String(code))
      }
      return ''
    },
    productMap() {
      var list = Array.isArray(this.productOptions) ? this.productOptions : []
      var m = {}
      list.forEach(function (o) {
        var key = String(o.productId || o.id || o.value || '')
        if (key) m[key] = o
      })
      return m
    },
    workshopMap() {
      var list = Array.isArray(this.workshopOptions) ? this.workshopOptions : []
      var m = {}
      list.forEach(function (o) {
        var key = String(o.workshopId || o.id || o.value || '')
        if (key) m[key] = o
      })
      return m
    },
    lineListWithName() {
      var self = this
      var list = Array.isArray(this.lineList) ? this.lineList : []
      return list.map(function (row) {
        if (!row.productName) {
          var pid = String(row.productId || '')
          var p = pid ? self.productMap[pid] : null
          if (p) row.productName = p.productName || p.name || p.label || ''
        }
        if (!row.workshopName) {
          var wid = String(row.workshopId || '')
          var w = wid ? self.workshopMap[wid] : null
          if (w) row.workshopName = w.workshopName || w.name || w.label || ''
        }
        return row
      })
    },
    priceTableDisplay() {
      var d = this.form || {}
      var code = d.priceTableCode != null ? String(d.priceTableCode).trim() : ''
      var name = d.priceTableName || ''
      if (name || code) {
        return (name ? name + (code ? ' (' + code + ')' : '') : String(code))
      }
      return '-'
    }
  },
  created() {
    this.loadDictData()
    this.loadRefData()
    this.getUserInfo()
  },
  watch: {
    id: {
      immediate: true,
      handler(val) {
        const v = (val !== undefined && val !== null) ? String(val) : ''
        if (v) this.loadDetail(v)
      }
    }
  },
  methods: {
    getUserInfo() {
      getInfo()
        .then((res) => {
          this.isGyglkzg = !!(res?.roleCodes?.includes('gyglkzg') && res?.roleCodes?.includes('001'));
          this.isGyglkzlglg = !!(res?.roleCodes?.includes('gyglkzlglg') && res?.roleCodes?.includes('001'));
        })
        .catch((err) => {
          console.error('获取用户信息失败:', err);
        });
    },
    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)
    },
    getInputValue(e) {
      if (e && e.detail && e.detail.value !== undefined) return e.detail.value
      return e
    },
    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.deliveryOptions = (d.DELIVERY_METHOD && d.DELIVERY_METHOD.data) || []
      } catch (e) {
        this.dictData = {}
        this.deliveryOptions = []
      }
    },
    async loadRefData() {
      var self = this
      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 : {}
        self.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 : []))
        self.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 : []))
      } catch (e) {
        self.productOptions = []
        self.workshopOptions = []
      }
    },
    pCall(fn, params) {
      try {
        return Promise.resolve(fn(params))
      } catch (e) {
        return Promise.reject(e)
      }
    },
    async loadDetail(id) {
      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] = []
          }
        })
        this.form = d
        var lines = d.lines || d.procurementPlanLineList || d.lineList || []
        this.lineList = Array.isArray(lines) ? lines.slice() : []
        // 初始化可编辑字段
        this.form.companyId = d.companyId || ''
        this.form.companyShortName = d.companyShortName || d.companyName || ''
        var date = d.date ? String(d.date).trim() : ''
        this.form.date = date.length >= 10 ? date.slice(0, 10) : date
        var sc = d.shippingCost
        this.form.shippingCost = (sc != null && sc !== '') ? this.toFixed(sc, 2) : ''
        this.buildAttachmentList()
        this.refreshLinesFromShipping()
        if (this.canEdit) {
          this.loadLatestPriceTableAndApply()
        } else {
          this.fetchPriceDetailAndApply(d.priceId)
        }
      } catch (e) {
        this.form = {}
        this.lineList = []
        this.attachmentList = []
      }
    },
    buildAttachmentList() {
      var d = this.form || {}
      var ids = d.attachmentFileIds
      var names = d.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
    },
    getDictOptions(dictCode) {
      var data = this.dictData[dictCode]
      return (data && data.data) ? data.data : []
    },
    isTagSelected(field, code) {
      var selected = this.form ? this.form[field] : undefined
      if (Array.isArray(selected)) return selected.indexOf(code) >= 0
      if (typeof selected === 'string' && selected) {
        return selected.split(',').indexOf(code) >= 0
      }
      return false
    },
    getDeliveryMethodLabel() {
      var opts = this.deliveryOptions || []
      var v = String(this.form.deliveryMode != null ? this.form.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 || '-'
      }
      return v
    },
    boolText(v) {
      if (typeof v === 'boolean') return v ? '是' : '否'
      if (v === 'true' || v === '1' || v === 1) return '是'
      if (v === 'false' || v === '0' || v === 0) return '否'
      return '-'
    },
    formatDateOnly(v) {
      var s = v == null ? '' : String(v).trim()
      if (!s) return '-'
      if (s.length >= 10) return s.slice(0, 10)
      return s
    },
    safeText(v) {
      var s = v == null ? '' : String(v)
      return s.trim() ? s : '-'
    },
    formatNumber(v) {
      if (v == null || v === '') return '-'
      var n = Number(v)
      if (isNaN(n)) return String(v)
      return n.toLocaleString('zh-CN', { maximumFractionDigits: 4 })
    },
    onPreviewAttachment(at) {
      if (!at || !at.id) {
        uni.showToast({ title: '无法查看', icon: 'none' })
        return
      }
      uni.showToast({ title: '查看附件 ' + at.name, icon: 'none' })
    },
    // ==================== 公司下拉 ====================
    fetchCompanyList(args) {
      var extra = (args && args.extra) ? args.extra : {}
      var keyword = extra.keyword || extra.name || ''
      var params = { pageIndex: args.pageIndex || 1, pageSize: args.pageSize || 20 }
      if (keyword) params.name = keyword
      return companyShortQueryApi(params).then(function (res) {
        var d = (res && res.data) ? res.data : {}
        var records = (d.datas && Array.isArray(d.datas)) ? d.datas : ((d.records && Array.isArray(d.records)) ? d.records : ((d.list && Array.isArray(d.list)) ? d.list : []))
        var total = d.totalCount || d.count || (records ? records.length : 0)
        var hasNext = !!d.hasNext
        return { records: records, totalCount: total, hasNext: hasNext }
      }).catch(function () {
        return { records: [], totalCount: 0, hasNext: false }
      })
    },
    openCompanySheet() {
      this.companySheetVisible = true
    },
    onCompanyConfirm(e) {
      var items = (e && e.items) ? e.items : []
      if (!items.length) return
      var row = items[0] || {}
      this.form.companyId = row.id || ''
      this.form.companyShortName = row.companyShortName || row.companyName || row.name || ''
    },
    // ==================== 价格表下拉 ====================
    fetchPriceTableList(args) {
      var extra = (args && args.extra) ? args.extra : {}
      var keyword = extra.keyword || extra.name || ''
      var params = { pageIndex: args.pageIndex || 1, pageSize: args.pageSize || 20 }
      if (keyword) params.name = keyword
      return priceTableQueryApi(params).then(function (res) {
        var d = (res && res.data) ? res.data : {}
        var records = (d.datas && Array.isArray(d.datas)) ? d.datas : ((d.records && Array.isArray(d.records)) ? d.records : ((d.list && Array.isArray(d.list)) ? d.list : []))
        var total = d.totalCount || d.count || (records ? records.length : 0)
        var hasNext = !!d.hasNext
        return { records: records, totalCount: total, hasNext: hasNext }
      }).catch(function () {
        return { records: [], totalCount: 0, hasNext: false }
      })
    },
    openPriceTableSheet() {
      this.priceSheetVisible = true
    },
    onPriceTableConfirm(e) {
      var items = (e && e.items) ? e.items : []
      if (!items.length) return
      this.selectPriceTableRow(items[0] || {})
    },
    selectPriceTableRow(row) {
      this.form.priceTableId = row.id || ''
      this.form.priceTableCode = row.priceTableCode || row.code || ''
      this.form.priceTableName = row.priceTableName || row.name || ''
      if (this.form.priceTableId) {
        this.fetchPriceDetailAndApply(this.form.priceTableId)
      }
    },
    async loadLatestPriceTableAndApply() {
      var self = this
      try {
        var res = await priceTableQueryApi({ pageIndex: 1, pageSize: 1, orderByColumn: 'createTime desc,id desc' })
        var d = (res && res.data) ? res.data : {}
        var list = (d.datas && Array.isArray(d.datas)) ? d.datas : ((d.records && Array.isArray(d.records)) ? d.records : ((d.list && Array.isArray(d.list)) ? d.list : []))
        if (!list || !list.length) return
        self.selectPriceTableRow(list[0])
      } catch (e) {
        return
      }
    },
    async fetchPriceDetailAndApply(priceId) {
      if (!priceId) return
      var self = this
      try {
        var res = await priceTableDetailApi({ id: priceId })
        var d = (res && res.data) ? res.data : {}
        if (d.code != null && this.form) {
          this.$set(this.form, 'priceTableCode', String(d.code))
        }
        if (d.priceTableName != null && this.form) {
          this.$set(this.form, 'priceTableName', d.priceTableName)
        }
        var priceLines = self.extractPriceLines(d)
        self.applyPriceLinesToLines(priceLines)
      } catch (e) {
        return
      }
    },
    extractPriceLines(priceDetail) {
      if (!priceDetail || typeof priceDetail !== 'object') return []
      var candidates = [
        priceDetail.procurementPriceLineList,
        priceDetail.priceLineList,
        priceDetail.priceList,
        priceDetail.lineList,
        priceDetail.datas,
        priceDetail.records,
        priceDetail.list
      ]
      for (var i = 0; i < candidates.length; i++) {
        if (Array.isArray(candidates[i]) && candidates[i].length) return candidates[i]
      }
      for (var k in priceDetail) {
        if (!Object.prototype.hasOwnProperty.call(priceDetail, k)) continue
        if (Array.isArray(priceDetail[k])) {
          var arr = priceDetail[k]
          if (arr.length && arr[0] && typeof arr[0] === 'object' && (arr[0].price != null || arr[0].productId != null || arr[0].breedId != null || arr[0].varietyId != null)) {
            return arr
          }
        }
      }
      return []
    },
    applyPriceLinesToLines(priceLines) {
      if (!Array.isArray(this.lineList)) return
      var priceMap = this.buildPriceMap(priceLines)
      var self = this
      this.lineList = this.lineList.map(function (row) {
        var pid = String(row.productId || row.breedId || row.varietyId || '')
        var price = null
        if (pid && priceMap[pid] != null) {
          price = priceMap[pid].price
        } else {
          var pname = (row.productName || '').trim()
          if (pname) {
            for (var k in priceMap) {
              if (!Object.prototype.hasOwnProperty.call(priceMap, k)) continue
              var meta = priceMap[k] && priceMap[k].meta ? priceMap[k].meta : null
              if (meta && ((meta.productName && meta.productName === pname) || (meta.breedName && meta.breedName === pname) || (meta.varietyName && meta.varietyName === pname))) {
                price = priceMap[k].price
                break
              }
            }
          }
        }
        if (price != null) {
          row.priceListPrices = self.toFixed(price, 2)
        } else {
          row.priceListPrices = ''
        }
        return row
      })
      this.refreshLinesFromShipping()
    },
    buildPriceMap(priceLines) {
      var m = {}
      if (!Array.isArray(priceLines)) return m
      for (var i = 0; i < priceLines.length; i++) {
        var line = priceLines[i] || {}
        if (line.price == null) continue
        var key = String(line.productId || line.breedId || line.varietyId || line.id || ('__idx_' + i))
        m[key] = { price: Number(line.price), meta: line }
      }
      return m
    },
    // ==================== 分厂选择 ====================
    openWorkshopSheet(idx) {
      var wOpts = this.workshopOptsComputed
      var curW = this.lineList[idx] && this.lineList[idx].workshopId
      var mW = wOpts.find(function (o) { return String(o.value) === String(curW) })
      this.workshopSheet = { visible: true, title: '请选择分厂', options: wOpts, value: mW ? mW.value : '', idx: idx }
    },
    onWorkshopConfirm(_ref) {
      var value = _ref.value
      var label = _ref.label
      var idx = this.workshopSheet.idx
      if (idx < 0 || !this.lineList[idx]) return
      var row = this.lineList[idx]
      this.$set(row, 'workshopId', value)
      this.$set(row, 'workshopName', label)
    },
    // ==================== 联动计算 ====================
    onShippingCostInput(e) {
      var s = this.getInputValue(e)
      s = s == null ? '' : String(s)
      s = s.replace(/[^\d.]/g, '')
      var parts = s.split('.')
      if (parts.length > 2) s = parts[0] + '.' + parts.slice(1).join('')
      this.form.shippingCost = s
      this.refreshLinesFromShipping()
    },
    onShippingCostBlur() {
      if (this.form.shippingCost == null || this.form.shippingCost === '') {
        this.refreshLinesFromShipping()
        return
      }
      var n = Number(this.form.shippingCost)
      if (isNaN(n) || n < 0) {
        this.form.shippingCost = ''
      } else {
        this.form.shippingCost = this.toFixed(n, 2)
      }
      this.refreshLinesFromShipping()
    },
    onLinePriceInput(idx, e) {
      var s = this.getInputValue(e)
      s = s == null ? '' : String(s)
      s = s.replace(/[^\d.]/g, '')
      var parts = s.split('.')
      if (parts.length > 2) s = parts[0] + '.' + parts.slice(1).join('')
      var row = this.lineList[idx]
      if (row) {
        this.$set(row, 'priceListPrices', s)
        this.recalcLine(idx)
      }
    },
    onLinePriceBlur(idx) {
      var row = this.lineList[idx]
      if (!row) return
      if (row.priceListPrices == null || row.priceListPrices === '') {
        this.recalcLine(idx)
        return
      }
      var n = Number(row.priceListPrices)
      if (isNaN(n) || n < 0) {
        this.$set(row, 'priceListPrices', '')
      } else {
        this.$set(row, 'priceListPrices', this.toFixed(n, 2))
      }
      this.recalcLine(idx)
    },
    refreshLinesFromShipping() {
      var self = this
      var sc = self.shippingCostNumber
      if (!Array.isArray(self.lineList)) return
      self.lineList = self.lineList.map(function (row) {
        var actual = self.toNumber(row.actualPurchasePrice)
        var including = actual + sc
        row.includingShippingPrice = self.toFixed(including, 2)
        var priceList = self.toNumber(row.priceListPrices)
        var loss = self.toNumber(row.estimatedLoss)
        var coord = including + loss - priceList
        row.coordinationRange = self.toFixed(coord, 2)
        return row
      })
    },
    recalcLine(idx) {
      var row = this.lineList[idx]
      if (!row) return
      var actual = this.toNumber(row.actualPurchasePrice)
      var including = actual + this.shippingCostNumber
      this.$set(row, 'includingShippingPrice', this.toFixed(including, 2))
      var priceList = this.toNumber(row.priceListPrices)
      var loss = this.toNumber(row.estimatedLoss)
      var coord = including + loss - priceList
      this.$set(row, 'coordinationRange', this.toFixed(coord, 2))
    },
    // ==================== 审核提交 ====================
    checkForm() {
      if (!this.canEdit) return true
      if (!this.form.companyId) {
        uni.showToast({ title: '请选择公司名称', icon: 'none' })
        return false
      }
      if (!this.form.date) {
        uni.showToast({ title: '请选择日期', icon: 'none' })
        return false
      }
      if (!this.form.priceTableId) {
        uni.showToast({ title: '请选择价格表编号', icon: 'none' })
        return false
      }
      if (this.canEditWorkshop) {
        var list = Array.isArray(this.lineList) ? this.lineList : []
        for (var i = 0; i < list.length; i++) {
          if (!list[i].workshopId) {
            uni.showToast({ title: '请选择明细' + (i + 1) + '的分厂', icon: 'none' })
            return false
          }
        }
      }
      return true
    },
    getFormValues() {
      var self = this
      var lines = Array.isArray(this.lineList) ? this.lineList : []
      return {
        companyId: this.form.companyId || '',
        companyShortName: this.form.companyShortName || this.form.companyName || '',
        date: this.form.date || '',
        shippingCost: this.form.shippingCost != null && this.form.shippingCost !== '' ? this.toNumber(this.form.shippingCost) : null,
        priceTableId: this.form.priceTableId || '',
        priceTableCode: this.form.priceTableCode || '',
        lineList: lines.map(function (r) {
          return {
            itemId: r.itemId || r.id || '',
            workshopId: r.workshopId || '',
            workshopName: r.workshopName || '',
            priceListPrices: self.toNumber(r.priceListPrices),
            includingShippingPrice: self.toNumber(r.includingShippingPrice),
            coordinationRange: self.toNumber(r.coordinationRange)
          }
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.detail-page {
  background: #f3f3f3;
}
.scroll {
  flex: 1;
  padding: 8rpx 0 48rpx;
}
.title-header {
  display: flex;
  align-items: center;
  padding: 24rpx 32rpx 12rpx;
  background-color: #ffffff;
  .title-header_icon {
    width: 36rpx;
    height: 36rpx;
    margin-right: 12rpx;
  }
  span {
    font-size: 34rpx;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.9);
  }
}
.section {
  padding: 32rpx;
  background: #fff;
  margin-bottom: 20rpx;
}
.row {
  display: flex;
  margin-bottom: 28rpx;
  align-items: center;
  &:last-child { margin-bottom: 0; }
  &.company {
    font-size: 36rpx;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.9);
    padding-top: 8rpx;
    line-height: 50rpx;
  }
  .label {
    max-width: 420rpx;
    margin-right: 20rpx;
    line-height: 32rpx;
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.6);
    &.required {
      position: relative;
      &::before {
        content: '*';
        color: #D54941;
        margin-right: 6rpx;
      }
    }
  }
  .value {
    flex: 1;
    line-height: 32rpx;
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.9);
    text-align: right;
    word-break: break-all;
    &.placeholder {
      color: rgba(0, 0, 0, 0.4);
    }
  }
}
.select-value {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  .arrow {
    margin-left: 8rpx;
    color: rgba(0, 0, 0, 0.4);
    font-size: 30rpx;
  }
}
.date-value {
  ::v-deep .uni-datetime-picker {
    display: inline-flex;
    justify-content: flex-end;
    .uni-datetime-picker__btn {
      padding: 0;
      border: none;
      background: transparent;
      font-size: 28rpx;
      color: rgba(0, 0, 0, 0.9);
    }
  }
}
.line-input {
  border-bottom: 1rpx solid #ddd;
  padding: 4rpx 0;
  text-align: right;
  height: 40rpx;
  min-height: 40rpx;
  font-size: 28rpx;
}
.line-block {
  padding-bottom: 24rpx;
  margin-bottom: 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  &:last-child {
    padding-bottom: 0;
    margin-bottom: 0;
    border-bottom: none;
  }
}
.line-title {
  font-size: 30rpx;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.9);
  margin-bottom: 20rpx;
}
.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-group {
  margin-top: 32rpx;
  &:first-child { margin-top: 0; }
}
.material-label {
  display: block;
  font-size: 28rpx;
  color: rgba(0, 0, 0, 0.6);
  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: #999;
  background: #f5f5f5;
}
.tag-btn.active {
  background: $theme-primary;
  border-color: $theme-primary;
  color: #fff;
}
.remark-text {
  font-size: 28rpx;
  color: rgba(0, 0, 0, 0.9);
  line-height: 1.6;
  white-space: pre-wrap;
}
.empty-tip {
  text-align: center;
  font-size: 28rpx;
  color: rgba(0, 0, 0, 0.4);
  padding: 24rpx 0;
}
</style>