CreateOrder.vue 93.4 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 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
<template>
  <view class="order">
    <view class="common-title">{{ orderCreateType == 'createWithPay' ? '新建工单' : '补录订单' }}</view>
    <view class="box">
      <scroll-view class="scroll-view" scroll-y="true">
        <view class="box-content">
          <GlCell :formList="formList" :formData="orderObj" :titleList="titleList" @radioChange="radioChange"
            @inputBlur="inputBlur" @handleCell="handleCell" @confirmCalendar="confirmCalendar">
            <template slot="customer">
              <view class="customer-title flex">
                客户信息
                <view class="customer-file flex" @click="
                  handleCell({
                    key: 'customer'
                  })
                  ">
                  <view class="sprite-icon icon-customer-list"></view>
                  客户档案
                </view>
              </view>
            </template>
            <template slot="frontGear">
              <Product v-if="orderObj.frontGear" @changeTotalPrice="changeTotalPrice" :list="orderObj.frontGear"
                :positionTypeList="positionTypeList" :baseConfigData="baseConfigData"
                :orderTypeCode="orderObj.orderTypeCode" :show-marketing-icon="true"></Product>
            </template>
            <template slot="frontWindow">
              <Product v-if="orderObj.frontWindow" @changeTotalPrice="changeTotalPrice" :list="orderObj.frontWindow"
                :positionTypeList="positionTypeList" :baseConfigData="baseConfigData"
                :orderTypeCode="orderObj.orderTypeCode" :show-marketing-icon="true"></Product>
            </template>
            <template slot="rearWindow">
              <Product v-if="orderObj.rearWindow" @changeTotalPrice="changeTotalPrice" :list="orderObj.rearWindow"
                :positionTypeList="positionTypeList" :baseConfigData="baseConfigData"
                :orderTypeCode="orderObj.orderTypeCode" :show-marketing-icon="true"></Product>
            </template>
            <template slot="rearGear">
              <Product v-if="orderObj.rearGear" @changeTotalPrice="changeTotalPrice" :list="orderObj.rearGear"
                :positionTypeList="positionTypeList" :baseConfigData="baseConfigData"
                :orderTypeCode="orderObj.orderTypeCode" :show-marketing-icon="true"></Product>
            </template>
            <template slot="sunRoof">
              <Product v-if="orderObj.sunRoof" @changeTotalPrice="changeTotalPrice" :list="orderObj.sunRoof"
                :positionTypeList="positionTypeList" :baseConfigData="baseConfigData"
                :orderTypeCode="orderObj.orderTypeCode" :show-marketing-icon="true"></Product>
            </template>
            <template slot="package">
              <Package v-if="orderObj.package" @changeTotalPrice="changeTotalPrice" :list="orderObj.package"
                :positionTypeList="positionTypeList" :orderTypeCode="orderObj.orderTypeCode"
                :show-marketing-icon="true"></Package>
            </template>
            <template slot="skuGoods">
              <SkuGoods v-if="orderObj.skuGoods" :list="orderObj.skuGoods" @changeTotalPrice="changeTotalPrice"
                :positionTypeList="positionTypeList" :baseConfigData="baseConfigData"
                :orderTypeCode="orderObj.orderTypeCode" :show-marketing-icon="true"></SkuGoods>
              <view class="total" v-if="totalPrice > 0">
                <view class="total-left">总价</view>
                <view class="total-right">¥{{ totalPrice }}</view>
              </view>
            </template>
            <template slot="otherPay">
              <view v-if="showPayTips" class="pay-tips">其他收款:当客户已向嘀加付款但无法使用流水补录时,新建工单应选择收款方为「嘀加收款」且支付方为「其他收款」。</view>
            </template>
          </GlCell>
        </view>
        <view v-if="orderObj.baseSceneCodeValue" @click="submit" class="btn">直接下单</view>
      </scroll-view>
    </view>
    <!-- 弹窗 -->
    <order-popup ref="orderPopup" :data="orderObj" :dataKey="valueKey" @onConfirm="onConfirm"
      :externalData="externalData" :popupType="popupType" :show-marketing-icon="true"
      :boutique-order-types-only="boutiqueOrderTypesOnly" />
  </view>
</template>

<script>
import utils from '@/utils/utils'
import OrderPopup from '@/components/OrderPopup/index.vue'
import GlCell from '../../../../components/Form/GlCell.vue'
import Product from './Product.vue'
import Package from './Package.vue'
import SkuGoods from './SkuGoods.vue'
import { FORM_LIST, popupTypeEnum, payTypeList, titleList } from '../contant'
import { interceptionMixin } from '@/mixin/index'
import { validateVin, formatVinInput } from '@/utils/vinVaildate'
import { collectBelowMinSellPriceItems } from '@/utils/minSellPrice'
import dayjs from 'dayjs'
import { getMarketingFlag, getActivityId, getSubmitMarketingFlag, getSubmitModifyFlag, getSubmitActivityId, snapshotOriginalPrice, snapshotOrderItemsOriginalPrice, snapshotActivityPriceFromCatalog } from '@/utils/marketingFlag'
export default {
  name: 'CreateOrder',
  mixins: [interceptionMixin],
  components: {
    GlCell,
    OrderPopup,
    Product,
    Package,
    SkuGoods
  },
  props: {
    transmissionOfData: {
      type: Object,
      default: () => null
    }
  },
  watch: {
    transmissionOfData: {
      handler(newVal) {
        if (newVal) {
          // 处理交易数据
          const handleTransactionData = newVal => {
            console.log('接收到的交易数据:', newVal)
            this.orderCreateType = newVal.type

            if (this.orderCreateType === 'supplementOrder') {
              // 补录订单处理
              const { outTradeNo, tradeNo } = newVal.selectedItems.reduce(
                (acc, item) => ({
                  outTradeNo: [...(acc.outTradeNo || []), item.outTradeNo],
                  tradeNo: [...(acc.tradeNo || []), item.tradeNo]
                }),
                {}
              )

              Object.assign(this.orderObj, {
                outTradeNo: outTradeNo.join(','),
                tradeNo: tradeNo.join(',')
              })

              // 补录订单也需要默认订单类型(用于页面“订单类型”字段展示)
              if (!this.orderObj.orderTypeCode) this.$set(this.orderObj, 'orderTypeCode', '1')
              if (!this.orderObj.djOrderType) this.$set(this.orderObj, 'djOrderType', '正常订单')
              const orderTypeCell = this.formList?.[2]?.find(item => item.value === 'djOrderType')
              if (orderTypeCell) orderTypeCell.current = this.orderObj.djOrderType
              return
            }
            // 编辑和修改订单进入这里
            const { paramsData } = newVal
            this.applyOrderEchoFromRest(paramsData)
            this.subOrderList = this.prepareSubOrderListFromOrder(paramsData)
            const customerId = paramsData.customer?.customerId
            if (customerId) {
              // 编辑/修改订单时,订单快照中的客户车型、车架号等字段可能缺失,需从客户建档详情补全
              this.fetchAndBackfillCustomerProfile(customerId, paramsData.customer)
              this.fetchGoodsOrderRemark(customerId)
            }
          }
          console.log(this.orderObj, 'orderObj')
          handleTransactionData(newVal)
        } else {
          this.baseConfigData = uni.$storage.get('mock_data') || {}
          this.orderCreateType = 'createWithPay'
          this.orderObj = {
            customer: {},
            customerSex: '1',
            experienceFlag: 'Y',
            payeeType: 1,
            salesType: '0',
            orderTypeCode: '1', // 默认正常订单
            djOrderType: '正常订单', // 默认正常订单
            frontGear: null, // 1 ,回显upgradeGoodsPosition == 1
            frontWindow: null, // 2
            rearWindow: null, // 3
            rearGear: null, // 4
            sunRoof: null, // 5, 6,7
            package: null,
            skuGoods: null, // upgradeGoodsPosition 为空,则是其他精品单商品
            customerTags: [], // 日报标签
            actualDeliveryDate: '', // 实际交付日期
          }
          this.initData()
        }
      },
      immediate: true
    },
    'orderObj.salesType': {
      handler(newVal) {
        this.customerTagsAndActualDeliveryDateHidden()
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    return {
      orderCreateType: 'createWithPay', // supplementOrder(补录订单) createWithPay(新增)
      titleList,
      formList: [],
      baseConfigData: {},
      requiredList: [], // 录单设置的必填项
      orderObj: {
        customer: {},
        customerSex: '1',
        experienceFlag: 'Y',
        payeeType: 1,
        salesType: '0',
        orderTypeCode: '1', // 默认正常订单
        djOrderType: '正常订单', // 默认正常订单(表单展示用)
        frontGear: null, // 1 ,回显upgradeGoodsPosition == 1
        frontWindow: null, // 2
        rearWindow: null, // 3
        rearGear: null, // 4
        sunRoof: null, // 5, 6,7
        package: null,
        skuGoods: null, // upgradeGoodsPosition 为空,则是其他精品单商品
        customerTags: [], // 日报标签
        actualDeliveryDate: '', // 实际交付日期
      }, // 弹窗传入的数据},
      popupType: 0,
      popupTypeEnum,
      externalData: [], //弹窗接口数据
      subShopMerchantList: [], // 二级流量方列表
      employeeList: [],
      djPayList: [], // 嘀加收款方对应支付方式
      merchantPayList: [], // 门店收款方对应支付方式
      configPayTypeList: [], // 园区店配置支持的支付方式
      payTypeList,
      goodsList: [],
      subOrderList: [],
      otherProduct: [],
      positionTypeList: [],
      valueKey: '',
      totalPrice: 0,
      validateState: true,
      // 产品槽位配置,用于循环渲染产品组件
      productSlots: {
        frontGear: true,
        frontWindow: true,
        rearGear: true,
        rearWindow: true,
        sunRoof: true
      }
    }
  },
  computed: {
    showPayTips() {
      if (this.orderObj.payeeType == 0 && this.orderObj.selectPayType == 7) return true
      else return false
    },
    boutiqueOrderTypesOnly() {
      return this.orderCreateType === 'createWithPay' && !this.orderObj.id
    },
    // 轻改场景 + 新建工单:隐藏场景名称表单项(仅展示层)
    hideSceneNameField() {
      const { sceneType } = this.userInfo || {}
      return sceneType == 1 && this.orderCreateType === 'createWithPay'
    },
    isHarmony() {
      const { channelType } = uni.$storage.get('userInfo')
      return channelType == 1
    },
  },
  mounted() {
    let formList = utils.deepClone(FORM_LIST),
      dailyTagList = [
        {
          value: '1',
          name: '已触客'
        },
        {
          value: '2',
          name: '已拉群'
        },
        {
          value: '3',
          name: '已交付引荐'
        },
        {
          value: '4',
          name: '首保维保客户 '
        },
        {
          value: '5',
          name: '事故车客户'
        }
      ]
    formList.forEach(item => {
      item.forEach(child => {
        if (child.value == 'customerTags') {
          child.radioList = this.isHarmony ? dailyTagList : dailyTagList.filter(item => ['1'].includes(item.value))
        }
      })
    })
    console.log('mounted', this.orderCreateType)
    console.log(formList, 'formList')
    this.baseConfigData = uni.$storage.get('mock_data') || {}
    this.formList = formList
    this.initData()
  },
  methods: {
    customerTagsAndActualDeliveryDateHidden() {
      let { salesType } = this.orderObj,
        { isHarmony } = this
        console.log(salesType)
      const selected = Boolean(this.orderObj && (this.orderObj.baseSceneCodeValue || this.orderObj.baseSceneCode))
      let formList = this.formList
      formList.map(item => {
        item.map(child => {
          if (child.value == 'customerTags') {
            let hidden = !selected || salesType == 2
            child.hidden = hidden
            if (hidden) this.$set(this.orderObj, 'customerTags', [])
          }
          if (child.value == 'actualDeliveryDate') {
            let hidden = (isHarmony ? ![3].includes(+salesType) : ![0, 3].includes(+salesType)) || !selected
            child.hidden = hidden
            if (hidden) this.$set(this.orderObj, 'actualDeliveryDate', '')
          }
        })
      })
      this.formList = formList
    },
    updateSceneGate() {
      const selected = Boolean(this.orderObj && (this.orderObj.baseSceneCodeValue || this.orderObj.baseSceneCode))
      const list = this.formList || []
      list.forEach(group => {
        ; (group || []).forEach(item => {
          if (!item) return
          if (item._originHidden === undefined) item._originHidden = Boolean(item.hidden)
          if (!selected) {
            item.hidden = item.value !== 'baseSceneCode'
          } else {
            item.hidden = item._originHidden
          }
          if (item.value === 'baseSceneCode' && this.hideSceneNameField) {
            item.hidden = true
          }
        })
      })
      this.formList = list
      this.$nextTick(() => {
        this.customerTagsAndActualDeliveryDateHidden()
      })
      return selected
    },
    async initRecentSceneEcho() {
      try {
        const userInfo = this.userInfo || uni.$storage.get('userInfo') || {}
        const phone = userInfo.phone
        const userSceneType = userInfo.sceneType
        if (!phone || userSceneType === undefined || userSceneType === null) return

        const recent = await uni.$api.equityApi.getUserRecentScene({
          phone,
          sceneType: userSceneType
        })
        recent.baseSceneCode = '100101'
        // HTTP 层已将 data.data 解包,recent 直接是 { baseSceneCode: '...' }
        const recentBaseSceneCode = recent?.baseSceneCode || recent?.uuid
        if (!recentBaseSceneCode) return

        // getSceneListWithOrder 有 Promise 缓存,不会重复发请求
        const rawList = await uni.$api.equityApi.getSceneListWithOrder({
          phone,
          sceneType: String(userSceneType)
        })
        const listData = Array.isArray(rawList) ? rawList : []
        const item = listData.find(i => String(i.baseSceneCode || i.uuid) === String(recentBaseSceneCode))
        if (!item) return

        this.$set(this.orderObj, 'baseSceneCode', item.name || item.staffName)
        this.$set(this.orderObj, 'baseSceneCodeValue', item.baseSceneCode || item.uuid)
        this.$set(this.orderObj, 'sceneType', item.sceneType)
        // 同步表单展示(GlCell 某些字段依赖 current)
        const sceneCell = this.formList?.[0]?.find(v => v && v.value === 'baseSceneCode')
        if (sceneCell) sceneCell.current = item.name || item.staffName || ''
      } catch (e) { }
    },
    // 计算单个商品的最终价格(与页面展示保持一致:先算单件优惠价,再乘数量,均向上取整两位)
    calculateFinalPrice(goods, sellPrice, number, orderTypeCode) {
      const price = parseFloat(sellPrice || 0)
      const qty = parseInt(number || 1)

      if (!price || !orderTypeCode) {
        const unit = utils.ceilDecimal(price)
        return utils.ceilDecimal(unit * qty)
      }

      const orderType = String(orderTypeCode || '')
      const strategyConfig = goods.strategyConfig || {}

      // '2' 打折策略
      if (orderType === '2') {
        if (strategyConfig.mode === 'ratio' && strategyConfig.discountRatio) {
          const ratio = parseFloat(strategyConfig.discountRatio)
          if (ratio >= 0.1 && ratio <= 10) {
            // 单件优惠价:单价 * 折扣比例,先向上取整两位
            const unit = utils.ceilDecimal(price * (ratio / 10))
            // 总价:单件优惠价 * 数量,再向上取整两位
            return utils.ceilDecimal(unit * qty)
          }
        } else if (strategyConfig.mode === 'amount' && strategyConfig.discountAmount) {
          const discountAmount = parseFloat(strategyConfig.discountAmount)
          if (discountAmount >= 0.01 && discountAmount <= price) {
            // 单件优惠价:单价 - 折扣金额,先向上取整两位
            const unit = utils.ceilDecimal(price - discountAmount)
            // 总价:单件优惠价 * 数量,再向上取整两位
            return utils.ceilDecimal(unit * qty)
          }
        }
        const unit = utils.ceilDecimal(price)
        return utils.ceilDecimal(unit * qty)
      }

      // '3' 买赠策略
      if (orderType === '3') {
        if (strategyConfig.isGift === '1') {
          return 0
        }
        const unit = utils.ceilDecimal(price)
        return utils.ceilDecimal(unit * qty)
      }

      // '5' 组合付款
      if (orderType === '5') {
        if (strategyConfig.mode === 'deduct' && strategyConfig.deductAmount) {
          const deductAmount = parseFloat(strategyConfig.deductAmount)
          if (deductAmount >= 0.01 && deductAmount <= price) {
            // 单件优惠价:单价 - 抵扣金额,先向上取整两位
            const unit = utils.ceilDecimal(price - deductAmount)
            // 总价:单件优惠价 * 数量,再向上取整两位
            return utils.ceilDecimal(unit * qty)
          }
        }
        const unit = utils.ceilDecimal(price)
        return utils.ceilDecimal(unit * qty)
      }

      const unit = utils.ceilDecimal(price)
      return utils.ceilDecimal(unit * qty)
    },
    // 计算主订单的总 finalPrice
    calculateTotalFinalPrice(subGoodsList) {
      if (!subGoodsList || subGoodsList.length === 0) return 0
      const total = subGoodsList.reduce((sum, item) => {
        return sum + parseFloat(item.finalPrice || 0)
      }, 0)
      return utils.ceilDecimal(total)
    },
    // 根据 discountType、discountValue 等字段构建 strategyConfig(用于回显)
    buildStrategyConfigFromDiscountFields(item, orderTypeCode) {
      const strategyConfig = {}
      const orderType = String(orderTypeCode || '')
      // 确保 discountType 是数字类型进行比较
      const discountType = item.discountType !== undefined && item.discountType !== null ? Number(item.discountType) : null

      // '2' 打折策略
      if (orderType === '2') {
        if (discountType === 1) {
          // 比例折扣
          strategyConfig.mode = 'ratio'
          // 确保 discountValue 存在且有效
          const discountValue = item.discountValue !== undefined && item.discountValue !== null && item.discountValue !== '' ? parseFloat(item.discountValue) : null
          if (discountValue !== null && !isNaN(discountValue)) {
            strategyConfig.discountRatio = discountValue
          } else {
            // 如果 discountValue 无效,但 discountType 是 1,仍然设置为 ratio 模式,但 discountRatio 为空
            strategyConfig.discountRatio = ''
          }
        } else if (discountType === 2) {
          // 折扣金额
          strategyConfig.mode = 'amount'
          // 确保 discountValue 存在且有效
          const discountValue = item.discountValue !== undefined && item.discountValue !== null && item.discountValue !== '' ? parseFloat(item.discountValue) : null
          if (discountValue !== null && !isNaN(discountValue)) {
            strategyConfig.discountAmount = discountValue
          } else {
            // 如果 discountValue 无效,但 discountType 是 2,仍然设置为 amount 模式,但 discountAmount 为空
            strategyConfig.discountAmount = ''
          }
        } else {
          // 无折扣(discountType === 3 或其他)
          strategyConfig.mode = 'none'
          strategyConfig.discountRatio = ''
          strategyConfig.discountAmount = ''
        }
      }
      // '3' 买赠策略
      else if (orderType === '3') {
        if (discountType === 4) {
          // 赠品
          strategyConfig.isGift = '1'
        } else {
          // 非赠品(discountType === 5 或其他)
          strategyConfig.isGift = '0'
        }
      }
      // '5' 组合付款
      else if (orderType === '5') {
        if (discountType === 2) {
          // 抵扣金额
          strategyConfig.mode = 'deduct'
          // 确保 discountValue 存在且有效
          const discountValue = item.discountValue !== undefined && item.discountValue !== null && item.discountValue !== '' ? parseFloat(item.discountValue) : null
          if (discountValue !== null && !isNaN(discountValue)) {
            strategyConfig.deductAmount = discountValue
          } else {
            strategyConfig.deductAmount = ''
          }
        } else {
          // 无抵扣(discountType === 3 或其他)
          strategyConfig.mode = 'none'
          strategyConfig.deductAmount = ''
        }
      }

      return strategyConfig
    },
    // 计算优惠相关字段(discountType, discountValue, discountAmount)
    calculateDiscountFields(goods, sellPrice, number, orderTypeCode) {
      const result = {
        discountType: null,
        discountValue: null,
        discountAmount: null
      }

      if (!orderTypeCode) {
        return result
      }

      const price = parseFloat(sellPrice || 0)
      const qty = parseInt(number || 1)
      const totalPrice = price * qty
      const orderType = String(orderTypeCode || '')
      const strategyConfig = goods.strategyConfig || {}

      // '2' 打折策略
      if (orderType === '2') {
        if (strategyConfig.mode === 'ratio' && strategyConfig.discountRatio) {
          // 比例折扣
          result.discountType = 1
          result.discountValue = parseFloat(strategyConfig.discountRatio)
          // 优惠金额 = 总价 - 折扣后总价(保持和 calculateFinalPrice 完全一致的算法)
          const finalPrice = this.calculateFinalPrice(goods, price, qty, orderTypeCode)
          result.discountAmount = Math.round((totalPrice - finalPrice) * 100) / 100
        } else if (strategyConfig.mode === 'amount' && strategyConfig.discountAmount) {
          // 折扣金额(单价折扣)
          result.discountType = 2
          result.discountValue = parseFloat(strategyConfig.discountAmount)
          // 优惠金额 = 单价折扣 * 数量
          result.discountAmount = Math.round(result.discountValue * qty * 100) / 100
        } else {
          // 无折扣
          result.discountType = 3
          result.discountAmount = 0
        }
      }
      // '3' 买赠策略
      else if (orderType === '3') {
        if (strategyConfig.isGift === '1') {
          // 赠品
          result.discountType = 4
          result.discountAmount = totalPrice
        } else {
          // 非赠品
          result.discountType = 5
          result.discountAmount = 0
        }
      }
      // '5' 组合付款
      else if (orderType === '5') {
        if (strategyConfig.mode === 'deduct' && strategyConfig.deductAmount) {
          // 抵扣金额(单价抵扣)
          result.discountType = 2
          result.discountValue = parseFloat(strategyConfig.deductAmount)
          // 优惠金额 = 单价抵扣 * 数量
          result.discountAmount = Math.round(result.discountValue * qty * 100) / 100
        } else {
          // 无抵扣
          result.discountType = 3
          result.discountAmount = 0
        }
      }
      // '1' 正常订单 或 '4' 冲量活动
      // '6' 内部结算:与正常订单同逻辑
      else {
        result.discountType = 3
        result.discountAmount = 0
      }

      return result
    },
    async initData() {
      console.log('initData', this.orderCreateType, this.orderObj.id)
      // 埋点
      if (this.orderCreateType == 'createWithPay' && !this.orderObj.id) {
        uni.$track.add({ eventCode: 'app_create_order' })
      } else if (this.orderCreateType == 'supplementOrder') {
        uni.$track.add({ eventCode: 'app_supplement_order' })
      }
      const { userInfo } = this
      if (!this.orderObj.id) {
        // 在原有的 orderObj 对象上新增这些属性
        Object.assign(this.orderObj, {
          sellerMerchantName: userInfo.merchantName,
          sellerName: userInfo.name,
          sellerMerchantId: userInfo.merchantId,
          sellerUserId: userInfo.uuid,
          merchantId: userInfo.shopMerchantId,
          merchantName: userInfo.shopMerchantName
        })
      }

      this.getShopMerchantPointConfig(this.orderObj.merchantId)

      this.getSetting()
      // 补录订单默认为嘀加收款,不需要获取园区店支付方式
      if (this.orderCreateType == 'supplementOrder') {
        this.orderObj.payeeType = 0
        const cell = this.formList[2].find(item => item.value == 'payeeType')
        if (cell) {
          cell.current = 0
          cell.radioList[1].disabled = true // 禁用4s店收款
        }
        this.djPayList = [
          {
            value: '5',
            name: '嘀加收款'
          }
        ]
        this.changePayee()
      } else {
        // 防止从补录进来4s店收款为禁用
        const cell = this.formList[2]?.find(item => item.value == 'payeeType')
        if (cell) {
          // 编辑订单时,使用已有的payeeType值,新建订单时使用默认值1
          if (!this.orderObj.id) {
            cell.current = 1
          } else {
            cell.current = this.orderObj.payeeType
          }
          cell.radioList[1].disabled = false
        }
        // 兼容:如果方法不存在则不调用,避免运行时报错
        if (typeof this.getConfig === 'function') {
          this.getConfig()
        }
      }
      // 设置订单类型表单显示(新建订单时)
      if (!this.orderObj.id && this.orderObj.djOrderType) {
        const orderTypeCell = this.formList[2]?.find(item => item.value === 'djOrderType')
        if (orderTypeCell) {
          orderTypeCell.current = this.orderObj.djOrderType
        }
      }
      // 新增页:先回显最近场景;未选场景时不展示/不请求下方表单与接口
      // 补录订单也需要回显最近场景(否则首屏场景名称为空,无法继续)
      if (!this.orderObj.id && (this.orderCreateType === 'createWithPay' || this.orderCreateType === 'supplementOrder')) {
        const hasScene = Boolean(this.orderObj && (this.orderObj.baseSceneCodeValue || this.orderObj.baseSceneCode))
        if (!hasScene) await this.initRecentSceneEcho()
      }
      const hasScene = this.updateSceneGate()
      if (!hasScene) return

      // this.getEmployeeList()
      this.getSelectOrderGoodsList()
      this.getPositionList()
      if (this.orderCreateType == 'createWithPay' && !this.orderObj.id) this.getLastUserOrderInfo() // 补录订单和有id的情况,不需要设置默认值
    },
    // 选择行事件
    async handleCell(val) {
      // 获取当前选中的popupType
      let foundKey = Object.keys(this.popupTypeEnum).find(key => this.popupTypeEnum[key].key === val.value)
      if (!foundKey && val.key) {
        foundKey = Object.keys(this.popupTypeEnum).find(key => this.popupTypeEnum[key].key === val.key)
      }
      if (!foundKey) {
        console.error(`Popup type not found for value: ${val.value}`)
        return
      }
      this.popupType = foundKey * 1
      // 获取对应的list字段
      const popupConfig = this.popupTypeEnum[this.popupType]
      if (!popupConfig) {
        console.error(`Popup config not found for popupType: ${this.popupType}`)
        return
      }
      if (popupConfig.list) {
        this.externalData = this[popupConfig.list] || []
      } else {
        this.externalData = []
      }
      // 定义产品相关字段数组
      const productFields = ['frontGear', 'frontWindow', 'rearGear', 'rearWindow', 'sunRoof', 'package', 'skuGoods']
      if (productFields.includes(val.value)) {
        this.valueKey = val.value
        if (!this.goodsList?.length && (this.orderObj.baseSceneCodeValue || this.orderObj.baseSceneCode)) {
          await this.getSelectOrderGoodsList()
        }
        if (this.$refs.orderPopup?.clearCacheByTypes) {
          this.$refs.orderPopup.clearCacheByTypes([this.popupType])
        }
        this.externalData = utils.deepClone(this.goodsList)
      }
      // 确保 orderPopup 引用存在后再调用 open 方法
      if (this.$refs.orderPopup && this.$refs.orderPopup.open) {
        this.$refs.orderPopup.open()
      } else {
        console.error('OrderPopup ref is not available')
      }
    },
    // 单选框change事件
    radioChange(e, val) {
      if (val.multiple) {
        let key = val.value,
          value = this.orderObj[key] || []
        if (value.includes(e)) {
          value = value.filter(item => item !== e)
        } else {
          value.push(e)
        }
        this.$set(this.orderObj, key, value)
      } else {
        this.$set(this.orderObj, val.value, e.detail.value)
        if (val.value == 'payeeType') {
          this.changePayee()
        }
      }
    },
    // 选择日期事件
    confirmCalendar(e, key) {
      let value = e.fulldate
      this.$set(this.orderObj, key, value)
    },
    // 弹窗确认回调
    onConfirm(val, flag) {
      this.externalData = []
      const chooseContent = utils.deepClone(val.chooseContent)
      // 确保popupType是数字类型
      const popupTypeNum = Number(this.popupType)
      // 根据popupTypeEnum优化处理
      const _typeValue = this.popupTypeEnum[popupTypeNum]

      if (val.popupType == 19) {
        console.log('客户档案选中数据:', chooseContent)
        return this.setCustomerInfo(chooseContent)
      }

      // 安全检查:如果_typeValue不存在,直接返回并关闭弹窗
      if (!_typeValue || !_typeValue.key) {
        console.error(`Invalid popupType: ${popupTypeNum}`)
        // 确保弹窗能够关闭
        if (this.$refs.orderPopup && this.$refs.orderPopup.close) {
          this.$refs.orderPopup.close()
        }
        return
      }
      // 定义产品相关字段数组
      const productFields = ['frontGear', 'frontWindow', 'rearGear', 'rearWindow', 'sunRoof', 'package', 'skuGoods']
      if (_typeValue.key == 'carBrand') {
        // 车型
        this.$set(this.orderObj, _typeValue.key, `${chooseContent.carBrand}-${chooseContent.carChildsBrandName}-${chooseContent.carSeriesName}`)
        this.orderObj.customer = {
          ...(this.orderObj.customer || {}),
          ...chooseContent
        }
      } else if (_typeValue.key == 'couponInfo') {
        // 礼券
        const { couponName, merchantCouponId, customerCouponCode } = chooseContent
        Object.assign(this.orderObj, {
          couponName: couponName,
          merchantCouponId: merchantCouponId,
          customerCouponCode: customerCouponCode
        })
        this.$set(this.orderObj, 'couponInfo', couponName + customerCouponCode)
      } else if (_typeValue.key == 'djOrderType') {
        // 订单类型
        this.$set(this.orderObj, 'djOrderType', chooseContent.name)
        this.$set(this.orderObj, 'orderTypeCode', chooseContent.value)
        // 订单类型切换时,清除已选商品
        const productFields = ['frontGear', 'frontWindow', 'rearGear', 'rearWindow', 'sunRoof', 'package', 'skuGoods']
        productFields.forEach(field => {
          this.$set(this.orderObj, field, null)
        })
        this.changeTotalPrice()
      } else if (productFields.includes(_typeValue.key)) {
        if (_typeValue.key == 'skuGoods') {
          if (!this.orderObj[_typeValue.key]) {
            // 其他精品第一次赋值
            this.$set(this.orderObj, _typeValue.key, chooseContent)
          } else {
            // 过滤出已选的goodFlag为2的对象
            const selectedGoods = this.orderObj[_typeValue.key].filter(item => item.goodsFlag === 2)
            const singleGoods = flag ? this.orderObj[_typeValue.key].filter(item => item.goodsFlag === 1) : chooseContent.filter(item => item.goodsFlag === 1)
            const moreGoods = chooseContent
              .filter(item => item.goodsFlag === 2)
              .filter(item => {
                return !selectedGoods.some(selectedItem => selectedItem.multipleSpecificationsGoods.goods.goodsId === item.multipleSpecificationsGoods.goods.goodsId)
              })
            // 合并已选的goodFlag为2的对象
            this.orderObj[_typeValue.key] = [...singleGoods, ...moreGoods, ...selectedGoods]
          }
        } else {
          this.$set(this.orderObj, _typeValue.key, chooseContent)
        }
        snapshotOrderItemsOriginalPrice(this.orderObj[_typeValue.key])
        this.enrichOrderItemsMarketingFields(this.orderObj[_typeValue.key])
        // 商品类,需计算总价
        setTimeout(() => {
          this.changeTotalPrice()
        }, 0)
      } else if (_typeValue.key === 'baseSceneCode') {
        // 场景名称:页面显示名称;提交时使用 code
        this.$set(this.orderObj, 'baseSceneCode', chooseContent.name || chooseContent.staffName)
        this.$set(this.orderObj, 'baseSceneCodeValue', chooseContent.baseSceneCode || chooseContent.uuid)
        this.$set(this.orderObj, 'sceneType', chooseContent.sceneType)
        // 选择后保存最近选中场景(sceneType 用登录场景)
        const userInfo = this.userInfo || uni.$storage.get('userInfo') || {}
        if (userInfo.phone) {
          uni.$api.equityApi.saveUserRecentScene({
            phone: userInfo.phone,
            sceneType: userInfo.sceneType,
            baseSceneCode: chooseContent.baseSceneCode || chooseContent.uuid
          })
        }
        // 场景名称切换时,清除已选商品(与订单类型切换一致)
        productFields.forEach(field => {
          this.$set(this.orderObj, field, null)
        })
        this.goodsList = []
        this.otherProduct = []
        this.changeTotalPrice()
        // 选中场景后,放开下方表单并触发依赖接口
        this.$refs.orderPopup && this.$refs.orderPopup.clearCacheByTypes([0, 1, 3, 6, 7, 8, 9, 10, 11, 12])
        this.updateSceneGate()
        this.getSelectOrderGoodsList()
        this.getPositionList()
      } else if (_typeValue.key) {
        this.orderObj[_typeValue.targetIdKey] = chooseContent[_typeValue.sourceIdKey]
        this.$set(this.orderObj, _typeValue.targetNameKey, chooseContent[_typeValue.sourceNameKey])
      }
    },
    // 输入框失去焦点事件
    inputBlur(e, val) {
      console.log(e, val)
      this.orderObj.customer[val.value] = this.orderObj[val.value]

      // VIN车架号动态校验:车架号字段,动态转换为大写
      let standNoVal = this.orderObj.standNo
      if (val.value === 'standNo' && standNoVal) {
        this.orderObj.standNo = formatVinInput(standNoVal)
        validateVin(this.orderObj.standNo)
          .then(result => {
            console.log('validateVin', result)
            let { valid } = result.data
            this.validateState = valid
            // 校验成功,所有提示已在公共方法中处理
            console.log('车架号校验成功:', result)
          })
          .catch(err => {
            console.log('validateVinErr', result)
          })
      }
    },
    // 校验必填等规则
    checkRequired() {
      const phoneRex = /^[1]([3-9])[0-9]{9}$/
      // 把formList中所有required为true的对象放到一个数组中
      const requiredArr = []
      const onlyLabelItem = []

      this.formList.forEach(group => {
        group.forEach(item => {
          if (item.required === true && item.hidden !== true) {
            if (item.onlyLabel === true) {
              onlyLabelItem.push(item)
            } else {
              requiredArr.push(item)
            }
          }
        })
      })

      // 遍历requiredArr,检查orderObj中是否有对应的值
      for (let i = 0; i < requiredArr.length; i++) {
        const item = requiredArr[i]
        // 兼容嵌套customer对象的情况
        let value
        if (item.value === 'customerName' || item.value === 'customerPhone' || item.value === 'standNo' || item.value === 'plateNumber') {
          value = this.orderObj.customer ? this.orderObj.customer[item.value] : undefined
        } else {
          value = this.orderObj[item.value]
        }
        // 0、false、'0'等视为有效,null/undefined/空字符串视为无效
        if (value === undefined || value === null || value === '') {
          uni.showToast({
            title: `${item.label}不能为空`,
            icon: 'none'
          })
          return false
        }
        // 如果是customerPhone,添加phoneRex校验
        if (item.value === 'customerPhone' && !phoneRex.test(value)) {
          uni.showToast({
            title: `请输入正确的${item.label}`,
            icon: 'none'
          })
          return false
        }
      }

      // if (this.orderObj.standNo) {
      //   if (!utils.validateVIN(this.orderObj.standNo)) throw '车架号校验不匹配,请核对后重新输入'
      // }

      // 处理onlyLabel为true的特殊校验
      if (onlyLabelItem.length > 0) {
        // 检查frontGear、frontWindow、rearGear、rearWindow、sunRoof和couponInfo字段中是否至少有一个不为空
        const labelFields = ['frontGear', 'frontWindow', 'rearGear', 'rearWindow', 'sunRoof', 'package', 'skuGoods']
        const hasValue = labelFields.some(field => {
          console.log(field, this.orderObj[field])
          const value = this.orderObj[field]
          return value !== undefined && value !== null && (Array.isArray(value) ? value.length > 0 : value !== '')
        })
        console.log(hasValue, hasValue)
        if (!hasValue) {
          uni.showToast({
            title: '商品不能为空',
            icon: 'none'
          })
          return false
        }
      }

      return true
    },
    // 验证订单策略和总价
    checkOrderStrategyAndTotal() {
      const orderTypeCode = String(this.orderObj.orderTypeCode || '')
      const labelFields = ['frontGear', 'frontWindow', 'rearGear', 'rearWindow', 'sunRoof', 'package', 'skuGoods']
      let allGoods = []

      // 收集所有商品
      labelFields.forEach(field => {
        const goodsList = this.orderObj[field]
        if (Array.isArray(goodsList) && goodsList.length > 0) {
          allGoods = allGoods.concat(goodsList)
        }
      })

      // 检查订单总价
      const total = parseFloat(this.totalPrice || 0)
      if (total < 0.01) {
        uni.showToast({
          title: '商品总价不可小于0.01,请修改商品价格后提交',
          icon: 'none'
        })
        return false
      }

      // 如果是打折策略(2)、买赠策略(3)、组合付款(5),需要验证策略配置
      if (orderTypeCode === '2') {
        // 打折策略:至少存在一项SKU为"比例折扣"或"折扣金额"
        let hasDiscount = false
        allGoods.forEach(item => {
          let goods = null
          if (item.goods) {
            goods = item.goods
          } else if (item.packageGoods && item.packageGoods.goodsList) {
            // 套餐商品,检查套餐内的商品
            item.packageGoods.goodsList.forEach(g => {
              const strategyConfig = g.strategyConfig || {}
              if (strategyConfig.mode === 'ratio' && strategyConfig.discountRatio) {
                hasDiscount = true
              } else if (strategyConfig.mode === 'amount' && strategyConfig.discountAmount) {
                hasDiscount = true
              }
            })
          } else if (item.multipleSpecificationsGoods && item.multipleSpecificationsGoods.goods) {
            goods = item.multipleSpecificationsGoods.goods
          }

          if (goods) {
            const strategyConfig = goods.strategyConfig || {}
            if (strategyConfig.mode === 'ratio' && strategyConfig.discountRatio) {
              hasDiscount = true
            } else if (strategyConfig.mode === 'amount' && strategyConfig.discountAmount) {
              hasDiscount = true
            }
          }
        })

        if (!hasDiscount) {
          uni.showToast({
            title: '至少存在一项SKU为"比例折扣"或"折扣金额"',
            icon: 'none'
          })
          return false
        }
      } else if (orderTypeCode === '3') {
        // 买赠策略:至少存在一项SKU为"赠品"
        let hasGift = false
        allGoods.forEach(item => {
          let goods = null
          if (item.goods) {
            goods = item.goods
          } else if (item.packageGoods && item.packageGoods.goodsList) {
            // 套餐商品,检查套餐内的商品
            item.packageGoods.goodsList.forEach(g => {
              const strategyConfig = g.strategyConfig || {}
              if (strategyConfig.isGift === '1') {
                hasGift = true
              }
            })
          } else if (item.multipleSpecificationsGoods && item.multipleSpecificationsGoods.goods) {
            goods = item.multipleSpecificationsGoods.goods
          }

          if (goods) {
            const strategyConfig = goods.strategyConfig || {}
            if (strategyConfig.isGift === '1') {
              hasGift = true
            }
          }
        })

        if (!hasGift) {
          uni.showToast({
            title: '至少存在一项SKU为"赠品"',
            icon: 'none'
          })
          return false
        }
      } else if (orderTypeCode === '5') {
        // 组合付款:至少存在一项SKU为"抵扣金额"
        let hasDeduct = false
        allGoods.forEach(item => {
          let goods = null
          if (item.goods) {
            goods = item.goods
          } else if (item.packageGoods && item.packageGoods.goodsList) {
            // 套餐商品,检查套餐内的商品
            item.packageGoods.goodsList.forEach(g => {
              const strategyConfig = g.strategyConfig || {}
              if (strategyConfig.mode === 'deduct' && strategyConfig.deductAmount) {
                hasDeduct = true
              }
            })
          } else if (item.multipleSpecificationsGoods && item.multipleSpecificationsGoods.goods) {
            goods = item.multipleSpecificationsGoods.goods
          }

          if (goods) {
            const strategyConfig = goods.strategyConfig || {}
            if (strategyConfig.mode === 'deduct' && strategyConfig.deductAmount) {
              hasDeduct = true
            }
          }
        })

        if (!hasDeduct) {
          uni.showToast({
            title: '至少存在一项SKU为"抵扣金额"',
            icon: 'none'
          })
          return false
        }
      }

      return true
    },
    // 提交

    async submit() {
      // 必填校验
      if (!this.checkRequired()) {
        return
      }

      // VIN车架号-动态校验
      const carVin = this.orderObj.standNo
      console.log('validateState', this.validateState)
      if (carVin) {
        // 前置判断
        if (carVin.length !== 17) {
          uni.showToast({ title: '请输入 17 位有效字符(支持大写 A-H/J-N/P-Z、0-9)', icon: 'none' })
          return false
        }
        // 根据接口校验结果判断
        if (carVin.length === 17 && !this.validateState) {
          uni.showToast({ title: '车架号校验不匹配,请核对后重新输入', icon: 'none' })
          return false
        }
      }

      // 验证订单策略和总价
      if (!this.checkOrderStrategyAndTotal()) {
        return
      }

      // 日报校验
      const hasInterception = await this.checkDailyReport()
      if (hasInterception) {
        return
      }

      // 低价提示
      const belowMinSellItems = collectBelowMinSellPriceItems(this.orderObj)
      if (belowMinSellItems.length > 0) {
        const names = belowMinSellItems.map(item => item.name).join('、')
        uni.showModal({
          title: '温馨提示',
          content: `以下商品售价低于最低售价:${names},请修改后重新提交`,
          showCancel: false,
          confirmText: '知道了'
        })
        return
      }
      this.doSubmit()
    },
    async doSubmit() {
      const { orderCreateType } = this
      const obj = utils.deepClone(this.orderObj)
      // 场景名称:界面展示用 name;提交入参需要 code
      if (obj.baseSceneCodeValue) obj.baseSceneCode = obj.baseSceneCodeValue
      delete obj.baseSceneCodeValue
      const otherCustomer = ['standNo', 'plateNumber', 'customerSex', 'experienceFlag', 'salesType', 'actualDeliveryDate', 'customerTags']
      obj.customer = {
        ...obj.customer,
        ...otherCustomer.reduce((acc, key) => {
          if (obj[key] !== undefined && obj[key] !== '' && obj[key] !== null) {
            if (key == 'customerTags') {
              obj[key] = obj[key].join(',')
            }
            if (key == 'actualDeliveryDate') {
              obj[key] += ' 00:00:00'
            }
            acc[key] = obj[key]
            delete obj[key]
          }
          return acc
        }, {})
      }
      // 将 frontGear、frontWindow、rearGear、rearWindow、sunRoof 字段合并到 goodsList 中
      const labelFields = ['frontGear', 'frontWindow', 'rearGear', 'rearWindow', 'sunRoof', 'package', 'skuGoods']
      let goodsList = []
      let subGoodsList = []
      labelFields.forEach(field => {
        if (Array.isArray(obj[field]) && obj[field].length > 0) {
          goodsList = goodsList.concat(obj[field])
        }
        delete obj[field]
      })
      if (goodsList.length > 0) {
        goodsList.map(e => {
          if (e.goodsFlag == 1) {
            // 单商品
            const sellPrice = parseFloat(e.goods.sellPrice || 0)
            const number = parseInt(e.goods.number || 1)
            const finalPrice = this.calculateFinalPrice(e.goods, sellPrice, number, obj.orderTypeCode)
            const discountFields = this.calculateDiscountFields(e.goods, sellPrice, number, obj.orderTypeCode)
            const unitFinalPrice = finalPrice / number
            subGoodsList.push({
              totalPrice: e.goods.sellPrice,
              number: e.goods.number,
              merchantGoodsId: e.goods.merchantGoodsId,
              finalPrice: finalPrice,
              // 商品实付单价(向上取整保留两位)
              singleProductFinalPrice: utils.ceilDecimal(unitFinalPrice),
              discountType: discountFields.discountType,
              discountValue: discountFields.discountValue,
              discountAmount: discountFields.discountAmount,
              djOrderType: obj.orderTypeCode ? parseInt(obj.orderTypeCode) : null,
              ...this.buildSubOrderGoodsFlags(e, e.goods)
            })
          }
          // 套餐
          if (e.goodsFlag == 3) {
            e.packageGoods.goodsList.forEach(g => {
              const sellPrice = parseFloat(g.sellPrice || 0)
              const number = parseInt(e.packageGoods.number || 1)
              const finalPrice = this.calculateFinalPrice(g, sellPrice, number, obj.orderTypeCode)
              const discountFields = this.calculateDiscountFields(g, sellPrice, number, obj.orderTypeCode)
              const unitFinalPrice = finalPrice / number
              subGoodsList.push({
                packageCode: e.packageGoods.packageCode,
                packageName: e.packageGoods.packageName,
                totalPrice: g.sellPrice,
                number: e.packageGoods.number,
                merchantGoodsId: g.merchantGoodsId,
                upgradePrice: g.oldPrice,
                finalPrice: finalPrice,
                singleProductFinalPrice: utils.ceilDecimal(unitFinalPrice),
                discountType: discountFields.discountType,
                discountValue: discountFields.discountValue,
                discountAmount: discountFields.discountAmount,
                djOrderType: obj.orderTypeCode ? parseInt(obj.orderTypeCode) : null,
                ...this.buildSubOrderGoodsFlags(e, g)
              })
            })
          }
          // 多规格
          if (e.goodsFlag == 2) {
            const goods = e.multipleSpecificationsGoods.goods
            const sellPrice = parseFloat(goods.sellPrice || 0)
            const number = parseInt(e.multipleSpecificationsGoods.number || 1)
            const finalPrice = this.calculateFinalPrice(goods, sellPrice, number, obj.orderTypeCode)
            const discountFields = this.calculateDiscountFields(goods, sellPrice, number, obj.orderTypeCode)
            const unitFinalPrice = finalPrice / number
            subGoodsList.push({
              baseGoodsId: goods.baseGoodsId,
              totalPrice: Number(goods.sellPrice),
              number: e.multipleSpecificationsGoods.number,
              merchantGoodsId: goods.id || goods.merchantGoodsId,
              finalPrice: finalPrice,
              // 商品实付单价(向上取整保留两位)
              singleProductFinalPrice: utils.ceilDecimal(unitFinalPrice),
              discountType: discountFields.discountType,
              discountValue: discountFields.discountValue,
              discountAmount: discountFields.discountAmount,
              djOrderType: obj.orderTypeCode ? parseInt(obj.orderTypeCode) : null,
              ...this.buildSubOrderGoodsFlags(e, goods)
            })
          }
        })
        obj.subOrderList = subGoodsList
      }
      // 主订单传 finalPrice(后端暂时不用)
      obj.finalPrice = this.calculateTotalFinalPrice(subGoodsList)
      // 主订单传 djOrderType(订单类型)
      if (obj.orderTypeCode) {
        obj.djOrderType = parseInt(obj.orderTypeCode)
      }
      delete obj.carBrand
      delete obj.couponInfo
      console.log(obj, 'rucan')

      uni.showLoading({
        title: '提交中...',
        mask: true
      })
      const res = await uni.$api.boutiqueApi[orderCreateType](obj).finally(() => {
        uni.hideLoading()
      })
      if (res) {
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        if (this.orderCreateType == 'createWithPay' && !this.orderObj.id) {
          uni.$track.add({ eventCode: 'app_submit_create_order' })
        } else if (this.orderCreateType == 'supplementOrder') {
          uni.$track.add({ eventCode: 'app_submit_supplement_order' })
        }
        this.$emit('jump', orderCreateType == 'supplementOrder' ? 'OrderDetail' : 'ConfirmOrder', res)
      }
    },
    // 计算所有产品的总价
    changeTotalPrice() {
      let total = 0
      const orderTypeCode = this.orderObj.orderTypeCode
      const orderType = String(orderTypeCode || '')
      // 判断是否使用优惠后的价格(不是正常订单和冲量活动的,都要用优惠后的价格)
      const useFinalPrice = orderType !== '1' && orderType !== '4' && orderType !== '6'

      // 遍历所有商品
      const productFields = ['frontGear', 'frontWindow', 'rearGear', 'rearWindow', 'sunRoof', 'package', 'skuGoods']
      productFields.forEach(slotName => {
        const productList = this.orderObj[slotName]
        if (Array.isArray(productList) && productList.length > 0) {
          // 计算每个产品的价格 * 数量,并累加到总价
          productList.forEach(item => {
            if (item.goods && item.goods.sellPrice) {
              const number = parseInt(item.goods.number || 1)
              if (useFinalPrice && item.goods.finalPrice !== undefined && item.goods.finalPrice !== null) {
                // 使用优惠后的价格(已经是总价:单价优惠后 × 数量)
                total += parseFloat(item.goods.finalPrice || 0)
              } else {
                // 使用原始价格
                total += parseFloat(item.goods.sellPrice) * number
              }
            } else if (item.packageGoods && item.packageGoods.goodsList && item.packageGoods.goodsList.length > 0) {
              const packageNumber = parseInt(item.packageGoods.number || 1)
              item.packageGoods.goodsList.forEach(i => {
                if (i.sellPrice) {
                  if (useFinalPrice && i.finalPrice !== undefined && i.finalPrice !== null) {
                    // 使用优惠后的价格
                    total += parseFloat(i.finalPrice || 0)
                  } else {
                    // 使用原始价格
                    total += parseFloat(i.sellPrice) * packageNumber
                  }
                }
              })
            } else if (item.multipleSpecificationsGoods && item.multipleSpecificationsGoods.goods && item.multipleSpecificationsGoods.goods.sellPrice) {
              const goods = item.multipleSpecificationsGoods.goods
              const number = parseInt(item.multipleSpecificationsGoods.number || 1)
              if (useFinalPrice && goods.finalPrice !== undefined && goods.finalPrice !== null) {
                // 使用优惠后的价格
                total += parseFloat(goods.finalPrice || 0)
              } else {
                // 使用原始价格
                total += parseFloat(goods.sellPrice) * number
              }
            }
          })
        }
      })
      // 更新总价
      this.totalPrice = total.toFixed(2)
    },

    // 获取上一个订单的销售顾问信息 并且不是再次下单
    async getLastUserOrderInfo() {
      const res = await uni.$api.boutiqueApi.getLastUserOrderInfo({
        sellerUserId: this.userInfo.subLoginUser.uuid
      })
      console.log(this.orderObj.merchantId)
      if (this.orderObj.merchantId == res.merchantId) {
        this.$set(this.orderObj, 'employeeName', res.employeeName)
        this.orderObj.userId = res.userId
        console.log(res, '上一个订单的销售顾问信息')
      } else {
        this.getEmployeeList()
      }
    },
    async getShopMerchantPointConfig(merchantId) {
      const res = await uni.$api.boutiqueApi.getShopMerchantPointConfig({ merchantId })
      // 录单员/交付专员配置
      if (res.pointsMultiRole == 'Y') {
        const employeeCell = this.formList[0].find(item => item.label === '销售顾问')
        if (employeeCell) employeeCell.label = '销售顾问/录单员'
        const deliveryCell = this.formList[0].find(item => item.label === '交付专员')
        if (deliveryCell) {
          // 告知 updateSceneGate 选中场景后该字段应展示
          deliveryCell._originHidden = false
          // 当前有无场景决定是否立即展示(避免无场景时提前出现)
          const hasScene = Boolean(this.orderObj && (this.orderObj.baseSceneCodeValue || this.orderObj.baseSceneCode))
          deliveryCell.hidden = !hasScene
        }
      }
      // 订单类型配置:createAllGoodsFlag = 1 显示全部类型;0 仅正常订单
      if (res.createAllGoodsFlag !== undefined && res.createAllGoodsFlag !== null) {
        uni.$storage.set('createAllGoodsFlag', res.createAllGoodsFlag)
      }
    },
    // 判断二级流量方
    async getSubShopMerchantList(merchantId) {
      const res = await uni.$api.boutiqueApi.getSubShopMerchantList({ merchantId })
      if (res && res.length) {
        this.subShopMerchantList = res
        const cell = this.formList[0].find(item => item.label === '二级流量方')
        if (cell) {
          cell._originHidden = false
          const hasScene = Boolean(this.orderObj && (this.orderObj.baseSceneCodeValue || this.orderObj.baseSceneCode))
          cell.hidden = !hasScene
        }
      }
    },
    // 动态获取 车型 车架 车牌 是否必填
    getYQorderInfo() {
      return new Promise(async (resolve, reject) => {
        const YQorderSetting = uni.$storage.get('boutique_YQorderSetting')
        if (YQorderSetting) return resolve(YQorderSetting)
        else {
          const { userInfo } = this
          let { shopMerchantId, merchantId, shopMerchantName } = userInfo
          const data = await uni.$api.boutiqueApi.getMerchantRecordingSettings({
            scene: 1,
            merchantId: shopMerchantId,
            merchantName: shopMerchantName
          })
          if (data) {
            let YQorderSetting = {}
            const keyMap = {
              carBrand: 'carTypeRequiredFlag',
              carNo: 'standNoRequiredFlag',
              plateNo: 'plateNumRequiredFlag',
              notUpgradeExperience: 'foEfRequiredFlag',
              notUpgradeRejectionReason: 'foRrRequiredFlag'
            }
              ; (data.orderFieldSettingList || []).forEach(e => {
                const key = keyMap[e.fieldKey] || e.fieldKey
                YQorderSetting[key] = e.isRequired ? 'Y' : 'N'
              })

            YQorderSetting.shopMerchantId = userInfo.shopMerchantId
            // 过滤园区店是否需要屏蔽手机号选项
            let filterYqPhoneConfig = JSON.parse(data.yqPhoneConfig)
            YQorderSetting.yqPhoneConfig = filterYqPhoneConfig?.find(item => item.yqMerchantId == merchantId)

            console.log(YQorderSetting)
            uni.$storage.set('boutique_YQorderSetting', YQorderSetting)
            resolve(YQorderSetting)
          }
        }
      })
    },
    // 获取车型、车架号、车牌号必填规则
    async getSetting() {
      const res = await this.getYQorderInfo()
      const dictionaryObj = {
        carTypeRequiredFlag: 'carBrand',
        standNoRequiredFlag: 'standNo',
        plateNumRequiredFlag: 'plateNumber'
      }
      for (const key in dictionaryObj) {
        const cell = this.formList[1].find(item => item.value === dictionaryObj[key])
        if (cell) cell.required = res[key] == 'Y'
      }
    },
    // 获取园区店支付方式
    async getConfig() {
      const res = await uni.$api.boutiqueApi.getYqStoreConfig({
        yqMerchantId: this.orderObj.sellerMerchantId
      })
      let m = res.supportPayTypes || []
      let n = this.payTypeList
      let list = n.filter(k => {
        let idx = m.find(j => j == k.value)
        return idx >= 0
      })
      // this.configPayTypeList = list
      this.djPayList = [
        ...list?.filter(v => ![2, 5].includes(Number(v.value))),
        {
          name: '对公转账',
          value: '6'
        },
        {
          name: '其它收款',
          value: '7'
        }
      ]
      this.merchantPayList = [...list?.filter(v => v.value == 2)]
      this.changePayee()
      console.log(this.djPayList, this.merchantPayList, 'list')
    },
    changePayee() {
      const cell = this.formList[2].find(item => item.value === 'selectPayType')
      if (cell) {
        cell.radioList = this.orderObj.payeeType == 1 ? this.merchantPayList : this.djPayList
        if (!this.orderObj.id && cell.radioList && cell.radioList.length > 0) {
          cell.current = cell.radioList[0].value
          // 使用 $set 确保响应式更新
          this.$set(this.orderObj, 'selectPayType', cell.radioList[0].value)
        }
      }
    },
    // 获取 销售顾问列表
    async getEmployeeList() {
      const { userInfo, orderObj } = this
      const { shopMerchantId, sceneType, merchantId } = userInfo,
        data = await uni.$api.popupApi.getEmployeeList({
          merchantId: orderObj.idKey == 'sellerUserId' ? merchantId : shopMerchantId,
          sceneList: orderObj.idKey == 'sellerUserId' ? '' : [this.orderObj.sceneType != null ? this.orderObj.sceneType : sceneType]
        })
      if (data && data.length) {
        this.employeeList = data
        this.$set(this.orderObj, 'employeeName', data[0].staffName)
        this.orderObj.userId = data[0].uuid
      }
    },
    async getPositionList() {
      const res = await uni.$api.boutiqueApi.getPositionList({})
      this.positionTypeList = res
    },
    // 商品列表
    async getSelectOrderGoodsList() {
      const { userInfo } = this
      const res = await uni.$api.boutiqueApi.getSelectOrderGoodsList({
        merchantId: userInfo.shopMerchantId,
        sceneType: userInfo.sceneType,
        baseSceneCode: this.orderObj.baseSceneCodeValue
      })
      this.goodsList = res

      // 分类映射
      const posMap = {
        frontGear: [1],
        frontWindow: [2],
        rearGear: [3],
        rearWindow: [4],
        sunRoof: [5, 6, 7]
      }
      // 初始化各类商品数组
      const arrMap = {
        frontGear: [],
        frontWindow: [],
        rearGear: [],
        rearWindow: [],
        sunRoof: []
      }

      res.forEach(val => {
        if (val.goodsFlag == 1) {
          let subVal = val.goods
          subVal.positionStr = subVal.position
          subVal.upgradePrice = subVal.sellPrice
          subVal.price = subVal.sellPrice
          snapshotOriginalPrice(subVal)
          subVal.goodsId = subVal.merchantGoodsId

          Object.keys(posMap).forEach(key => {
            if (posMap[key].includes(subVal.merchantGoodsPosition)) {
              arrMap[key].push(val)
            }
          })
        }
        //商品多规格
        if (val.goodsFlag == 2) {
          val.multipleSpecificationsGoods.specificationList.forEach(item => {
            item.specificationSelectValueList = []
            item.specificationValueList.forEach(second => {
              if (second.show) {
                item.specificationSelectValueList.push(second.specificationValue)
              }
            })
          })
          this.otherProduct.push(val)
        }
      })
      console.log(arrMap, 'arrMap')
      // 批量设置 hidden 属性
      Object.keys(arrMap).forEach(key => {
        const cell = this.formList[2].find(item => item.value === key)
        if (cell) cell.hidden = arrMap[key].length === 0
      })
      console.log('this.formList', this.formList)
      const subOrderList = this.subOrderList || []
      console.log('subOrderList', subOrderList)
      let chooseList = []
      subOrderList.map(e => {
        // 普通商品
        if (e && !e.packageName) {
          if (e.specificationData.indexOf(';~;') == -1) {
            // 修复取值字段名字错误问题
            // 始终使用 totalPrice(原价)来计算单价,确保编辑时显示的是原价,而不是优惠后的价格
            // 即使 e.price 已存在(可能被 ConfirmOrder.vue 设置为优惠后的价格),也要重新计算
            const catalogMatch = this.findCatalogGoodsMatch({ merchantGoodsId: e.merchantGoodsId, goodsId: e.goodsId })
            snapshotActivityPriceFromCatalog(e, catalogMatch)
            if (e.totalPrice !== undefined && e.totalPrice !== null) {
              e.price = utils.ceilDecimal(Number(e.totalPrice) / Number(e.number || 1))
            } else if (!e.price) {
              // 如果没有 totalPrice,才使用已存在的 price 或计算默认值
              e.price = utils.ceilDecimal(Number(e.finalPrice || 0) / Number(e.number || 1))
            }
            e.sellPrice = e.price
            e.goodsId = e.merchantGoodsId
            if (!e.minSellPrice) e.minSellPrice = e.upgradeShopMinPrice
            e.goodsInfo = {
              goodsName: e.upgradeGoodsAlias || e.upgradeGoodsName
            }
            e.merchantGoodsId = e.merchantGoodsId || e.id
            // 确保 number 字段存在且正确(用于回显)
            if (e.number !== undefined && e.number !== null) {
              e.number = String(e.number)
            } else {
              e.number = '1'
            }

            // 回显 finalPrice 和 strategyConfig
            if (e.finalPrice !== undefined && e.finalPrice !== null) {
              e.finalPrice = parseFloat(e.finalPrice)
            }
            // 优先使用商品级别的 djOrderType,否则使用订单级别的 orderTypeCode
            const goodsOrderTypeCode = e.djOrderType ? String(e.djOrderType) : this.orderObj.orderTypeCode
            // 始终根据 discountType 和 discountValue 重新构建 strategyConfig,忽略后端可能错误的 strategyConfig
            if (goodsOrderTypeCode && e.discountType !== undefined && e.discountType !== null) {
              // 删除后端可能错误的 strategyConfig,重新构建
              delete e.strategyConfig
              const newStrategyConfig = this.buildStrategyConfigFromDiscountFields(e, goodsOrderTypeCode)
              this.$set(e, 'strategyConfig', newStrategyConfig)
            }
            if (e.activityId == null || e.activityId === '') {
              const catalogActivityId = this.getCatalogActivityId({ merchantGoodsId: e.merchantGoodsId, goodsId: e.goodsId })
              if (catalogActivityId != null && catalogActivityId !== '') {
                e.activityId = catalogActivityId
              }
            }

            chooseList.push({
              goodsFlag: 1,
              goods: e,
              number: e.number,
              active: true,
              marketingFlag: this.getMarketingFlag({ merchantGoodsId: e.merchantGoodsId, goodsId: e.goodsId })
            })
          }
          // 多规格商品
          if (e.specificationData.indexOf(';~;') > -1) {
            // 修复取值字段名字错误问题
            // 始终使用 totalPrice(原价)来计算单价,确保编辑时显示的是原价,而不是优惠后的价格
            // 即使 e.price 已存在(可能被 ConfirmOrder.vue 设置为优惠后的价格),也要重新计算
            const catalogMatch = this.findCatalogGoodsMatch({ merchantGoodsId: e.merchantGoodsId, goodsId: e.goodsId })
            snapshotActivityPriceFromCatalog(e, catalogMatch)
            if (e.totalPrice !== undefined && e.totalPrice !== null) {
              e.price = utils.ceilDecimal(Number(e.totalPrice) / Number(e.number || 1))
            } else if (!e.price) {
              // 如果没有 totalPrice,才使用已存在的 price 或计算默认值
              e.price = utils.ceilDecimal(Number(e.finalPrice || 0) / Number(e.number || 1))
            }
            e.sellPrice = e.price
            e.goodsId = e.merchantGoodsId
            if (!e.minSellPrice) e.minSellPrice = e.upgradeShopMinPrice
            e.goodsInfo = {
              goodsName: e.upgradeGoodsAlias || e.upgradeGoodsName
            }
            // 确保数量字段正确回显(多规格商品使用 count 字段)
            if (e.number !== undefined && e.number !== null) {
              e.count = e.number
            } else {
              e.count = 1
            }
            e.merchantGoodsId = e.merchantGoodsId || e.id

            // 回显 finalPrice 和 strategyConfig(多规格商品需要传递给 handleSpecificationsEcho)
            if (e.finalPrice !== undefined && e.finalPrice !== null) {
              e.finalPrice = parseFloat(e.finalPrice)
            }
            // 优先使用商品级别的 djOrderType,否则使用订单级别的 orderTypeCode
            const goodsOrderTypeCode = e.djOrderType ? String(e.djOrderType) : this.orderObj.orderTypeCode
            if (goodsOrderTypeCode && e.discountType !== undefined && e.discountType !== null) {
              // 删除后端可能错误的 strategyConfig,重新构建
              delete e.strategyConfig
              const newStrategyConfig = this.buildStrategyConfigFromDiscountFields(e, goodsOrderTypeCode)
              this.$set(e, 'strategyConfig', newStrategyConfig)
            }

            let specificdata = this.handleSpecificationsEcho(e)
            console.log(specificdata, 'specificdata')
            chooseList = chooseList.concat(specificdata)
          }
        }
        // 套餐
        if (e && e.packageName) {
          const catalogMatch = this.findCatalogGoodsMatch({ packageGoods: e })
          e.packageGoodsOrderList.forEach(g => {
            snapshotActivityPriceFromCatalog(g, catalogMatch)
            // 注意:价格为 0 时也要回显,不能用 truthy 判断
            if (g.totalPrice !== undefined && g.totalPrice !== null) {
              g.price = utils.ceilDecimal(Number(g.totalPrice) / Number(g.number || 1)).toFixed(2)
            } else if (g.sellPrice !== undefined && g.sellPrice !== null && g.sellPrice !== '') {
              g.price = utils.ceilDecimal(Number(g.sellPrice)).toFixed(2)
            } else {
              g.price = '0.00'
            }
            g.sellPrice = g.price

            // 回显 finalPrice 和 strategyConfig(套餐内每个商品)
            if (g.finalPrice !== undefined && g.finalPrice !== null) {
              g.finalPrice = parseFloat(g.finalPrice)
            }
            // 优先使用商品级别的 djOrderType,否则使用订单级别的 orderTypeCode
            const goodsOrderTypeCode = g.djOrderType ? String(g.djOrderType) : this.orderObj.orderTypeCode
            if (goodsOrderTypeCode && g.discountType !== undefined && g.discountType !== null) {
              // 删除后端可能错误的 strategyConfig,重新构建
              delete g.strategyConfig
              const newStrategyConfig = this.buildStrategyConfigFromDiscountFields(g, goodsOrderTypeCode)
              this.$set(g, 'strategyConfig', newStrategyConfig)
            }
          })
          e.goodsList = e.packageGoodsOrderList
          e.upgradePrice = e.goodsList.reduce((prev, cur) => {
            console.log(prev, cur)
            return prev + cur.sellPrice
          }, 0)
          e.number = e.goodsList.length ? e.goodsList[0].number : 1

          e.price = e.goodsList.reduce((prev, cur) => {
            // 注意:cur.totalPrice 可能为 0 或空,需要显式处理
            const unit = cur.totalPrice !== undefined && cur.totalPrice !== null ? Number(cur.totalPrice) / Number(cur.number || 1) : Number(cur.sellPrice || 0)
            return prev + unit
          }, 0)
          e.price = Number(utils.decimal(e.price, 2)).toFixed(2)

          const catalogActivityId = this.getCatalogActivityId({ packageGoods: e })
          if (catalogActivityId != null && catalogActivityId !== '') {
            if (e.activityId == null || e.activityId === '') {
              e.activityId = catalogActivityId
            }
          }

          chooseList.push({
            isType: 'meal',
            active: true,
            goodsFlag: 3,
            packageGoods: e,
            number: e.number,
            totalPrice: e.price,
            marketingFlag: this.getMarketingFlag({ packageGoods: e })
          })
        }
      })
      console.log(chooseList, 'chooseList')
      const _singleGoods = chooseList.filter(item => item.goodsFlag == 1)
      const _packageGoods = chooseList.filter(item => item.goodsFlag == 3)
      const _skuGoods = chooseList.filter(item => item.goodsFlag == 2) || []
      console.log(_singleGoods, 'singleGoods')
      if (_singleGoods) {
        // 回显upgradeGoodsPosition   1:前挡 2:前窗 3:后窗 4:后挡 5、6、7:天窗。 为空则是其他精品
        this.$set(
          this.orderObj,
          'frontGear',
          _singleGoods.filter(item => item.goods.upgradeGoodsPosition == 1)
        )
        this.$set(
          this.orderObj,
          'frontWindow',
          _singleGoods.filter(item => item.goods.upgradeGoodsPosition == 2)
        )
        this.$set(
          this.orderObj,
          'rearWindow',
          _singleGoods.filter(item => item.goods.upgradeGoodsPosition == 4)
        )
        this.$set(
          this.orderObj,
          'rearGear',
          _singleGoods.filter(item => item.goods.upgradeGoodsPosition == 3)
        )
        this.$set(
          this.orderObj,
          'sunRoof',
          _singleGoods.filter(item => item.goods.upgradeGoodsPosition == 5 || item.goods.upgradeGoodsPosition == 6 || item.goods.upgradeGoodsPosition == 7)
        )
        // 将没有upgradeGoodsPosition的商品添加到_skuGoods中
        const noPositionGoods = _singleGoods.filter(item => !item.goods.upgradeGoodsPosition)
        if (noPositionGoods.length > 0) {
          _skuGoods.push(...noPositionGoods)
        }
      }
      if (_packageGoods) {
        this.$set(this.orderObj, 'package', _packageGoods)
      }
      console.log(_skuGoods, '_skuGoods')
      if (_skuGoods && _skuGoods.length) {
        this.$set(this.orderObj, 'skuGoods', _skuGoods)
      }
      console.log(this.orderObj, 'this.orderObj')
      this.changeTotalPrice()
    },
    handleSpecificationsEcho(item) {
      let skuArr = []
      const { otherProduct } = this,
        arr = item.specificationData.split('/'),
        str = arr.join(';~;'),
        obj = {
          count: item.count,
          goodsFlag: 2,
          goods: null,
          active: true,
          isFlag: true, //初始化进来不显示标识
          marketingFlag: null
        }
      otherProduct.forEach(data => {
        if (data.goodsFlag == 2) {
          let tempData = data.multipleSpecificationsGoods.specificationGoodsMap[str]
          if (tempData) {
            tempData.forEach(temp => {
              if (temp.merchantGoodsId == item.goodsId) {
                // 回显 finalPrice 和 strategyConfig(多规格商品)
                // 确保使用原价(totalPrice),而不是可能被设置为优惠后的 item.price
                let goodsPrice = item.price
                if (item.totalPrice !== undefined && item.totalPrice !== null) {
                  // 优先使用 totalPrice(原价)计算单价
                  goodsPrice = utils.ceilDecimal(Number(item.totalPrice) / Number(item.number || 1))
                } else if (!item.price && item.finalPrice !== undefined && item.finalPrice !== null) {
                  // 如果没有 totalPrice 和 price,才使用 finalPrice
                  goodsPrice = utils.ceilDecimal(Number(item.finalPrice) / Number(item.number || 1))
                }
                const catalogMatch = this.findCatalogGoodsMatch({ merchantGoodsId: item.goodsId, goodsId: item.goodsId })
                const goodsData = {
                  ...temp,
                  price: goodsPrice,
                  sellPrice: goodsPrice,
                  goodsId: item.goodsId,
                  specificationStr: item.specificationData.replace(/;~;/g, '/')
                }
                snapshotActivityPriceFromCatalog(goodsData, catalogMatch)
                if ((goodsData.oldPrice == null || goodsData.oldPrice === '') && temp.sellPrice != null && temp.sellPrice !== '') {
                  goodsData.oldPrice = temp.sellPrice
                }
                if (item.finalPrice !== undefined && item.finalPrice !== null) {
                  goodsData.finalPrice = parseFloat(item.finalPrice)
                }
                // 确保 discountType 和 discountValue 也传递到 goodsData 中,以便 initStrategyConfig 能正确识别回显数据
                if (item.discountType !== undefined && item.discountType !== null) {
                  goodsData.discountType = item.discountType
                }
                if (item.discountValue !== undefined && item.discountValue !== null) {
                  goodsData.discountValue = item.discountValue
                }
                // 优先使用商品级别的 djOrderType,否则使用订单级别的 orderTypeCode
                const goodsOrderTypeCode = item.djOrderType ? String(item.djOrderType) : this.orderObj.orderTypeCode
                if (goodsOrderTypeCode && item.discountType !== undefined && item.discountType !== null) {
                  // 删除后端可能错误的 strategyConfig,重新构建
                  delete goodsData.strategyConfig
                  const newStrategyConfig = this.buildStrategyConfigFromDiscountFields(item, goodsOrderTypeCode)
                  goodsData.strategyConfig = newStrategyConfig
                }
                const resolvedMarketingFlag = item.marketingFlag ?? temp.marketingFlag ?? data.multipleSpecificationsGoods?.marketingFlag ?? getMarketingFlag(data)
                if (resolvedMarketingFlag != null && resolvedMarketingFlag !== '') {
                  goodsData.marketingFlag = resolvedMarketingFlag
                }
                const resolvedActivityId = item.activityId ?? temp.activityId ?? data.multipleSpecificationsGoods?.activityId ?? getActivityId(data)
                if (resolvedActivityId != null && resolvedActivityId !== '') {
                  goodsData.activityId = resolvedActivityId
                }

                obj.multipleSpecificationsGoods = {
                  ...data.multipleSpecificationsGoods,
                  baseGoodsName: item.goodsName || item.upgradeGoodsName,
                  goods: goodsData,
                  // 确保数量字段正确回显
                  number: item.count !== undefined && item.count !== null ? String(item.count) : '1'
                }
                if (resolvedMarketingFlag != null && resolvedMarketingFlag !== '') {
                  obj.multipleSpecificationsGoods.marketingFlag = resolvedMarketingFlag
                }
                if (resolvedActivityId != null && resolvedActivityId !== '') {
                  obj.multipleSpecificationsGoods.activityId = resolvedActivityId
                }
                obj.marketingFlag = resolvedMarketingFlag
                if (resolvedActivityId != null && resolvedActivityId !== '') {
                  obj.activityId = resolvedActivityId
                }
                skuArr.push(obj)
              }
            })
          }
        }
      })
      console.log(skuArr)
      return skuArr
    },
    buildSubOrderGoodsFlags(orderItem, goods) {
      if (!['createWithPay', 'supplementOrder'].includes(this.orderCreateType)) return {}

      const catalogMatch = this.resolveCatalogMatch(orderItem, goods)
      let marketingFlag = getSubmitMarketingFlag(orderItem, goods)
      if (marketingFlag !== 1 && catalogMatch) {
        marketingFlag = getSubmitMarketingFlag(catalogMatch)
      }

      const flags = {
        marketingFlag,
        modifyFlag: getSubmitModifyFlag(goods)
      }

      if (marketingFlag === 1) {
        let activityId = getSubmitActivityId(orderItem, goods)
        if ((activityId == null || activityId === '') && catalogMatch) {
          activityId = getActivityId(catalogMatch)
          if ((activityId == null || activityId === '') && orderItem.goodsFlag == 3 && goods?.merchantGoodsId) {
            const pkgGoods = catalogMatch.packageGoods?.goodsList?.find(g => g.merchantGoodsId == goods.merchantGoodsId)
            activityId = pkgGoods?.activityId
          }
        }
        if (activityId != null && activityId !== '') {
          flags.activityId = activityId
        }
      }
      return flags
    },
    resolveCatalogMatch(orderItem, goods) {
      if (!orderItem) return undefined
      if (orderItem.goodsFlag == 1) {
        const g = goods ?? orderItem.goods
        return this.findCatalogGoodsMatch({
          merchantGoodsId: g?.merchantGoodsId,
          goodsId: g?.goodsId ?? g?.merchantGoodsId
        })
      }
      if (orderItem.goodsFlag == 2) {
        const id = orderItem.multipleSpecificationsGoods?.id ?? orderItem.multipleSpecificationsGoods?.merchantGoodsId
        return this.findCatalogGoodsMatch({ merchantGoodsId: id, goodsId: id })
      }
      if (orderItem.goodsFlag == 3 && orderItem.packageGoods) {
        return this.findCatalogGoodsMatch({ packageGoods: orderItem.packageGoods })
      }
      return undefined
    },
    enrichOrderItemsMarketingFields(items) {
      if (!Array.isArray(items)) return
      items.forEach(item => {
        const catalogMatch = this.resolveCatalogMatch(item)
        if (!catalogMatch) return

        const catalogMarketingFlag = getMarketingFlag(catalogMatch)
        const catalogActivityId = getActivityId(catalogMatch)

        if (catalogMarketingFlag != null && catalogMarketingFlag !== '' && (item.marketingFlag == null || item.marketingFlag === '')) {
          item.marketingFlag = catalogMarketingFlag
        }
        if (catalogActivityId != null && catalogActivityId !== '' && (item.activityId == null || item.activityId === '')) {
          item.activityId = catalogActivityId
        }

        if (item.goodsFlag == 1 && item.goods) {
          if (catalogMarketingFlag != null && catalogMarketingFlag !== '' && (item.goods.marketingFlag == null || item.goods.marketingFlag === '')) {
            item.goods.marketingFlag = catalogMarketingFlag
          }
          if (catalogActivityId != null && catalogActivityId !== '' && (item.goods.activityId == null || item.goods.activityId === '')) {
            item.goods.activityId = catalogActivityId
          }
        }

        if (item.goodsFlag == 2 && item.multipleSpecificationsGoods) {
          const msg = item.multipleSpecificationsGoods
          if (catalogMarketingFlag != null && catalogMarketingFlag !== '' && (msg.marketingFlag == null || msg.marketingFlag === '')) {
            msg.marketingFlag = catalogMarketingFlag
          }
          if (catalogActivityId != null && catalogActivityId !== '' && (msg.activityId == null || msg.activityId === '')) {
            msg.activityId = catalogActivityId
          }
          if (msg.goods) {
            if (catalogMarketingFlag != null && catalogMarketingFlag !== '' && (msg.goods.marketingFlag == null || msg.goods.marketingFlag === '')) {
              msg.goods.marketingFlag = catalogMarketingFlag
            }
            if (catalogActivityId != null && catalogActivityId !== '' && (msg.goods.activityId == null || msg.goods.activityId === '')) {
              msg.goods.activityId = catalogActivityId
            }
          }
        }

        if (item.goodsFlag == 3 && item.packageGoods) {
          if (catalogMarketingFlag != null && catalogMarketingFlag !== '' && (item.packageGoods.marketingFlag == null || item.packageGoods.marketingFlag === '')) {
            item.packageGoods.marketingFlag = catalogMarketingFlag
          }
          if (catalogActivityId != null && catalogActivityId !== '' && (item.packageGoods.activityId == null || item.packageGoods.activityId === '')) {
            item.packageGoods.activityId = catalogActivityId
          }
          item.packageGoods.goodsList?.forEach(g => {
            const catalogGoods = catalogMatch.packageGoods?.goodsList?.find(cg => cg.merchantGoodsId == g.merchantGoodsId)
            if (!catalogGoods) return
            if (catalogGoods.marketingFlag != null && catalogGoods.marketingFlag !== '' && (g.marketingFlag == null || g.marketingFlag === '')) {
              g.marketingFlag = catalogGoods.marketingFlag
            }
            if (catalogGoods.activityId != null && catalogGoods.activityId !== '' && (g.activityId == null || g.activityId === '')) {
              g.activityId = catalogGoods.activityId
            }
          })
        }
      })
    },
    findCatalogGoodsMatch({ merchantGoodsId, goodsId, packageGoods } = {}) {
      const list = this.goodsList || []
      return list.find(item => {
        if (item.goodsFlag == 1) {
          const id = item.goods?.merchantGoodsId
          return id != null && (id == merchantGoodsId || id == goodsId)
        }
        if (item.goodsFlag == 2) {
          const id = item.multipleSpecificationsGoods?.id ?? item.multipleSpecificationsGoods?.merchantGoodsId
          return id != null && (id == merchantGoodsId || id == goodsId)
        }
        if (item.goodsFlag == 3 && packageGoods) {
          const pkgCode = item.packageGoods?.packageCode
          const targetCode = packageGoods.packageCode
          if (pkgCode && targetCode && pkgCode === targetCode) return true
          const pkgId = item.packageGoods?.merchantGoodsId ?? item.packageGoods?.id ?? item.packageGoods?.packageId
          const targetId = packageGoods.merchantGoodsId ?? packageGoods.id ?? packageGoods.packageId
          return pkgId != null && targetId != null && pkgId == targetId
        }
        return false
      })
    },
    getMarketingFlag({ merchantGoodsId, goodsId, packageGoods } = {}) {
      return getMarketingFlag(this.findCatalogGoodsMatch({ merchantGoodsId, goodsId, packageGoods }))
    },
    getCatalogActivityId({ merchantGoodsId, goodsId, packageGoods } = {}) {
      return getActivityId(this.findCatalogGoodsMatch({ merchantGoodsId, goodsId, packageGoods }))
    },
    applyOrderEchoFromRest(orderData, { skipOrderId = false } = {}) {
      const customer = orderData.customer || {}
      const customerCoupon = orderData.customerCoupon || {}
      const rest = orderData
      const baseFields = ['id', 'orderCode', 'userId', 'employeeName', 'deliveryEmployeeName', 'deliveryUserId', 'subShopMerchantName', 'subShopMerchantId', 'sellerName', 'sellerUserId', 'sellerMerchantName', 'sellerMerchantId', 'merchantId', 'merchantName', 'customerCouponId', 'selectPayType']
      const fieldsToAssign = skipOrderId ? baseFields.filter(field => !['id', 'orderCode'].includes(field)) : baseFields
      Object.assign(this.orderObj, Object.fromEntries(fieldsToAssign.map(field => [field, rest[field]])))

      this.$set(this.orderObj, 'baseSceneCode', rest.baseSceneName || '')
      this.$set(this.orderObj, 'baseSceneCodeValue', rest.baseSceneCode || '')
      const sceneCell = this.formList?.[0]?.find(item => item.value === 'baseSceneCode')
      if (sceneCell) sceneCell.current = rest.baseSceneName || ''

      const orderTypeMap = {
        1: '正常订单',
        2: '打折策略',
        3: '买赠策略',
        4: '冲量活动',
        5: '组合付款',
        6: '内部结算'
      }
      if (rest.djOrderType !== undefined && rest.djOrderType !== null) {
        this.orderObj.orderTypeCode = String(rest.djOrderType)
        this.orderObj.djOrderType = orderTypeMap[this.orderObj.orderTypeCode] || ''
      } else {
        this.orderObj.orderTypeCode = '1'
        this.orderObj.djOrderType = orderTypeMap['1'] || '正常订单'
      }
      let actualDeliveryDate = rest.actualDeliveryDate || customer.actualDeliveryDate,
        customerTags = rest.customerTags || customer.customerTags
      if (actualDeliveryDate) this.orderObj.actualDeliveryDate = dayjs(actualDeliveryDate).format('YYYY-MM-DD')
      if (customerTags && typeof customerTags === 'string') this.orderObj.customerTags = customerTags.split(',')

      this.orderObj.payeeType = rest.selectPayType == '2' ? '1' : '0'
      const customerFields = ['customerName', 'customerSex', 'customerPhone', 'salesType', 'standNo', 'plateNumber', 'experienceFlag']
      Object.assign(this.orderObj, Object.fromEntries(customerFields.map(field => [field, customer[field]])))

      const { couponName, customerCouponCode } = customerCoupon
      if (couponName || customerCouponCode) {
        Object.assign(this.orderObj, {
          couponName,
          customerCouponCode,
          couponInfo: `${couponName || ''}${customerCouponCode || ''}`
        })
      }

      this.orderObj.customer = {
        carBrand: customer.carBrand,
        carBrandId: customer.carBrandId,
        carChildsBrandId: customer.carChildsBrandId,
        carChildsBrandName: customer.carChildsBrandName,
        carSeriesId: customer.carSeriesId,
        carSeriesName: customer.carSeriesName,
        customerPhone: customer.customerPhone,
        standNo: customer.standNo,
        plateNumber: customer.plateNumber,
        customerSex: customer.customerSex,
        experienceFlag: customer.experienceFlag,
        salesType: customer.salesType,
        customerName: customer.customerName
      }

      this.orderObj.carBrand = customer.carBrandId ? `${customer.carBrand}-${customer.carChildsBrandName}-${customer.carSeriesName}` : ''

      const updateFormCell = (formIndex, fieldName, value) => {
        const cell = this.formList[formIndex].find(item => item.value === fieldName)
        if (cell) cell.current = value
      }

      const formUpdates = [
        [1, 'salesType', customer.salesType],
        [1, 'customerSex', customer.customerSex],
        [1, 'experienceFlag', customer.experienceFlag],
        [2, 'selectPayType', this.orderObj.selectPayType],
        [2, 'payeeType', this.orderObj.payeeType]
      ]
      formUpdates.forEach(([index, field, value]) => updateFormCell(index, field, value))

      const orderTypeCell = this.formList[2].find(item => item.value === 'djOrderType')
      if (orderTypeCell && this.orderObj.djOrderType) {
        orderTypeCell.current = this.orderObj.djOrderType
      }
    },
    prepareSubOrderListFromOrder(orderData) {
      let subOrderList = (orderData.subOrderList || []).filter(item => item.merchantGoodsId)
      const packageGoodsList = orderData.packageGoodsList || []
      if (packageGoodsList.length) {
        packageGoodsList.forEach(item => {
          item.goodsList = item.packageGoodsOrderList
          item.price = item.goodsList.reduce((prev, cur) => {
            return prev + Number(cur.finalPrice) / Number(cur.number)
          }, 0)
          item.count = item.goodsList.length ? item.goodsList[0].number : 1
          const total = item.price * item.count
          item.finalPrice = utils.decimal(total, 2)
        })
        subOrderList = subOrderList.concat(packageGoodsList)
      }
      return subOrderList
    },
    // 判断订单客户信息是否需要从建档详情补全(任一关键字段缺失即触发)
    needsCustomerProfileBackfill(customer = {}) {
      const profileFields = ['standNo', 'carSeriesId', 'carSeriesName', 'carBrandId', 'carBrand', 'carChildsBrandId', 'carChildsBrandName']
      return profileFields.some(field => customer[field] == null || customer[field] === '')
    },
    // 将客户建档详情接口返回的数据回填到订单表单,仅补缺失字段,不覆盖已有值
    applyCustomerProfileBackfill(res, customer = {}) {
      if (!res || typeof res !== 'object') return

      // 与 detailFiles.vue findVisitsInfo 保持一致:建档接口的车型字段需映射为订单使用的 carChildsBrand 字段
      if (res.carChildsBrandId) res.carChildsBrandId = res.carSeriesId
      if (res.carChildsBrandName) res.carChildsBrandName = res.carSeriesName

      const profileFields = ['standNo', 'carSeriesId', 'carSeriesName', 'carBrandId', 'carBrand', 'carChildsBrandId', 'carChildsBrandName']
      if (!this.orderObj.customer) this.$set(this.orderObj, 'customer', {})

      profileFields.forEach(field => {
        if ((customer[field] == null || customer[field] === '') && res[field] != null && res[field] !== '') {
          customer[field] = res[field]
          this.$set(this.orderObj.customer, field, res[field])
        }
      })

      // standNo 同时存在于 orderObj 顶层与 customer 对象,需同步回填
      if ((this.orderObj.standNo == null || this.orderObj.standNo === '') && res.standNo) {
        this.$set(this.orderObj, 'standNo', res.standNo)
      }

      // 拼接车型展示文案:一级品牌-子品牌-车系(与 applyOrderEchoFromRest 回显逻辑一致)
      const c = this.orderObj.customer
      if (c.carBrandId && (this.orderObj.carBrand == null || this.orderObj.carBrand === '')) {
        this.$set(this.orderObj, 'carBrand', `${c.carBrand}-${c.carChildsBrandName}-${c.carSeriesName}`)
      }
    },
    // 调用客户建档详情接口(customerProfileInfoAPI),补全订单中缺失的客户车型与车架号信息
    async fetchAndBackfillCustomerProfile(customerId, customer = {}) {
      if (!customerId || !this.needsCustomerProfileBackfill(customer)) return
      try {
        const res = await uni.$api.customerApi.customerProfileInfoAPI({ id: customerId })
        this.applyCustomerProfileBackfill(res, customer)
        console.log('补全客户详情***', res)
      } catch (e) {
        console.error('获取客户详情失败', e)
      }
    },
    async fetchGoodsOrderRemark(customerId) {
      console.log('获取订单备注***', customerId)
      if (!customerId) return
      try {
        const res = await uni.$api.commonApi.updateGoodsOrderRemark({ id: customerId })
        console.log('获取订单备注***', res)
        const remark = res?.remark || ''
        this.$set(this.orderObj, 'remark', remark)
      } catch (e) {
        console.error('获取订单备注失败', e)
      }
    },
    async setCustomerInfo(customerInfo) {
      const productFields = ['frontGear', 'frontWindow', 'rearGear', 'rearWindow', 'sunRoof', 'package', 'skuGoods']
      productFields.forEach(field => {
        this.$set(this.orderObj, field, null)
      })

      this.applyOrderEchoFromRest(customerInfo, { skipOrderId: true })
      this.orderObj.customerId = customerInfo.id
      this.subOrderList = this.prepareSubOrderListFromOrder(customerInfo)

      const customerId = customerInfo.customer?.customerId
      if (customerId) {
        // 选择客户带入订单时,同样可能存在车型/车架号缺失,优先补全后再拉取备注
        await this.fetchAndBackfillCustomerProfile(customerId, customerInfo.customer)
        await this.fetchGoodsOrderRemark(customerId)
      }

      this.updateSceneGate()
      const echoedSelectPayType = this.orderObj.selectPayType
      const echoedPayeeType = this.orderObj.payeeType
      this.changePayee()
      if (echoedSelectPayType != null && echoedSelectPayType !== '') {
        this.$set(this.orderObj, 'selectPayType', echoedSelectPayType)
        const payCell = this.formList[2].find(item => item.value === 'selectPayType')
        if (payCell) payCell.current = echoedSelectPayType
      }
      if (echoedPayeeType != null && echoedPayeeType !== '') {
        this.$set(this.orderObj, 'payeeType', echoedPayeeType)
        const payeeCell = this.formList[2].find(item => item.value === 'payeeType')
        if (payeeCell) payeeCell.current = echoedPayeeType
      }
      await this.getSelectOrderGoodsList()

      if (this.orderObj.standNo) {
        this.orderObj.standNo = formatVinInput(this.orderObj.standNo)
        validateVin(this.orderObj.standNo)
          .then(result => {
            this.validateState = result.data.valid
          })
          .catch(() => { })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.order {
  height: 100%;
}

.box {
  height: calc(100% - #{toRpx(120)});
  padding-bottom: toRpx(24);

  .scroll-view {
    height: 100%;
  }
}

.box-content {
  padding: 0 toRpx(48);
}

.total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: toRpx(24) toRpx(32) toRpx(24) 0;
  font-size: toRpx(28);
  border-bottom: toRpx(2) solid #f7f7f6;

  &-left {
    color: #333;
    font-weight: 500;
  }

  &-right {
    color: #f45001;
    font-weight: 500;
  }
}

.pay-tips {
  padding: toRpx(24) toRpx(24) toRpx(24) 0;
  font-size: toRpx(24);
  color: #999;
}

.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: toRpx(88) auto 0;
  width: toRpx(1130);
  height: toRpx(80);
  color: #fff;
  border-radius: toRpx(48);
  background: linear-gradient(0deg, #2c66f7 0%, #48a6ff 100%);
}

.customer-title {
  .customer-file {
    margin-left: toRpx(20);
    color: #347bff;
    font-size: toRpx(24);

    .sprite-icon {
      margin-right: toRpx(4);
      transform: translateY(toRpx(3));
    }
  }
}
</style>