merchantCheck.vue 63.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 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
<!-- 对账编辑 -->
<template>
  <d2-Container v-loading="pageOverlayLoading">
    <div class="merchant-check">
      <div class="headerCon">
        <div class="check-title">
          <div class="store">
            商户名称:{{ merchantRow.merchantName }}
          </div>
          <div class="scene">
            业务场景:{{ sceneLabel }}
          </div>
        </div>
      </div>

      <div class="check-tab">
        <!-- 下拉选择特殊品类:避免千级品类时 el-tabs 页签条 DOM 线性增长 -->
        <p class="edit-sub-title division-rules-toolbar">
          品类切换
          <span class="division-rules-toolbar__controls">
            <span class="select-wrapper">
              <el-select class="tab-select"
                         placeholder="请选择特殊品类"
                         popper-class="merchant-check-tab-select-dropdown"
                         :popper-append-to-body="false"
                         :value="editableTabsValue"
                         @change="handleDivisionTabChange">
                <el-option v-for="(item, idx) in editableTabs"
                           :key="item.name"
                           :label="item.title"
                           :value="item.name">
                  <div class="tab-select-options-wrapper">
                    <span v-if="item.validError == 'Y'"
                          class="el-icon-warning icons"
                          style="color: #EB4E4E;"
                          title="该项校验未通过">
                    </span>
                    <span class="label">{{ item.title }}</span>
                    <span v-if="idx != 0"
                          class="actions el-icon-close"
                          @click.stop="confirmRemove(item.name)" />
                  </div>
                </el-option>
              </el-select>
            </span>
            <span v-if="addVisible" class="actions-wrapper">
              <el-button icon="el-icon-plus"
                         size="small"
                         plain
                         @click="handleAppendDivisionTab">
                新增
              </el-button>
            </span>
          </span>
        </p>
        <div v-if="editableTabs.length" class="classificationCptContainer">
          <ClassificationCpt ref="classificationActive"
                             :page-context="classificationPageContext"
                             :pane-context="classificationPaneContext"
                             :selection-context="classificationSelectionContext"
                             @classification-change="handleClassificationChange" />
        </div>
      </div>
      <div class="check-btns">
        <el-button size="small"
                   type="primary"
                   @click="showsmCode">
          保存
        </el-button>
        <el-button size="small" @click="handleReset">
          取消
        </el-button>
      </div>
    </div>
    <VerificationCodeDialog v-if="verificationCodeVisible"
                            :effect-start-date="effectStartDate"
                            :visible.sync="verificationCodeVisible"
                            @handleConfirm="codeHandleConfirm" />
  </d2-Container>
</template>

<script>
// 具体商品/套餐分页列表:grounding 内 getAllGoodsListPage、merchantPackageGoodsInfoPage 已 skipGlobalLoading,避免整屏转圈
import {
	getAllGoodsListPage as getAllGoodsList,
	merchantPackageGoodsInfoPage,
} from "@api/grounding";
import {
	getEffectRuleApi,
	getQueryFeeCategoryByTypeApi,
	ruleAuditSituation,
	saveRuleApi,
} from "@api/merchant";
import { getBaseSceneCodeList } from "@api/productManage";
import { getGoodsCategoryConfiguration } from "@/api/sys.base.js";
import { sceneList } from "@/common/constants";
import { resolveBaseSceneCodeFromRouter } from "@/common/sceneBaseSceneCode";
/**
 * 商户对账编辑页(merchantCheck)
 *
 * 数据获取
 * - created:getRowItem(路由 params)+ 并行 getQueryFeeCategoryByType(三路费用类别,不 await)
 * - mounted:pageOverlayLoading 包住 Promise.allSettled(分类 + getEffectRule)+ ruleAuditSituation;整页 v-loading 不绑定 d2admin 全局,避免子组件远程商品请求整页转圈
 * - watch productType → initBaseData;仅当前 Tab 挂载 classificationCpt(ref classificationActive)
 *
 * 校验(保存)
 * - showsmCode → verifyFormData → getReconciliationGoodsTypeGroupRules:persist 后按 diff +(有基线槽位时 touched/sessionAdded)定待校验 Tab;
 *   先首遍仅缓存的 getReconciliationRuleValidationResult(无 merge/getEffectRule)首错即停,通过后再第二遍
 *   resolveReconciliationRulePayloadForTabValidation + getReconciliationRuleValidationResult;失败时 Toast + 当前 Tab classificationCpt.validateFormOnly 整表标红
 * - checkParamsType 通过后打开验证码弹窗;失败 focusTabByErrorIndex
 *
 * 提交
 * - codeHandleConfirm → submitFormData:若自打开验证码前无新的对账相关交互则跳过第二次 verify;saveRuleApi 传 goodsTypeGroupRules(增量,含 type=DELETE 的删除项)、
 *   smsCode/effectStartDate、formObj 四项费用字段、merchantId/sceneType(不再单独传 deletedGroupDivisionRuleIds)
 *
 * 后续优化要点(A 段):sceneLabel、productType 浅监听、allSettled、费用 Promise.all、getAllReconciliationParams、
 * persist 深拷贝、uniqueBy、errorIndex;子组件见 merchantStep/components/classificationCpt.vue(B 段)。
 *
 * @typedef {Object} MerchantCheckPageContext
 * @property {Array} queryFeeCategoryByTypeFlow
 * @property {Array} queryFeeCategoryByTypeServe
 * @property {Array} queryFeeCategoryByTypePlatform
 * @property {Array|Object} goodsTypeGroupReconciliationRules
 * @typedef {Object} MerchantCheckSelectionContext
 * @property {Array} goodsList
 * @property {Array} goodsSelectList
 * @property {Array} upgradeGoodsList
 * @property {Array} packageGoodsList
 * @property {Array} selectUpgradeGoodsList
 * @property {Array} selectPackageGoodsList
 * @typedef {Object} MerchantCheckPaneContext
 * @property {number} paneIndex
 * @property {number} tabindex
 * @property {Object} tabItem
 * @property {Object} classificationObjSelect
 * @property {Object} goodsTypeGroupReconciliationRule
 * @property {Object|null} phantomFullCategoryRule
 */
import { deepClone } from "@/common/util";
import verificationCodeDialog from "../financialRules/components/verificationCodeDialog";
import { CLASSIFICATION_EMIT } from "../financialRules/utils/classificationEmitTypes";
import {
	appendDeleteOpsToIncremental,
} from "../financialRules/utils/classificationRuleCache";
import { financialRulePayloadDeepEqual } from "../financialRules/utils/rulePayloadCanonicalCompare";
import { prepareRuleForValidation } from "../financialRules/utils/validateGoodsTypeGroupRulePayload";
import {
	getSceneDisplayNameFromList,
	normalizeBaseSceneListResponse,
	pickSceneLookupCode,
} from "../merchantGroundingEdit/utils/merchantDetailMap";
import classificationCpt from "./components/classificationCpt.vue";
import { uniqueBy } from "./utils/arrayUniqueBy";
import { getEffectivePhantomFullCategoryRuleRaw as resolveEffectivePhantomRaw } from "./utils/effectivePhantomReconciliationRule";
import {
	filterUpgradeGoodsByMerchantCode,
	getUpgradeGoodsRowKey,
	mapProductSearchListToUpgradeGoodsOptions,
	resolveProductSearchPages,
	sameUpgradeGoodsRow,
	uniquePackageByPackageCode,
	uniqueUpgradeGoodsById,
} from "./utils/groundingUpgradeList";
import { normalizeReconciliationRuleForCompare } from "./utils/normalizeReconciliationRuleForCompare";
import {
	buildReconciliationIncrementalRules,
	getStableReconciliationRuleId,
	mergeReconciliationRuleServerFields,
} from "./utils/reconciliationIncrementalRules";
import {
	getReconciliationRuleIndexForTab,
	hasPhantomFullCategoryRuleSlot,
} from "./utils/reconciliationRuleTabIndex";
import { applyGoodsTypeGroupRelationBranches } from "./utils/reconciliationRuleBranches";
import {
	fillDjGoodsTypeGroupRelations,
	fillGoodsTypesCategoryInfo,
	filterDivisionTabPanes,
	rebuildCrossTabReconciliationSelections,
} from "./utils/reconciliationShared";
import { shouldIncludeReconciliationTabForProcess } from "./utils/reconciliationSubmitTabGate";
import { parseRouteMerchantRow } from "./utils/routeMerchant";
import {
	getReconciliationRuleValidationResult,
	reconciliationRulePayloadIsSubstantive,
} from "./utils/validateReconciliationRulePayload";

/** 提交前与基线比对时剥离 buildReconciliationIncrementalRules 注入的 type / tabPaneIndex */
function stripReconciliationIncrementalMeta(rule) {
	if (!rule || typeof rule !== "object") {
		return { tabPaneIndex: undefined, payload: null };
	}
	const { type, tabPaneIndex, ...payload } = rule;
	return { tabPaneIndex, payload };
}

export default {
	name: "MerchantCheck",
	components: {
		ClassificationCpt: classificationCpt,
		VerificationCodeDialog: verificationCodeDialog,
	},
	provide() {
		return {
			financialRulesEnv: this.financialRulesEnv,
		};
	},
	data() {
		return {
			/** 本页专用全屏遮罩:不绑定 d2admin 全局 loading,避免「具体商品」远程下拉等请求整页转圈 */
			pageOverlayLoading: false,
			effectStartDateDate: "",
			effectStartDate: false, // 规则时间 true 表示可以立即生效 是否立即生效
			/** 业务场景展示:按 baseSceneCode + getBaseSceneCodeList */
			baseSceneList: [],
			sceneList,
			verificationCodeVisible: false,
			smsCode: "",
			/**
			 * 最近一次 verifyFormData 结果:增量 goodsTypeGroupRules + 全量合并视图(仅前端)。
			 * submitFormData 会在请求前经 shapeGoodsTypeGroupRulesForApi 写入此处,与实际上报一致。
			 */
			reconciliationLastVerifyResult: null,
			/** 本会话删除的已落库对账规则整行快照;提交前并入 goodsTypeGroupRules(type=DELETE),不向接口单独字段传(名历史遗留,兼容仅存 id) */
			pendingDeletedGroupDivisionRuleIds: [],
			editableTabsValue: "1",
			addIndex: 1,
			editableTabs: [
				{
					title: "全部品类",
					name: "1",
					classificationUserTouched: false,
					sessionAdded: false,
				},
			],
			/** 全量校验失败时,首个未通过 Tab 在 editableTabs 中的下标;已用于校验循环内定位,模板未展示时可做「切 Tab / 提示」扩展 */
			errorIndex: -1,
			goodsSelectList: [],
			goodsTypeGroupRelations: [],
			merchantRow: {}, // 当前选中的详情
			productType: [],
			goodsTypeGroupReconciliationRules: [],
			queryFeeCategoryByTypeFlow: [],
			queryFeeCategoryByTypeServe: [],
			queryFeeCategoryByTypePlatform: [],
			formObj: {},
			currentPage: 1,
			pageSize: 20,
			selectUpgradeGoodsList: [],
			upgradeGoodsList: [],
			selectPackageGoodsList: [],
			packageGoodsList: [],
			goodsNameKeyword: "",
			allPages: 1,
			/** 占位「全部品类」tab0:无 rules[0] 行时的表单快照,供回填与防 watch 刷空(不写进 goodsTypeGroupReconciliationRules[0]) */
			phantomFullCategoryRule: null,
			/**
			 * getEffectRule 成功后的规则快照,用于与当前缓存比对「是否有改动」。
			 */
			reconciliationRulesBaseline: null,
			/**
			 * 用户对对账相关 UI 的交互世代号;与 reconciliationSmsVerifyEpoch 一致时才允许短信提交短路第二次 verify。
			 */
			reconciliationInteractionEpoch: 0,
			reconciliationSmsVerifyEpoch: -1,
			/** provide/inject:子组件读取 routerInfo、scene(与 computed routerInfo 同步) */
			financialRulesEnv: {
				routerInfo: {},
				scene: undefined,
			},
		};
	},
	computed: {
		routerInfo() {
			return parseRouteMerchantRow(this.$route.query?.params);
		},
		addVisible() {
			// 已选中的小于全部商品即可追加
			const length1 = this.goodsTypeGroupRelations.length;
			const length2 = this.editableTabs.length - 1;
			const length3 = this.goodsSelectList.length;
			return length1 - length3 > 0 && length1 > length2;
		},
		activeDivisionTabIndex() {
			const i = this.editableTabs.findIndex(
				t => String(t.name) === String(this.editableTabsValue),
			);
			return i === -1 ? 0 : i;
		},
		/** A1:避免模板每次渲染调用方法;按 baseSceneCode 与场景列表回显,缺失时兜底 scene 枚举 */
		sceneLabel() {
			const name = this.merchantRow?.baseSceneName;
			if (name != null && String(name).trim() !== "") {
				return String(name).trim();
			}
			let code = pickSceneLookupCode(this.merchantRow);
			if (code === "") {
				const sc = this.merchantRow?.scene;
				if (sc != null && sc !== "") {
					code = String(resolveBaseSceneCodeFromRouter(this.merchantRow));
				}
			}
			if (code !== "") {
				const fromList = getSceneDisplayNameFromList(code, this.baseSceneList);
				if (fromList !== "") {
					return fromList;
				}
			}
			const key = this.merchantRow?.scene;
			if (key == null || key === "") {
				return "-";
			}
			const label = this.sceneList[key];
			return label != null && label !== "" ? label : "-";
		},
		/** @returns {MerchantCheckPageContext} */
		classificationPageContext() {
			return {
				queryFeeCategoryByTypeFlow: this.queryFeeCategoryByTypeFlow,
				queryFeeCategoryByTypeServe: this.queryFeeCategoryByTypeServe,
				queryFeeCategoryByTypePlatform: this.queryFeeCategoryByTypePlatform,
				goodsTypeGroupReconciliationRules: this.goodsTypeGroupReconciliationRules,
			};
		},
		classificationSelectionContext() {
			return {
				goodsList: this.goodsTypeGroupRelations,
				goodsSelectList: this.goodsSelectList,
				upgradeGoodsList: this.upgradeGoodsList,
				packageGoodsList: this.packageGoodsList,
				selectUpgradeGoodsList: this.selectUpgradeGoodsList,
				selectPackageGoodsList: this.selectPackageGoodsList,
			};
		},
		classificationPaneContext() {
			const idx = this.activeDivisionTabIndex;
			return {
				paneIndex: idx,
				tabindex: idx,
				tabItem: this.editableTabs[idx] || {},
				classificationObjSelect: {},
				goodsTypeGroupReconciliationRule:
          this.resolveReconciliationRuleForPaneIndex(idx),
				phantomFullCategoryRule:
          idx === 0 && this.hasPhantomFullCategoryTab()
          	? this.getEffectivePhantomFullCategoryRuleRaw()
          	: null,
			};
		},
	},
	watch: {
		routerInfo: {
			immediate: true,
			handler(v) {
				this.financialRulesEnv.routerInfo = v && typeof v === "object" ? v : {};
				const sc = v && v.scene;
				this.financialRulesEnv.scene = sc != null && sc !== "" ? sc : undefined;
			},
		},
		// A2:productType 仅整表替换(见 fetchGoodsCategoryConfiguration),无需 deep,减少 initBaseData / deepClone
		productType: {
			handler() {
				this.initBaseData();
			},
			immediate: true,
			deep: false,
		},
	},
	created() {
		this.getRowItem();
		void this.fetchBaseSceneListForLabel();
		// A4:异步方法,不 await,与 mounted 数据加载并行;内部已 try/catch 三路费用接口
		void this.getQueryFeeCategoryByType();
	},
	async mounted() {
		this.pageOverlayLoading = true;
		try {
			this.fetchReconciliationRuleAuditSituation();
			/**
			 * A3 策略:分类与对账规则并行加载;互不拖死。
			 * - 分类失败:提示,规则仍可能成功。
			 * - 规则失败:保留已加载分类,降级拉空升级品/套餐列表(与 getEffectRule 无数据分支一致),避免白屏。
			 */
			const [catResult, ruleResult] = await Promise.allSettled([
				this.fetchGoodsCategoryConfiguration(),
				this.getEffectRule(),
			]);
			if (catResult.status === "rejected") {
				console.warn("[MerchantCheck] fetchGoodsCategoryConfiguration", catResult.reason);
				this.$message.warning("商品分类配置加载失败,请刷新页面重试");
			}
			if (ruleResult.status === "rejected") {
				console.warn("[MerchantCheck] getEffectRule", ruleResult.reason);
				this.$message.warning("对账规则加载失败,请检查网络后重试");
				this.getSelectingList();
				this.getSelectingListPackage();
			}
		} finally {
			this.pageOverlayLoading = false;
		}
	},
	beforeDestroy() {
		// 删除子组件保留的数据
		localStorage.removeItem("getListPartnerMerchant");
		localStorage.removeItem("getMerchantLevelList");
	},
	methods: {
		async fetchBaseSceneListForLabel() {
			try {
				const res = await getBaseSceneCodeList({});
				this.baseSceneList = normalizeBaseSceneListResponse(res);
			} catch (e) {
				console.warn("[MerchantCheck] fetchBaseSceneListForLabel", e);
				this.baseSceneList = [];
			}
		},
		/**
		 * 安全获取 classificationCpt 子组件实例(单实例 ref="classificationActive")。
		 * 非当前激活 tab 无挂载实例,返回 undefined(与原先虚拟 Tab 语义一致)。
		 */
		getClassificationRef(name) {
			if (name == null || name === "") {
				return undefined;
			}
			if (String(name) !== String(this.editableTabsValue)) {
				return undefined;
			}
			const ref = this.$refs.classificationActive;
			return Array.isArray(ref) ? ref[0] : ref;
		},
		/** 子组件 classificationObj 非 init 回填变更时上报(与 financialRules onClassificationTouched 一致)。 */
		onClassificationTouched(tabIndex) {
			const idx = Number(tabIndex);
			if (!Number.isFinite(idx) || idx < 0 || idx >= this.editableTabs.length) {
				return;
			}
			const tab = this.editableTabs[idx];
			if (!tab || String(tab.name) === "add") {
				return;
			}
			this.$set(tab, "classificationUserTouched", true);
		},
		/**
		 * 下拉切换品类:受控 el-select,先持久化旧 tab 再更新 editableTabsValue(对齐原 beforeLeave)。
		 */
		async handleDivisionTabChange(newName) {
			const oldName = this.editableTabsValue;
			if (String(newName) === String(oldName)) {
				return;
			}
			await this.$nextTick();
			await this.$nextTick();
			this.persistClassificationTabByPaneName(oldName);
			this.rebuildCrossTabGoodsSelectionsFromRules();
			this.editableTabsValue = newName;
			this.bumpReconciliationInteractionEpoch();
		},
		/**
		 * 新增特殊品类 tab:对齐原「+」页签逻辑,先持久化当前 tab 再 addTab。
		 */
		handleAppendDivisionTab() {
			const oldName = this.editableTabsValue;
			if (oldName != null && oldName !== "") {
				this.$nextTick()
					.then(() => this.$nextTick())
					.then(() => {
						this.persistClassificationTabByPaneName(oldName);
						this.rebuildCrossTabGoodsSelectionsFromRules();
						this.bumpReconciliationInteractionEpoch();
						this.addTab();
					});
			} else {
				this.bumpReconciliationInteractionEpoch();
				this.addTab();
			}
		},
		/**
		 * Tab 下标 → goodsTypeGroupReconciliationRules 下标。
		 * 首条规则为特殊品类时 tab0「全部品类」仅占位,无对应规则行,返回 null(不可按 tab 下标写 rules[0])。
		 */
		reconciliationRuleIndexForTabIndex(tabIndex) {
			return getReconciliationRuleIndexForTab(
				this.goodsTypeGroupReconciliationRules,
				tabIndex,
				this.getEffectivePhantomFullCategoryRuleRaw(),
			);
		},
		/**
		 * live phantom 在 getEffectRule 末尾会清空;与基线比对、resolve、子组件 props 需回落 baseline.phantomFullCategoryRule。
		 */
		getEffectivePhantomFullCategoryRuleRaw() {
			const b = this.reconciliationRulesBaseline;
			return resolveEffectivePhantomRaw(
				this.phantomFullCategoryRule,
				b && b.phantomFullCategoryRule,
			);
		},
		/**
		 * 当前 Tab 槽位对应的一条对账规则(与财务 goodsTypeGroupRules[i] 同构)。
		 * tab0 占位用 phantomFullCategoryRule,否则取 goodsTypeGroupReconciliationRules[ruleIdx],缺省 {}。
		 */
		resolveReconciliationRuleForPaneIndex(idx) {
			const ruleIdx = this.reconciliationRuleIndexForTabIndex(idx);
			if (ruleIdx == null && idx === 0 && this.hasPhantomFullCategoryTab()) {
				const p = this.getEffectivePhantomFullCategoryRuleRaw();
				return p && typeof p === "object" ? p : {};
			}
			if (ruleIdx != null && Array.isArray(this.goodsTypeGroupReconciliationRules)) {
				const r = this.goodsTypeGroupReconciliationRules[ruleIdx];
				return r && typeof r === "object" ? r : {};
			}
			return {};
		},
		/**
		 * tab0「全部品类」仅占位:首条接口规则为特殊品类时,tab0 无 goodsTypeGroupReconciliationRules 行。
		 */
		hasPhantomFullCategoryTab() {
			return hasPhantomFullCategoryRuleSlot(
				this.goodsTypeGroupReconciliationRules,
				this.getEffectivePhantomFullCategoryRuleRaw(),
			);
		},
		/**
		 * 基线中与 Tab ti 对应的原始规则行(tab0 phantom 用 baseline.phantomFullCategoryRule,否则 rules[ruleIdx])。
		 */
		getReconciliationBaselineRawForTabIndex(ti) {
			const b = this.reconciliationRulesBaseline;
			if (!b) {
				return null;
			}
			const ruleIdx = this.reconciliationRuleIndexForTabIndex(ti);
			if (ruleIdx == null && ti === 0 && this.hasPhantomFullCategoryTab()) {
				return b.phantomFullCategoryRule;
			}
			if (ruleIdx != null && Array.isArray(b.goodsTypeGroupReconciliationRules)) {
				return b.goodsTypeGroupReconciliationRules[ruleIdx];
			}
			return null;
		},
		bumpReconciliationInteractionEpoch() {
			this.reconciliationInteractionEpoch++;
		},
		/**
		 * 与 getReconciliationGoodsTypeGroupRules 内「从缓存拼规则」一致,供基线比对复用。
		 */
		buildRuleFromCacheForTabIndex(ti) {
			const ruleIdx = this.reconciliationRuleIndexForTabIndex(ti);
			let raw = null;
			if (ruleIdx == null && ti === 0 && this.hasPhantomFullCategoryTab()) {
				raw = this.getEffectivePhantomFullCategoryRuleRaw();
			} else if (ruleIdx != null) {
				raw = this.goodsTypeGroupReconciliationRules[ruleIdx];
			}
			if (!raw || typeof raw !== "object") {
				return null;
			}
			const o = deepClone(raw);
			fillDjGoodsTypeGroupRelations(o);
			return o;
		},
		/**
		 * 与 financialRules buildMergedClassificationPayloadAtIndex 对位:仅当该 Tab 的 classificationCpt 已挂载时,
		 * await getEffectRule 后再 getBackendFormat,并与对账缓存行浅合并为 next;无 ref 返回 null(校验退回 resolve 内纯缓存)。
		 */
		async buildMergedReconciliationPayloadAtTabIndex(idx) {
			if (idx == null || idx < 0 || idx >= this.editableTabs.length) {
				return null;
			}
			const tabPane = this.editableTabs[idx];
			if (!tabPane) {
				return null;
			}
			const node = this.getClassificationRef(tabPane.name);
			if (
				!node
				|| typeof node.getBackendFormat !== "function"
				|| typeof node.getEffectRule !== "function"
			) {
				return null;
			}
			const ruleIdx = this.reconciliationRuleIndexForTabIndex(idx);
			let prevStored;
			if (ruleIdx == null) {
				if (idx === 0 && this.hasPhantomFullCategoryTab()) {
					const eff = this.getEffectivePhantomFullCategoryRuleRaw();
					prevStored = eff && typeof eff === "object" ? eff : {};
				} else {
					return null;
				}
			} else {
				prevStored = this.goodsTypeGroupReconciliationRules[ruleIdx] || {};
			}
			try {
				await node.getEffectRule();
				await this.$nextTick();
				const raw = node.getBackendFormat();
				return { next: deepClone({ ...prevStored, ...raw }), prevStored };
			} catch (e) {
				console.warn("buildMergedReconciliationPayloadAtTabIndex", e);
				return null;
			}
		},
		/**
		 * 纯数据校验用 payload:与 financial resolveRulePayloadForTabValidation 对位。
		 * 合并结果与缓存经归一化后一致时用缓存;无 ref 时仅用缓存(依赖 persist / 切 Tab 时已写入 goodsTypeGroupReconciliationRules)。
		 */
		async resolveReconciliationRulePayloadForTabValidation(tabindex) {
			const ruleIdx = this.reconciliationRuleIndexForTabIndex(tabindex);
			let cachedRaw = {};
			if (ruleIdx == null && tabindex === 0 && this.hasPhantomFullCategoryTab()) {
				const eff = this.getEffectivePhantomFullCategoryRuleRaw();
				cachedRaw = eff && typeof eff === "object" ? eff : {};
			} else if (ruleIdx != null) {
				cachedRaw = this.goodsTypeGroupReconciliationRules[ruleIdx] || {};
			}

			const filledFromCache = () =>
				fillDjGoodsTypeGroupRelations(deepClone(cachedRaw));

			const built = await this.buildMergedReconciliationPayloadAtTabIndex(tabindex);
			if (!built) {
				return filledFromCache();
			}
			const { next, prevStored } = built;
			if (prevStored == null || typeof prevStored !== "object") {
				return fillDjGoodsTypeGroupRelations(deepClone(next));
			}
			const nextNorm = normalizeReconciliationRuleForCompare(
				fillDjGoodsTypeGroupRelations(deepClone(next)),
			);
			const prevNorm = normalizeReconciliationRuleForCompare(
				fillDjGoodsTypeGroupRelations(deepClone(prevStored)),
			);
			if (financialRulePayloadDeepEqual(nextNorm, prevNorm)) {
				return filledFromCache();
			}
			return fillDjGoodsTypeGroupRelations(deepClone(next));
		},
		/** 当前 Tab 槽位规则是否与进入页时的基线一致(fillDj 后深度比较) */
		reconciliationTabDiffersFromBaseline(ti) {
			if (!this.reconciliationRulesBaseline) {
				return false;
			}
			const prevRaw = this.getReconciliationBaselineRawForTabIndex(ti);
			const cur = this.buildRuleFromCacheForTabIndex(ti);
			if (!prevRaw) {
				if (!cur) {
					return false;
				}
				return reconciliationRulePayloadIsSubstantive(cur);
			}
			const prevNorm = normalizeReconciliationRuleForCompare(
				fillDjGoodsTypeGroupRelations(deepClone(prevRaw)),
			);
			const curNorm = cur
				? normalizeReconciliationRuleForCompare(cur)
				: null;
			if (!curNorm && !prevNorm) {
				return false;
			}
			if (!curNorm || !prevNorm) {
				return true;
			}
			return !financialRulePayloadDeepEqual(curNorm, prevNorm);
		},
		/**
		 * 基线中是否存在与当前 Tab 可成对比对的行(含 tab0 phantom);与 reconciliationTabDiffersFromBaseline 的 prevRaw 解析一致。
		 */
		reconciliationBaselineHasSlotForTabIndex(ti) {
			const prevRaw = this.getReconciliationBaselineRawForTabIndex(ti);
			return !!(prevRaw && typeof prevRaw === "object");
		},
		/**
		 * 校验通过后的单条规则快照是否与进入页基线一致(用于收缩 goodsTypeGroupRules 增量)。
		 */
		reconciliationSnapshotEqualsBaseline(ti, snapshot) {
			if (!this.reconciliationRulesBaseline || !snapshot || typeof snapshot !== "object") {
				return false;
			}
			const prevRaw = this.getReconciliationBaselineRawForTabIndex(ti);
			if (!prevRaw) {
				if (!reconciliationRulePayloadIsSubstantive(snapshot)) {
					return true;
				}
				return false;
			}
			const curNorm = normalizeReconciliationRuleForCompare(
				fillDjGoodsTypeGroupRelations(deepClone(snapshot)),
			);
			const prevNorm = normalizeReconciliationRuleForCompare(
				fillDjGoodsTypeGroupRelations(deepClone(prevRaw)),
			);
			if (!curNorm && !prevNorm) {
				return true;
			}
			if (!curNorm || !prevNorm) {
				return false;
			}
			return financialRulePayloadDeepEqual(curNorm, prevNorm);
		},
		/**
		 * 校验通过的 Tab 中下,仅「快照与基线仍不一致」的进入提交(无基线时仅 sessionAdded)。
		 */
		filterIndicesToSubmitIncremental(dirtyIndices, validatedByTabIndex) {
			return dirtyIndices.filter((ti) => {
				const rule = validatedByTabIndex[ti];
				if (!rule || typeof rule !== "object") {
					return false;
				}
				if (!this.reconciliationRulesBaseline) {
					return this.editableTabs[ti]?.sessionAdded === true
						&& reconciliationRulePayloadIsSubstantive(rule);
				}
				return !this.reconciliationSnapshotEqualsBaseline(ti, rule);
			});
		},
		/**
		 * 序列化前再压一遍归一化(去掉 merchant / 空 children / 空数组键等)。
		 * forCompare: false 保留 expenseCategoryRules 的表单顺序,排序仅用于基线 deepEqual。
		 */
		shapeGoodsTypeGroupRulesForApi(rules) {
			if (!Array.isArray(rules) || !rules.length) {
				return [];
			}
			return rules.map((rule) => {
				const type = rule.type;
				const tabPaneIndex = rule.tabPaneIndex;
				const { payload } = stripReconciliationIncrementalMeta(rule);
				const body = normalizeReconciliationRuleForCompare(
					payload && typeof payload === "object" ? payload : {},
					{ forCompare: false },
				);
				return { ...body, type, tabPaneIndex };
			});
		},
		persistClassificationTabByPaneName(paneName) {
			if (paneName == null || paneName === "" || paneName === "add") {
				return;
			}
			const idx = this.editableTabs.findIndex(
				t => String(t.name) === String(paneName),
			);
			if (idx < 0) {
				return;
			}
			const ruleIdx = this.reconciliationRuleIndexForTabIndex(idx);
			if (ruleIdx == null) {
				if (idx === 0) {
					const node0 = this.getClassificationRef(this.editableTabs[idx].name);
					if (node0 && typeof node0.getBackendFormat === "function") {
						try {
							this.phantomFullCategoryRule = deepClone(node0.getBackendFormat());
						} catch (e) {
							console.warn("persistClassificationTabByPaneName phantom tab0", e);
						}
					}
				}
				return;
			}
			const node = this.getClassificationRef(this.editableTabs[idx].name);
			if (!node || typeof node.getBackendFormat !== "function") {
				return;
			}
			try {
				/**
				 * A6:对「prev 与接口快照」先浅合并再 deepClone 一次,避免对 prev、payload 各做一次深拷贝。
				 * 仍需整树深拷贝:子组件 getBackendFormat 与 classificationObj 共享嵌套引用,不切断会触发
				 * goodsTypeGroupReconciliationRules 深度 watch 死循环(见原注释)。
				 */
				const prev = this.goodsTypeGroupReconciliationRules[ruleIdx] || {};
				const raw = node.getBackendFormat();
				this.$set(
					this.goodsTypeGroupReconciliationRules,
					ruleIdx,
					deepClone({ ...prev, ...raw }),
				);
			} catch (e) {
				console.warn("persistClassificationTabByPaneName", e);
			}
		},
		persistActiveClassificationTab() {
			this.persistClassificationTabByPaneName(this.editableTabsValue);
		},
		/**
		 * 虚拟 Tab 下仅当前页挂载 classificationCpt,其它页的勾选不会触发 assign* emit,
		 * goodsSelectList 等与跨 Tab 禁用不同步。从 goodsTypeGroupReconciliationRules 聚合已选品类/商品/套餐
		 * (对账侧品类存在 goodsTypeGroupRelations,须按 categoryType 取值,避免与 upgradeGoods 重复计数)。
		 * 占位「全部品类」无 rules 行时,另合并 phantomFullCategoryRule(父级回传快照)。
		 */
		rebuildCrossTabGoodsSelectionsFromRules() {
			const sel = rebuildCrossTabReconciliationSelections(
				this.goodsTypeGroupReconciliationRules,
				{
					includePhantom: this.hasPhantomFullCategoryTab(),
					phantomRule: this.getEffectivePhantomFullCategoryRuleRaw(),
				},
			);
			this.goodsSelectList = sel.goodsSelectList;
			this.selectUpgradeGoodsList = sel.selectUpgradeGoodsList;
			this.selectPackageGoodsList = sel.selectPackageGoodsList;
		},
		/**
		 * 收集所有 Tab 的原始参数(不做 handleConfirm),删除 Tab 等与财务 getAllParams 对齐。
		 */
		getAllReconciliationParams() {
			// A5:仅按 Tab 元数据遍历 name,无需 deepClone 整块 editableTabs
			const list = this.editableTabs;
			const rows = [];
			for (let tabindex = 0; tabindex < list.length; tabindex++) {
				const node = this.getClassificationRef(list[tabindex].name);
				const ruleIdx = this.reconciliationRuleIndexForTabIndex(tabindex);
				if (node && typeof node.getBackendFormat === "function") {
					try {
						rows.push(deepClone(node.getBackendFormat()));
					} catch (e) {
						const cached
							= ruleIdx == null
								? (tabindex === 0 ? this.getEffectivePhantomFullCategoryRuleRaw() : null)
								: this.goodsTypeGroupReconciliationRules[ruleIdx];
						rows.push(cached ? deepClone(cached) : {});
					}
				} else {
					const cached
						= ruleIdx == null
							? (tabindex === 0 ? this.getEffectivePhantomFullCategoryRuleRaw() : null)
							: this.goodsTypeGroupReconciliationRules[ruleIdx];
					rows.push(cached ? deepClone(cached) : {});
				}
			}
			return rows;
		},
		/**
		 * 对账数据校验未通过:切 Tab、标红;不单独 Toast vr.message,避免与上层「请完善对账规则」叠两条提示。
		 */
		async applyReconciliationDataValidationFailure(pane, tabindex, tab, vr) {
			this.errorIndex = tabindex;
			if (tab) {
				tab.validError = "Y";
			}
			this.editableTabsValue = pane.name;
			await this.$nextTick();
			await this.$nextTick();
			const nodeMounted = this.getClassificationRef(pane.name);
			if (!nodeMounted) {
				return;
			}
			await this.$nextTick();
			if (typeof nodeMounted.validateFormOnly === "function") {
				await nodeMounted.validateFormOnly();
			}
		},
		/**
		 * 对账规则校验与组装:对每个 eligible Tab(含接口回填且本会话未改动的行)做两遍数据校验;persist 后用于增量的
		 * indicesToProcess 逻辑不变,仍由 diff + shouldIncludeReconciliationTabForProcess 门控,filterIndicesToSubmitIncremental
		 * 与基线比对组包。
		 * 首遍仅 buildRuleFromCacheForTabIndex + getReconciliationRuleValidationResult;
		 * 全过后第二遍 resolveReconciliationRulePayloadForTabValidation + 校验并组快照。失败时切 Tab + 子组件 validateFormOnly 整表标红。
		 *
		 * @returns {Promise<{ ok: boolean, incrementalRules: Array, fullMergedRules: Array|null, firstErrorTabIndex?: number }>}
		 */
		async getReconciliationGoodsTypeGroupRules(list) {
			const panes = filterDivisionTabPanes(list);
			const eligiblePanes = panes.filter((pane) => {
				const ti = this.editableTabs.findIndex(
					t => String(t.name) === String(pane.name),
				);
				if (ti === 0) {
					return true;
				}
				return this.reconciliationRuleIndexForTabIndex(ti) != null;
			});
			const prevTabName = this.editableTabsValue;

			const getTabIndexForPane = pane =>
				this.editableTabs.findIndex(
					t => String(t.name) === String(pane.name),
				);

			this.persistActiveClassificationTab();
			await this.$nextTick();

			const mergeFullRules = (validatedByTabIndex) => {
				return eligiblePanes.map((pane) => {
					const ti = getTabIndexForPane(pane);
					if (ti < 0) {
						return false;
					}
					const snap = validatedByTabIndex[ti];
					if (snap != null) {
						return snap;
					}
					const fromCache = this.buildRuleFromCacheForTabIndex(ti);
					return fromCache || false;
				});
			};

			let indicesToProcess = [];
			const tabCount = this.editableTabs.length;
			for (let i = 0; i < tabCount; i++) {
				const tab = this.editableTabs[i];
				if (!tab || String(tab.name) === "add") {
					continue;
				}
				const differs = this.reconciliationTabDiffersFromBaseline(i);
				const isSessionAdded = tab.sessionAdded === true;
				if (!differs && !isSessionAdded) {
					continue;
				}
				if (differs) {
					if (
						!shouldIncludeReconciliationTabForProcess({
							hasBaselineSlot: this.reconciliationBaselineHasSlotForTabIndex(i),
							classificationUserTouched: tab.classificationUserTouched === true,
							sessionAdded: isSessionAdded,
						})
					) {
						continue;
					}
				}
				indicesToProcess.push(i);
			}
			indicesToProcess = [...new Set(indicesToProcess)];
			const ai = this.activeDivisionTabIndex;
			if (indicesToProcess.length > 1 && ai >= 0 && indicesToProcess.includes(ai)) {
				indicesToProcess = [
					ai,
					...indicesToProcess.filter(x => x !== ai).sort((a, b) => a - b),
				];
			} else {
				indicesToProcess.sort((a, b) => a - b);
			}

			let allEligibleTabIndices = eligiblePanes
				.map(p => getTabIndexForPane(p))
				.filter(ti => ti >= 0);
			allEligibleTabIndices = [...new Set(allEligibleTabIndices)];
			const actForSort = this.activeDivisionTabIndex;
			if (allEligibleTabIndices.length > 1 && actForSort >= 0 && allEligibleTabIndices.includes(actForSort)) {
				allEligibleTabIndices = [
					actForSort,
					...allEligibleTabIndices.filter(x => x !== actForSort).sort((a, b) => a - b),
				];
			} else {
				allEligibleTabIndices.sort((a, b) => a - b);
			}

			const validatedByTabIndex = {};
			let failedTabIndex = -1;

			for (let v = 0; v < allEligibleTabIndices.length; v++) {
				const tabindex = allEligibleTabIndices[v];
				const pane = eligiblePanes.find(p => getTabIndexForPane(p) === tabindex);
				if (!pane) {
					continue;
				}
				const tab = this.editableTabs[tabindex];
				const fromCache = this.buildRuleFromCacheForTabIndex(tabindex);
				const cacheVr = getReconciliationRuleValidationResult(fromCache || {});
				if (!cacheVr.ok) {
					failedTabIndex = tabindex;
					await this.applyReconciliationDataValidationFailure(
						pane,
						tabindex,
						tab,
						cacheVr,
					);
					break;
				}
			}

			for (let v = 0; v < allEligibleTabIndices.length && failedTabIndex < 0; v++) {
				const tabindex = allEligibleTabIndices[v];
				const pane = eligiblePanes.find(p => getTabIndexForPane(p) === tabindex);
				if (!pane) {
					continue;
				}
				const tab = this.editableTabs[tabindex];

				const rulePayload
					= await this.resolveReconciliationRulePayloadForTabValidation(tabindex);

				const payloadVr = getReconciliationRuleValidationResult(rulePayload);
				if (!payloadVr.ok) {
					failedTabIndex = tabindex;
					await this.applyReconciliationDataValidationFailure(
						pane,
						tabindex,
						tab,
						payloadVr,
					);
					break;
				}

				if (tab) {
					tab.validError = "N";
				}
				let snap = prepareRuleForValidation(rulePayload);
				const cachedForId = this.buildRuleFromCacheForTabIndex(tabindex);
				snap = mergeReconciliationRuleServerFields(snap, cachedForId);
				validatedByTabIndex[tabindex] = snap;
			}

			if (failedTabIndex >= 0) {
				this.errorIndex = failedTabIndex;
				const failEligibleIdx = eligiblePanes.findIndex(
					p => getTabIndexForPane(p) === failedTabIndex,
				);
				const out = [];
				for (let i = 0; i < eligiblePanes.length; i++) {
					const ti = getTabIndexForPane(eligiblePanes[i]);
					if (failEligibleIdx < 0) {
						out.push(false);
						continue;
					}
					if (i < failEligibleIdx) {
						if (validatedByTabIndex[ti] != null) {
							out.push(validatedByTabIndex[ti]);
						} else {
							const c = this.buildRuleFromCacheForTabIndex(ti);
							out.push(c || false);
						}
					} else if (i === failEligibleIdx) {
						out.push(false);
					} else {
						out.push(false);
					}
				}
				this.rebuildCrossTabGoodsSelectionsFromRules();
				return {
					ok: false,
					incrementalRules: [],
					fullMergedRules: out,
					firstErrorTabIndex: failedTabIndex,
				};
			}

			const fullMergedRules = mergeFullRules(validatedByTabIndex);
			const allPassed
				= fullMergedRules.length > 0
					&& fullMergedRules.every(item => item);
			const indicesToSubmit = allPassed
				? this.filterIndicesToSubmitIncremental(
						indicesToProcess,
						validatedByTabIndex,
					)
				: [];
			const incrementalRules = allPassed && indicesToSubmit.length
				? buildReconciliationIncrementalRules(
						validatedByTabIndex,
						indicesToSubmit,
					)
				: [];
			if (allPassed) {
				if (this.hasPhantomFullCategoryTab()) {
					fullMergedRules.slice(1).forEach((rule, i) => {
						if (rule && typeof rule === "object") {
							this.$set(
								this.goodsTypeGroupReconciliationRules,
								i,
								deepClone(rule),
							);
						}
					});
					const fullSnap = fullMergedRules[0];
					if (fullSnap && typeof fullSnap === "object") {
						this.phantomFullCategoryRule = deepClone(fullSnap);
					}
				} else {
					fullMergedRules.forEach((rule, i) => {
						if (rule && typeof rule === "object") {
							this.$set(
								this.goodsTypeGroupReconciliationRules,
								i,
								deepClone(rule),
							);
						}
					});
				}
			}
			if (
				allPassed
				&& prevTabName != null
				&& String(prevTabName) !== "add"
			) {
				this.editableTabsValue = prevTabName;
				await this.$nextTick();
			}

			this.rebuildCrossTabGoodsSelectionsFromRules();
			let firstErrorTabIndex;
			if (!allPassed) {
				const failI = fullMergedRules.findIndex(item => !item);
				if (failI >= 0 && eligiblePanes[failI]) {
					firstErrorTabIndex = getTabIndexForPane(eligiblePanes[failI]);
					if (firstErrorTabIndex >= 0) {
						this.errorIndex = firstErrorTabIndex;
					}
				}
			}
			return {
				ok: allPassed,
				incrementalRules,
				fullMergedRules,
				firstErrorTabIndex,
			};
		},
		/** 拉取对账规则生效态:是否可立即生效(effectStartDate),内部 ruleAuditSituation */
		fetchReconciliationRuleAuditSituation() {
			const { merchantId, scene: sceneType } = this.routerInfo;
			ruleAuditSituation({
				merchantId,
				sceneType,
				baseSceneCode: resolveBaseSceneCodeFromRouter(this.routerInfo),
				ruleType: 3,
			})
				.then((res) => {
					this.effectStartDate = !res.inEffectReconciliationRule;
				})
				.catch(() => { });
		},
		/** A4:三路费用类别一次聚合 + 统一 catch,避免部分成功导致三方下拉数据不一致 */
		async getQueryFeeCategoryByType() {
			const scene = this.merchantRow.scene;
			const pageSize = 10000;
			const base = {
				feeCategoryType: 2,
				applicationSceneType: scene,
				pageSize,
				baseSceneCodeList: [resolveBaseSceneCodeFromRouter(this.routerInfo)],
			};
			const emptyThree = () => {
				this.queryFeeCategoryByTypeFlow = [];
				this.queryFeeCategoryByTypeServe = [];
				this.queryFeeCategoryByTypePlatform = [];
			};
			try {
				const [flowRes, serveRes, platformRes] = await Promise.all([
					getQueryFeeCategoryByTypeApi({
						...base,
						applicationObjectType: 1,
					}),
					getQueryFeeCategoryByTypeApi({
						...base,
						applicationObjectType: 2,
						orderBy: 2,
					}),
					getQueryFeeCategoryByTypeApi({
						...base,
						applicationObjectType: 3,
					}),
				]);
				this.queryFeeCategoryByTypeFlow = flowRes?.list || [];
				this.queryFeeCategoryByTypeServe = serveRes?.list || [];
				this.queryFeeCategoryByTypePlatform = platformRes?.list || [];
			} catch (e) {
				console.warn("[MerchantCheck] getQueryFeeCategoryByType", e);
				emptyThree();
				this.$message.warning("费用类别加载失败,请刷新页面重试");
			}
		},
		async fetchGoodsCategoryConfiguration() {
			const result = await getGoodsCategoryConfiguration({});
			const { list } = result || {};
			if (list && list.length) {
				this.productType = deepClone(list);
			} else {
				this.productType = [];
			}
		},
		initBaseData() {
			this.goodsTypeGroupRelations = deepClone(this.productType);
		},
		handleClassificationChange({ type, payload }) {
			this.bumpReconciliationInteractionEpoch();
			switch (type) {
				case CLASSIFICATION_EMIT.ASSIGN_GOODS_TYPE_LIST:
					this.assignGoodsTypeList(payload);
					break;
				case CLASSIFICATION_EMIT.DELETE_GOODS_TYPE_ITEM:
					this.deleteGoodsTypeItem(payload);
					break;
				case CLASSIFICATION_EMIT.ASSIGN_UPGRADE_GOODS_LIST:
					this.assignUpgradeGoodsList(payload);
					break;
				case CLASSIFICATION_EMIT.DELETE_UPGRADE_GOODS_ITEM:
					this.deleteUpgradeGoodsItem(payload);
					break;
				case CLASSIFICATION_EMIT.ASSIGN_PACKAGE_GOODS_LIST:
					this.assignPackageGoodsList(payload);
					break;
				case CLASSIFICATION_EMIT.DELETE_PACKAGE_GOODS_ITEM:
					this.deletePackageGoodsItem(payload);
					break;
				case CLASSIFICATION_EMIT.DELETE_SELECT_GOODS_TYPE_LIST:
					this.deleteSelectGoodsTypeList(payload);
					break;
				case CLASSIFICATION_EMIT.DELETE_SELECT_UPGRADE_GOODS_LIST:
					this.deleteSelectUpgradeGoodsList(payload);
					break;
				case CLASSIFICATION_EMIT.DELETE_SELECT_PACKAGE_GOODS_LIST:
					this.deleteSelectPackageGoodsList(payload);
					break;
				case CLASSIFICATION_EMIT.SYNC_CATEGORY_TYPE:
					this.syncCategoryType(payload);
					break;
				case CLASSIFICATION_EMIT.CLASSIFICATION_TOUCHED:
					this.onClassificationTouched(payload);
					break;
				default:
					break;
			}
		},
		assignGoodsTypeList(list) {
			this.goodsSelectList = uniqueBy(
				[...this.goodsSelectList, ...list],
				x => x.thirdLevelGoodsType || x.secondaryGoodsType || x.goodsType,
			);
		},
		assignUpgradeGoodsList(list) {
			this.selectUpgradeGoodsList = uniqueBy(
				[...this.selectUpgradeGoodsList, ...list],
				x => getUpgradeGoodsRowKey(x),
			);
		},
		// 取消选中套餐商品
		deletePackageGoodsItem(item) {
			this.selectPackageGoodsList = this.selectPackageGoodsList.filter(
				el => el?.packageCode != item?.packageCode,
			);
		},
		assignPackageGoodsList(list) {
			this.selectPackageGoodsList = uniqueBy(
				[...this.selectPackageGoodsList, ...list],
				x => x?.packageCode,
			);
		},
		// 进入页面获取第一页商品数据
		getSelectingList(defaultSelect) {
			getAllGoodsList({
				goodsNameKeyword: this.goodsNameKeyword,
				merchantId: this.routerInfo.merchantId,
				baseSceneCode: resolveBaseSceneCodeFromRouter(this.routerInfo),
				currentPage: this.currentPage,
				pageSize: this.pageSize,
			})
				.then((res) => {
					this.allPages = resolveProductSearchPages(
						res,
						this.currentPage,
						this.pageSize,
					);
					const resArr = mapProductSearchListToUpgradeGoodsOptions(res.list || []);
					let arr = this.upgradeGoodsList.concat(resArr);

					if (defaultSelect?.length) {
						arr = arr.concat(defaultSelect);
					}
					arr = filterUpgradeGoodsByMerchantCode(arr);
					this.upgradeGoodsList = uniqueUpgradeGoodsById(arr);
				})
				.catch(() => { });
		},
		// 或者商品套餐
		getSelectingListPackage(defaultSelect = []) {
			merchantPackageGoodsInfoPage({
				// goodsNameKeyword: this.goodsNameKeyword,
				currentPage: 1,
				pageSize: 20,
				status: 1,
				sceneType: this.routerInfo.scene,
				merchantIdList: [this.routerInfo.merchantId],
			})
				.then((res) => {
					// this.allPages = res.pages
					const resArr = [];
					res.list
					&& res.list.forEach((val) => {
						resArr.push({
							packageCode: val.packageCode,
							packageName: val.packageName,
						});
					});
					let arr = this.packageGoodsList.concat(resArr);
					if (defaultSelect?.length) {
						arr = arr.concat(defaultSelect);
					}
					this.packageGoodsList = uniquePackageByPackageCode(arr);
				})
				.catch(() => { });
		},

		addTab() {
			const length = this.editableTabs.length;
			this.addIndex = Math.max(1, length);

			this.editableTabs = this.editableTabs.map((item, index) => {
				item.name = (index + 1).toString();
				return item;
			});
			const newTabIndex = (this.editableTabs.length + 1).toString();

			this.editableTabs.push({
				title: "特殊品类" + this.addIndex++,
				name: newTabIndex,
				classificationUserTouched: false,
				sessionAdded: true,
			});

			const newIdx = this.editableTabs.length - 1;
			const ruleIdx = this.reconciliationRuleIndexForTabIndex(newIdx);
			if (
				ruleIdx != null
				&& this.goodsTypeGroupReconciliationRules[ruleIdx] == null
			) {
				this.$set(this.goodsTypeGroupReconciliationRules, ruleIdx, {});
			}

			this.editableTabsValue = newTabIndex;
			this.$nextTick(() => {
				if (String(this.editableTabsValue) !== String(newTabIndex)) {
					this.editableTabsValue = newTabIndex;
				}
			});
			this.bumpReconciliationInteractionEpoch();
		},
		confirmRemove(targetName) {
			// 删除tab
			this.$confirm("确认删除标签页吗?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
				closeOnClickModal: false, // 是否可以点击空白处关闭弹窗
			})
				.then(() => {
					// 确认切换标签页
					// this.activeName = tab.name
					this.removeTab(targetName);
				})
				.catch(() => {
					// 取消切换标签页
					this.$message({
						type: "info",
						message: "已取消删除",
					});
				});
		},
		async removeTab(targetName) {
			this.persistActiveClassificationTab();
			await this.$nextTick();
			const tabs = this.editableTabs;
			if (this.editableTabs.length <= 1) {
				return false;
			}

			const removeIdx = tabs.findIndex(
				item => String(item.name) === String(targetName),
			);
			if (removeIdx < 0) {
				return false;
			}

			const removedTab = tabs[removeIdx];
			const ruleIdxRemoved = this.reconciliationRuleIndexForTabIndex(removeIdx);
			if (
				removedTab
				&& removedTab.sessionAdded !== true
				&& ruleIdxRemoved != null
			) {
				const cached = this.goodsTypeGroupReconciliationRules[ruleIdxRemoved];
				const rid = getStableReconciliationRuleId(cached);
				if (rid) {
					const ruleSnapshot = cached && typeof cached === "object"
						? deepClone(cached)
						: {};
					delete ruleSnapshot.type;
					delete ruleSnapshot.tabPaneIndex;
					if (
						ruleSnapshot.groupDivisionRuleId == null
						|| String(ruleSnapshot.groupDivisionRuleId).trim() === ""
					) {
						ruleSnapshot.groupDivisionRuleId = rid;
					}
					this.pendingDeletedGroupDivisionRuleIds.push(ruleSnapshot);
				}
			}

			let activeIdx = tabs.findIndex(
				item => String(item.name) === String(this.editableTabsValue),
			);
			if (activeIdx < 0) {
				activeIdx = 0;
			}

			let newActiveIndex = activeIdx;
			if (newActiveIndex === removeIdx) {
				newActiveIndex = removeIdx > 0 ? removeIdx - 1 : 0;
			} else if (newActiveIndex > removeIdx) {
				newActiveIndex -= 1;
			}

			const upgradeArr = [];
			const packageArr = [];
			if (
				ruleIdxRemoved != null
				&& ruleIdxRemoved < this.goodsTypeGroupReconciliationRules.length
			) {
				this.goodsTypeGroupReconciliationRules.splice(ruleIdxRemoved, 1);
			}
			tabs.splice(removeIdx, 1);
			tabs.forEach((tab, index) => {
				this.$set(tab, "title", index ? "特殊品类" + index : "全部品类");
				this.$set(tab, "name", (index + 1).toString());
			});

			newActiveIndex = Math.max(0, Math.min(newActiveIndex, tabs.length - 1));
			this.editableTabsValue = tabs[newActiveIndex].name;

			this.goodsTypeGroupReconciliationRules.forEach((item) => {
				applyGoodsTypeGroupRelationBranches(
					item,
					item,
					upgradeArr,
					packageArr,
				);
			});
			this.getSelectingList(upgradeArr);
			this.getSelectingListPackage(packageArr);
			this.rebuildCrossTabGoodsSelectionsFromRules();
			this.bumpReconciliationInteractionEpoch();
			await this.$nextTick();
			this.$message({
				type: "success",
				message: "删除成功!",
			});
			return true;
		},

		deleteGoodsTypeItem(item) {
			// 根据最细一级的值来确定唯一性
			const targetValue = this._getFinestGoodsTypeValue(item);
			this.goodsSelectList = this.goodsSelectList.filter((el) => {
				const elValue = this._getFinestGoodsTypeValue(el);
				return elValue !== targetValue;
			});
		},
		/**
		 * 同步 categoryType 到 goodsTypeGroupReconciliationRules[ruleIdx],避免切换类型后被 getEffectRule 覆盖
		 */
		syncCategoryType(categoryType) {
			const tabIndex = this.activeDivisionTabIndex;
			const ruleIdx = this.reconciliationRuleIndexForTabIndex(tabIndex);
			// tab0 phantom 占位时 ruleIdx 为 null,无需同步(phantom 不在 rules 数组中)
			if (ruleIdx != null && this.goodsTypeGroupReconciliationRules?.[ruleIdx]) {
				this.$set(this.goodsTypeGroupReconciliationRules[ruleIdx], "categoryType", categoryType);
			}
		},
		deleteSelectGoodsTypeList(list) {
			this.goodsSelectList = this.goodsSelectList.filter((item) => {
				if (!list || !list.length) {
					return true;
				}
				// 根据最细一级的值来比较
				const itemValue = this._getFinestGoodsTypeValue(item);
				return !list.some((el) => {
					const elValue = this._getFinestGoodsTypeValue(el);
					return itemValue === elValue;
				});
			});
			// 同步清空当前 tab 在 goodsTypeGroupReconciliationRules 中的对应字段
			const tabIndex = this.activeDivisionTabIndex;
			const ruleIdx = this.reconciliationRuleIndexForTabIndex(tabIndex);
			if (ruleIdx != null && this.goodsTypeGroupReconciliationRules?.[ruleIdx]) {
				this.$set(this.goodsTypeGroupReconciliationRules[ruleIdx], "goodsTypeGroupRelations", []);
			}
			// 重新计算跨 Tab 禁用列表
			this.rebuildCrossTabGoodsSelectionsFromRules();
		},
		// 获取goodsType数据的最细一级值(用于唯一性判断)
		_getFinestGoodsTypeValue(item) {
			if (!item) {
				return null;
			}
			// 优先使用三级类目,然后二级,最后一级
			if (item.thirdLevelGoodsType) {
				return item.thirdLevelGoodsType;
			}
			if (item.secondaryGoodsType) {
				return item.secondaryGoodsType;
			}
			return item.goodsType;
		},
		deleteUpgradeGoodsItem(item) {
			this.selectUpgradeGoodsList = this.selectUpgradeGoodsList.filter(
				el => !sameUpgradeGoodsRow(el, item),
			);
		},
		deleteSelectUpgradeGoodsList(list) {
			this.selectUpgradeGoodsList = this.selectUpgradeGoodsList.reduce(
				(arr, item) => {
					if (
						list
						&& list.findIndex(el => sameUpgradeGoodsRow(item, el)) == -1
					) {
						arr.push(item);
					}
					return arr;
				},
				[],
			);
			// 同步清空当前 tab 在 goodsTypeGroupReconciliationRules 中的对应字段
			const tabIndex = this.activeDivisionTabIndex;
			const ruleIdx = this.reconciliationRuleIndexForTabIndex(tabIndex);
			if (ruleIdx != null && this.goodsTypeGroupReconciliationRules?.[ruleIdx]) {
				this.$set(this.goodsTypeGroupReconciliationRules[ruleIdx], "upgradeGoods", []);
			}
			// 重新计算跨 Tab 禁用列表
			this.rebuildCrossTabGoodsSelectionsFromRules();
		},
		deleteSelectPackageGoodsList(list) {
			this.selectPackageGoodsList = this.selectPackageGoodsList.reduce(
				(arr, item) => {
					if (
						list
						&& list.findIndex(el => item?.packageCode == el?.packageCode) == -1
					) {
						arr.push(item);
					}
					return arr;
				},
				[],
			);
			// 同步清空当前 tab 在 goodsTypeGroupReconciliationRules 中的对应字段
			const tabIndex = this.activeDivisionTabIndex;
			const ruleIdx = this.reconciliationRuleIndexForTabIndex(tabIndex);
			if (ruleIdx != null && this.goodsTypeGroupReconciliationRules?.[ruleIdx]) {
				this.$set(this.goodsTypeGroupReconciliationRules[ruleIdx], "packageGoods", []);
			}
			// 重新计算跨 Tab 禁用列表
			this.rebuildCrossTabGoodsSelectionsFromRules();
		},
		getRowItem() {
			this.merchantRow = parseRouteMerchantRow(this.$route.query?.params);
		},
		/**
		 * 拉取对账生效规则(仅进入页 / mounted 等调用 getEffectRuleApi)。
		 * 提交保存时不会走本方法;子组件 classificationCpt.getEffectRule 是本地合并回显,非接口请求。
		 */
		async getEffectRule() {
			this.reconciliationInteractionEpoch = 0;
			this.reconciliationSmsVerifyEpoch = -1;
			const params = {
				merchantId: this.merchantRow.merchantId,
				sceneType: this.merchantRow.scene,
			};
			const { baseSceneCode } = this.merchantRow;
			if (baseSceneCode != null && baseSceneCode !== "") {
				params.baseSceneCode = baseSceneCode;
			}
			const res = await getEffectRuleApi(params);
			if (res) {
				const typeList = res?.goodsTypeGroupReconciliationRules;
				if (Array.isArray(typeList) && Array.isArray(this.productType) && this.productType.length > 0) {
					fillGoodsTypesCategoryInfo(typeList, this.productType, "goodsTypeGroupRelations");
				}
				this.goodsTypeGroupReconciliationRules
					= res?.goodsTypeGroupReconciliationRules;
				this.formObj = res;

				if (typeList?.length) {
					/**
					 * 首条为特殊品类时:保留首 Tab「全部品类」占位(无对应规则),子组件 tab0 不做回填;
					 * 特殊品类从第二个 Tab 起与 rules 按下标对齐(子组件内 res[tabindex-1])。
					 */
					const upgradeArr = [];
					const packageArr = [];
					typeList.forEach((item, index) => {
						if (item.groupType == 2) {
							this.editableTabs.push({
								title:
                  "特殊品类"
                  + (typeList[0].groupType == 2 ? index + 1 : index),
								name: (
									(typeList[0].groupType == 2 ? index + 1 : index) + 1
								).toString(),
								classificationUserTouched: false,
								sessionAdded: false,
							});
						}

						applyGoodsTypeGroupRelationBranches(
							item,
							this.goodsTypeGroupReconciliationRules[index],
							upgradeArr,
							packageArr,
						);
					});
					this.getSelectingList(upgradeArr);
					this.getSelectingListPackage(packageArr);
				}
				this.rebuildCrossTabGoodsSelectionsFromRules();
			} else {
				this.getSelectingList();
				this.getSelectingListPackage();
				this.rebuildCrossTabGoodsSelectionsFromRules();
			}
			this.editableTabs.forEach((tab) => {
				this.$set(tab, "classificationUserTouched", false);
				this.$set(tab, "sessionAdded", false);
			});
			this.reconciliationRulesBaseline = {
				goodsTypeGroupReconciliationRules: deepClone(
					this.goodsTypeGroupReconciliationRules || [],
				),
				phantomFullCategoryRule: this.phantomFullCategoryRule
					? deepClone(this.phantomFullCategoryRule)
					: null,
			};
			/** 与基线比对、resolve、跨 Tab 聚合见 getEffectivePhantomFullCategoryRuleRaw(回落 baseline.phantom) */
			this.phantomFullCategoryRule = null;
			this.pendingDeletedGroupDivisionRuleIds = [];
		},
		/**
		 * 校验结果:增量对象 `{ ok, incrementalRules }`(与 verifyFormData / getReconciliationGoodsTypeGroupRules 一致)。
		 */
		checkParamsType(obj) {
			if (!obj || typeof obj !== "object" || !("ok" in obj)) {
				return false;
			}
			if (obj.ok === false) {
				return false;
			}
			const inc = obj.incrementalRules;
			if (Array.isArray(inc)) {
				if (inc.length === 0) {
					return true;
				}
				return inc.every(item => item && typeof item === "object");
			}
			return true;
		},
		// 显示smcode弹框
		async showsmCode() {
			this.pageOverlayLoading = true;
			try {
				const res = await this.verifyFormData();
				if (!this.checkParamsType(res)) {
					this.focusTabByErrorIndex();
					return this.$message.warning("请完善对账规则");
				}
				this.errorIndex = -1;
				this.reconciliationSmsVerifyEpoch = this.reconciliationInteractionEpoch;
				this.verificationCodeVisible = true;
			} finally {
				this.pageOverlayLoading = false;
			}
		},
		// 获取弹框中的验证码
		codeHandleConfirm({ smsCode, effectStartDate }) {
			this.effectStartDateDate = effectStartDate
				? effectStartDate + " 00:00:00"
				: "";
			this.smsCode = smsCode;
			this.submitFormData(true);
		},
		/**
		 * 提交对账规则:`goodsTypeGroupRules` 为相对基线仍有变更的增量(含 type ADD/UPDATE/DELETE),
		 * 无变更且无待删 id 时为 []。
		 */
		async submitFormData(skipReverifyAfterSms = false) {
			this.pageOverlayLoading = true;
			try {
				const canSkipReverify
					= skipReverifyAfterSms
						&& this.reconciliationLastVerifyResult?.ok === true
						&& this.reconciliationSmsVerifyEpoch === this.reconciliationInteractionEpoch;
				const res = canSkipReverify
					? {
							ok: true,
							incrementalRules:
              this.reconciliationLastVerifyResult.incrementalRules || [],
							fullMergedRules: this.reconciliationLastVerifyResult.fullMergedRules,
						}
					: await this.verifyFormData();
				if (!this.checkParamsType(res)) {
					this.focusTabByErrorIndex();
					return this.$message.warning("请完善对账规则");
				}
				this.errorIndex = -1;
				const {
					shopMerchantTotalFeeCalculateType,
					shopMerchantExpenseCategoryValue,
					partnerMerchantTotalFeeCalculateType,
					partnerMerchantExpenseCategoryValue,
				} = this.formObj;
				const rawIncremental
					= this.reconciliationLastVerifyResult?.incrementalRules ?? [];
				const shapedIncremental = this.shapeGoodsTypeGroupRulesForApi(
					rawIncremental,
				);
				const goodsPayload = appendDeleteOpsToIncremental(
					shapedIncremental,
					this.pendingDeletedGroupDivisionRuleIds || [],
				);
				if (this.reconciliationLastVerifyResult?.ok) {
					this.reconciliationLastVerifyResult.incrementalRules = deepClone(
						goodsPayload,
					);
				}
				const params = {
					smsCode: this.smsCode,
					effectStartDate: this.effectStartDateDate,
					merchantId: this.merchantRow.merchantId,
					sceneType: this.merchantRow.scene,
					baseSceneCode: resolveBaseSceneCodeFromRouter(this.routerInfo),
					goodsTypeGroupRules: goodsPayload,
					shopMerchantTotalFeeCalculateType,
					shopMerchantExpenseCategoryValue,
					partnerMerchantTotalFeeCalculateType,
					partnerMerchantExpenseCategoryValue,
				};
				// 处理分账品类按商品分类的传参,仅传选中最细一级的类目数据
				params.goodsTypeGroupRules?.forEach((item) => {
					item.goodsTypeGroupRelations?.forEach((relation) => {
						relation.goodsType = relation.thirdLevelGoodsType || relation.secondaryGoodsType || relation.goodsType;
						relation.goodsTypeName = relation.thirdLevelGoodsTypeName || relation.secondaryGoodsTypeName || relation.goodsTypeName;
						delete relation.thirdLevelGoodsType;
						delete relation.thirdLevelGoodsTypeName;
						delete relation.secondaryGoodsType;
						delete relation.secondaryGoodsTypeName;
					});
				});
				console.log("[MerchantCheck] submitFormData params", params);
				const result = await saveRuleApi({ json: JSON.stringify(params) });
				if (result) {
					this.pendingDeletedGroupDivisionRuleIds = [];
					this.$message({
						message: "提交成功",
						type: "success",
					});
					this.$router.push({ name: "merchantManage" });
				}
			} finally {
				this.pageOverlayLoading = false;
			}
		},
		// 校验所有form数据(persist 仅在 getReconciliationGoodsTypeGroupRules 内、有待校验 Tab 时执行,避免无操作保存前污染缓存)
		async verifyFormData() {
			await this.$nextTick();
			const result = await this.getReconciliationGoodsTypeGroupRules(
				this.editableTabs,
			);
			if (result.ok) {
				this.reconciliationLastVerifyResult = {
					ok: true,
					incrementalRules: deepClone(result.incrementalRules || []),
					fullMergedRules: result.fullMergedRules
						? deepClone(result.fullMergedRules)
						: null,
				};
				this.errorIndex = -1;
			} else {
				this.reconciliationLastVerifyResult = { ok: false, incrementalRules: [], fullMergedRules: null };
			}
			return result;
		},
		/**
		 * A7:errorIndex 与 getReconciliationGoodsTypeGroupRules 联动;校验失败时显式切到首个有误 Tab(避免恢复焦点后仍停在其它 Tab)
		 */
		focusTabByErrorIndex() {
			if (this.errorIndex < 0) {
				return;
			}
			const tab = this.editableTabs[this.errorIndex];
			if (tab && tab.name != null) {
				this.editableTabsValue = String(tab.name);
			}
		},
		// 取消
		handleReset() {
			this.$router.go(-1);
		},
	},
};
</script>

<style lang="scss">
.merchant-check {
	padding-left: 20px;
	padding-right: 16px;
	padding-bottom: 20px;

	.headerCon {
		box-sizing: border-box;
		background-color: #fff;
		// padding-bottom: 20px;
		margin-bottom: 20px;
	}

	// .w432 {
	//   width: 432px;
	// }
	.check-title {
		display: flex;
		align-items: center;
		// margin-top: 16px;
		margin-bottom: 16px;
		height: 52px;
		background: #ffffff;

		.store {
			margin-left: 20px;
			font-size: 14px;
			color: #333333;
		}

		.scene {
			margin-left: 220px;
			font-size: 14px;
			color: #333333;
		}
	}

	.check-tab {
		background: #ffffff;
	}

	/* 与 financialRules/index.vue「品类切换」工具条同构(含下拉、选项行、蓝条) */
	.edit-sub-title.division-rules-toolbar {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		gap: 8px 16px;
		padding: 10px 28px 0;
	}

	/* 覆盖 public.scss:flex 工具条行高大于纯文字标题时,蓝竖条需相对本行垂直居中 */
	.edit-sub-title.division-rules-toolbar::before {
		top: 60%;
		left: 16px;
		transform: translateY(-50%);
	}

	.division-rules-toolbar {
		.division-rules-toolbar__controls {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			flex: 1;
			min-width: 0;
		}

		.select-wrapper {
			flex-shrink: 0;
			flex: 1;
			min-width: 200px;

			::v-deep .tab-select {
				width: 280px;
				max-width: 100%;
			}
		}

		.actions-wrapper {
			flex-shrink: 0;
		}
	}

	.classificationCptContainer {
		margin-top: 8px;
		padding-bottom: 8px;
	}

	.check-btns {
		padding-top: 16px;
		// margin-top: 16px;
		display: flex;
		justify-content: center;
		align-items: center;
		background: #f0f2f5;
	}

	.multiple-type {
		display: flex;
		align-items: center;
		margin-bottom: 18px;

		.el-form-item__content {
			display: flex;
			align-items: center;
		}

		.el-form-item {
			margin-bottom: 0;
		}

		.el-input__inner {
			line-height: 1px !important;
		}
	}

	.ml20 {
		margin-left: 20px;
	}
}
</style>

<style lang="scss">
.merchant-check-tab-select-dropdown.el-select-dropdown {
	.el-select-dropdown__item {
		display: flex;
		align-items: center;
		width: 100% !important;
		max-width: 100%;
		box-sizing: border-box;
		padding-right: 20px;
	}

	.tab-select-options-wrapper {
		width: 100%;
		min-width: 0;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		overflow: hidden;

		> .icons {
			flex-shrink: 0;
		}

		> .label {
			flex: 1;
			min-width: 0;
			margin: 0 4px;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}

		> .actions {
			flex-shrink: 0;
			margin-left: auto;
		}
	}
}
</style>