SystemBillDialog.vue 76.9 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
<template>
  <div>
    <el-drawer :visible.sync="billVisible" size="100%" class="bill-drawer" :before-close="handleClose">
      <div slot="title" class="drawer-title">系统对账单</div>
      <div class="privacyDrawer">
        <div class="flex">
          <div>
            {{ dateStr }}销售对账单
            <el-button v-if="billTmplInfo.billType == '1'" size="mini" icon="el-icon-plus" @click="handleChooseRefundOrder">添加门店退款订单</el-button>
          </div>
          <!-- <div>适用对象:{{billTmplInfo.billMerchantName}}</div> -->
          <el-form ref="accountForm" :model="infoForm" :rules="formRules" label-width="120px" class="flex">
            <el-form-item label="对账模版:" prop="templateId" style="margin-bottom: 10px;">
              <el-select v-model="infoForm.templateId" style="width:240px" @change="handleTmplChange">
                <el-option v-for="item in baseData[billTypeStr + 'TemplateList']" :key="item.id" :label="item.templateName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item prop="fieldsJson" label-width="8px" style="margin-bottom: 10px;">
              <div class="tmpl-box">
                <el-tooltip v-show="infoForm.fieldsTxt" effect="dark" placement="top" :content="infoForm.fieldsTxt">
                  <span class="fields-txt">{{infoForm.fieldsTxt}}</span>
                </el-tooltip>
                <div v-show="tmplSelectList.length">共{{tmplSelectList.length}}个字段</div>
                <el-button v-if="infoForm.templateId" type="text" @click="handleCustTmpl" style="margin-left: 8px;">自定义</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <el-table v-loading="loading" :data="tableList" style="width: 100%" height="652px" ref="billMutiTable" show-summary :summary-method="getSummaries" :span-method="arraySpanMethod" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column v-for="(item, idx) in tableHeader" :key="idx" :label="item.moduleName">
            <el-table-column v-for="(subItem, subIdx) in item.items" :key="subIdx" :prop="subItem.fieldCode" :label="subItem.fieldName" :width="subItem.width || '120px'">
              <div class="tb-header-cell" slot="header" slot-scope="scope">
                <span>{{subItem.fieldName}}</span>
                <img v-if="judgeImgShow(scope)" src="@/assets/icon-edit2.png" style="cursor: pointer;margin-left: 5px;width: 16px;height: 16px; vertical-align: middle;" @click="handleBatch(scope)" />
                <img v-if="judgeFilterImgShow(scope).show && judgeFilterImgShow(scope).icon =='icon-filter'" src="@/assets/icon-filter.png" style="cursor: pointer;margin-left: 5px;width: 16px;height: 16px;vertical-align: middle;" @click="handleOpenSearch(scope)" />
                <img v-if="judgeFilterImgShow(scope).show && judgeFilterImgShow(scope).icon =='icon-filter-check'" src="@/assets/icon-filter-check.png" style="cursor: pointer;margin-left: 5px;width: 16px;height: 16px;vertical-align: middle;" @click="handleOpenSearch(scope)" />
              </div>
              <div class="tb-cell" slot-scope="scope">
                <!-- 输入框 -->
                <template v-if="subItem.editType == 'input'">
                  <span v-if="judgeDisable(scope.$index, subItem.extInfo.source || 'ORDER', subItem) && ['partnerFeeCalculateCoefficient'].includes(subItem.fieldCode)">-</span>
                  <el-input v-else :style="{ 'width': subItem.extInfo.width || '110px' }" :placeholder="item.placeholder || '请输入'" v-bind="subItem.attrs ? subItem.attrs : {}" v-on="subItem.listeners ? subItem.listeners : {}" :prefix-icon="subItem.prefixIcon" :disabled="judgeDisable(scope.$index, subItem.extInfo.source || 'ORDER', subItem)" v-model.trim="scope.row[subItem.extInfo.source || 'ORDER'][subItem.fieldCode]" :maxlength="subItem.maxlength" :type="subItem.inputType || 'text'" @input="(e) => handleInputDown(e, scope.$index, subItem.extInfo.source || 'ORDER', subItem)" @blur="modifyAdd(scope.$index, subItem.extInfo.source || 'ORDER', subItem.fieldCode, subItem)" :class="{ 'is-error': hasError(scope.$index, subItem.extInfo.source || 'ORDER', subItem.fieldCode) }">
                    <span v-if="subItem.editObj.prepend" slot="prepend" style="font-size: 12px;">{{ subItem.editObj.prepend }}</span>
                    <span v-if="subItem.editObj.append" slot="suffix" style="font-size: 12px;">{{ subItem.append }}</span>
                  </el-input>
                  <div v-if="hasError(scope.$index, subItem.extInfo.source || 'ORDER', subItem.fieldCode)" class="el-form-item__error">
                    {{ getErrorMessage(scope.$index, subItem.extInfo.source || 'ORDER', subItem.fieldCode) }}
                  </div>
                </template>
                <!-- 选择框 -->
                <div v-else-if="subItem.editType == 'select'">
                  <el-select :style="{ 'width': subItem.extInfo.width || '110px' }" v-model="scope.row[subItem.extInfo.source || 'ORDER'][subItem.fieldCode]" v-bind="item.attrs ? item.attrs : {}" v-on="item.listeners ? item.listeners : {}" clearable :placeholder="item.placeholder || '请选择'" :filterable="!item.noFilter" :disabled="judgeDisable(scope.$index, subItem.extInfo.source || 'ORDER', subItem)" no-data-text="无数据" :multiple="item.multiple || false" :collapse-tags="item.collapseTags || true" @change="selectAddAttr($event, scope.$index, subItem)" :class="{ 'is-error': hasError(scope.$index, subItem.extInfo.source || 'ORDER', subItem.fieldCode) }">
                    <el-option v-for="k in baseData[subItem.editObj.optionsName]" :key="k[subItem.editObj.optionId]" :label="k[subItem.editObj.optionLabel]" :value="k[subItem.editObj.optionId]"></el-option>
                  </el-select>
                  <div v-if="hasError(scope.$index, subItem.extInfo.source || 'ORDER', subItem.fieldCode)" class="el-form-item__error">
                    {{ getErrorMessage(scope.$index, subItem.extInfo.source || 'ORDER', subItem.fieldCode) }}
                  </div>
                </div>

                <!-- 选择输入组合框 -->
                <div v-else-if="subItem.editType == 'selectInput'">
                  <div class="select-input-container">
                    <span v-if="judgeDisable(scope.$index, subItem.extInfo.source || 'ORDER', subItem)">-</span>
                    <el-input v-else placeholder="请输入" v-model.trim="scope.row[subItem.extInfo.source || 'ORDER'][subItem.editObj.inputField]" :type="subItem.editObj.inputType || 'text'" class="input-with-select" :disabled="judgeDisable(scope.$index, subItem.extInfo.source || 'ORDER', subItem)" @input="handleSelectInputChange(scope.$index, subItem, false)" @blur="modifyAdd(scope.$index, subItem.extInfo.source || 'ORDER', subItem.fieldCode, subItem)" :class="{ 'is-error': hasError(scope.$index, subItem.extInfo.source || 'ORDER', subItem.editObj.inputField) }">
                      <el-select v-model="scope.row[subItem.extInfo.source || 'ORDER'][subItem.editObj.selectField]" style="width: 90px" :popper-append-to-body="false" slot="prepend" placeholder="请选择" :disabled="judgeDisable(scope.$index, subItem.extInfo.source || 'ORDER', subItem)" @change="handleSelectInputChange(scope.$index, subItem)" :class="{ 'is-error': hasError(scope.$index, subItem.extInfo.source || 'ORDER', subItem.editObj.selectField) }">
                        <el-option v-for="(k, kIdx) in subItem.editObj.optionList" :key="kIdx" :label="k[subItem.editObj.optionLabel]" :value="k[subItem.editObj.optionId]" />
                      </el-select>
                      <span v-if="subItem.editObj.suffixFn" slot="suffix">
                        <span class="inputSuffix">{{ subItem.editObj.suffixFn(scope.$index, subItem.extInfo.source || 'ORDER', subItem.editObj.selectField, subItem.editObj.inputField) }}</span>
                      </span>
                    </el-input>
                    <div v-if="hasError(scope.$index, subItem.extInfo.source || 'ORDER', subItem.editObj.selectField)" class="el-form-item__error">
                      {{ getErrorMessage(scope.$index, subItem.extInfo.source || 'ORDER', subItem.editObj.selectField) }}
                    </div>
                    <div v-if="hasError(scope.$index, subItem.extInfo.source || 'ORDER', subItem.editObj.inputField)" class="el-form-item__error">
                      {{ getErrorMessage(scope.$index, subItem.extInfo.source || 'ORDER', subItem.editObj.inputField) }}
                    </div>
                  </div>
                </div>
                <div v-else-if="subItem.txtType == 'selectInput'">
                  {{scope.row[subItem.extInfo.source || 'ORDER'][subItem.txtObj.selectField] ? (scope.row[subItem.extInfo.source || 'ORDER'][subItem.txtObj.selectField] + (scope.row[subItem.extInfo.source || 'ORDER'][subItem.txtObj.inputField] + '')) : '-'}}
                </div>
                <!-- 普通文本显示 -->
                <div v-else class="flex-center">
                  <div v-if="subItem.fieldCode == 'orderCode'" class="flex-center">
                    <img v-if="scope.row.ORDER.sourceType != 1" class="refund-img" src="@/assets/retrun.png">
                    <div>{{ scope.row[subItem.extInfo.source || 'ORDER'][subItem.fieldCode] || '-' }}</div>
                  </div>
                  <div v-else-if="subItem.fieldCode == 'tradeNo'" :class="['trade-no', scope.row.ORDER.payVoucherList && scope.row.ORDER.payVoucherList.length ? 'txt-blue': '' ]" @click="handleReviewImg(scope.row)">
                    {{ scope.row[subItem.extInfo.source || 'ORDER'][subItem.fieldCode] || '-' }}
                  </div>
                  <div v-else-if="scope.row[subItem.extInfo.source || 'ORDER'][subItem.fieldCode] === 0">0</div>
                  <div v-else>{{ scope.row[subItem.extInfo.source || 'ORDER'][subItem.fieldCode] || '-' }}</div>
                </div>
              </div>
            </el-table-column>
          </el-table-column>
          <el-table-column label="操作" :width=" billTypeStr == 'traffic' ? '50px' : ''">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.pageNum" :page-size="page.pageSize" :total="page.total" :page-sizes="[10, 20, 30, 40]" layout="sizes,total,->,prev,pager,next,jumper">
      </el-pagination> -->
        <DynamicAddTable v-if="billTypeStr == 'traffic'" ref="dynamicReceiveAdd" :configObj="{'title': '应收'}" :adjustments="receivableAdjustments" @handleInputBlur="billCompute"></DynamicAddTable>
        <DynamicAddTable ref="dynamicAdd" :adjustments="payableAdjustments" @handleInputBlur="billCompute"></DynamicAddTable>
      </div>
      <div class="footer">
        <div class="total-box">
          <div>订单总数:{{ totalOrderCount }}</div>
          <div>总产值:{{ totalAmount }}元</div>
          <div v-if="billTypeStr == 'traffic'">应收总额:{{ totalReceivable }}元</div>
          <div>应付总额:{{ totalPayable }}元</div>
          <div v-if="billTypeStr == 'traffic'">线上分账总额:{{ totalSplitPaidAmount }}元</div>
          <div v-if="billTypeStr == 'traffic'">线下已付总额:{{ totalOfflinePaidAmount }}元</div>
          <div v-if="billTypeStr == 'traffic'">线下对账总额:{{ totalOfflineReconciliation }}元</div>
        </div>
        <div class="btn-box">
          <el-button class="btn" @click="handleClose">取消</el-button>
          <el-button class="btn" type="primary" :loading="loading" @click="handleConfirm">确定</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 批量輸入 -->
    <d2-dialog v-if="batchVisible" :title="headObj.fieldCode == 'payType' ? '备注' : ('批量设置' + headObj.fieldName)" :is-visible="batchVisible" class="privacyDailog" width="480px" @closeDialog="handleBatchClose" @confirmDialog="handleBatchConfirm">
      <div class="batch-box">
        <!-- 输入框 -->
        <template v-if="headObj.editType == 'input'">
          <el-input style="width: 200px" placeholder="请输入" :prefix-icon="headObj.prefixIcon" v-model.trim="batchForm[headObj.fieldCode]" :maxlength="headObj.maxlength" :type="headObj.inputType || 'text'" @blur="batchValidateForm" @input="(e) => maxLengthInput(e)" :class="{ 'is-error': dialogErrors[headObj.fieldCode] }">
            <span v-if="headObj.editObj.prepend" slot="prepend">{{ headObj.editObj.prepend }}</span>
            <span v-if="headObj.editObj.append" slot="suffix">{{ headObj.append }}</span>
          </el-input>
          <div v-if="dialogErrors[headObj.fieldCode]" class="el-form-item__error">{{ dialogErrors[headObj.fieldCode] }}</div>
        </template>

        <!-- 选择框 -->
        <div v-else-if="headObj.editType == 'select'">
          <el-select style="width: 400px" v-model="batchForm[headObj.fieldCode]" placeholder="请选择" no-data-text="无数据" :class="{ 'is-error': dialogErrors[headObj.fieldCode] }" @change="batchValidateForm">
            <el-option v-for="k in baseData[headObj.editObj.optionsName]" :key="k[headObj.editObj.optionId]" :label="k[headObj.editObj.optionLabel]" :value="k[headObj.editObj.optionId]"></el-option>
          </el-select>
          <div v-if="dialogErrors[headObj.fieldCode]" class="el-form-item__error">{{ dialogErrors[headObj.fieldCode] }}</div>
        </div>

        <!-- 选择输入组合框 -->
        <div v-else-if="headObj.editType === 'selectInput'">
          <div class="select-input-container">
            <el-input placeholder="请输入" v-model.trim="batchForm[headObj.editObj.inputField]" class="input-with-select" :class="{ 'is-error': dialogErrors[headObj.editObj.inputField] }" :type="headObj.editObj.inputType || 'text'" @blur="batchValidateForm">
              <el-select v-model="batchForm[headObj.editObj.selectField]" style="width: 200px" :popper-append-to-body="false" slot="prepend" placeholder="请选择" :class="{ 'is-error': dialogErrors[headObj.editObj.selectField] }" @change="batchValidateForm">
                <el-option v-for="(k, kIdx) in headObj.editObj.optionList" :key="kIdx" :label="k[headObj.editObj.optionLabel]" :value="k[headObj.editObj.optionId]" />
              </el-select>
              <span v-if="headObj.editObj.suffixFn" slot="suffix">
                <span class="inputSuffix">{{ headObj.editObj.suffixFn('', headObj.extInfo.source || 'ORDER', headObj.editObj.selectField, headObj.editObj.inputField, true) }}</span>
              </span>
            </el-input>
            <div v-if="dialogErrors[headObj.editObj.inputField]" class="el-form-item__error">{{ dialogErrors[headObj.editObj.inputField] }}</div>
            <div v-if="dialogErrors[headObj.editObj.selectField]" class="el-form-item__error">{{ dialogErrors[headObj.editObj.selectField] }}</div>
          </div>
        </div>
        <div v-if="headObj.fieldCode == 'payType'" class="red-txt">
          提示:若按支付方式拆分对账单,切换收款方式,系统自动将该订单切换至对应周期+收款方式的对账单中;若无对账单则在下次生成对应收款方式的对账单时自动加入;
        </div>
      </div>
    </d2-dialog>
    <tmpl-drawer v-if="tmplDrawerVisible" :tmplDrawerVisible="tmplDrawerVisible" :type="tmplInfo.type" :tmplSelectList="tmplInfo.tmplSelectList" @handleConfirm="handleCustConfirm" @handleClose="handleCustVisible"></tmpl-drawer>
    <choose-refund-order-dialog v-if="chooseVisible" :chooseVisible="chooseVisible" :infoForm="refundInfo" @chooseOrderConfirm="chooseOrderConfirm" @dialogClose="changeChooseVisible"></choose-refund-order-dialog>
    <glsk-form-dialog v-if="searchVisible" :selectVisible="searchVisible" :dialogConfig="searchDialogConfig" label-width="200px" :formRules="searchRules" :editData="searchForm" :editFormData="searchEditFormData" :baseData="baseData" @handleClose="searchDialogVisible" @handleConfirm="handleSearchConfirm"></glsk-form-dialog>
    <el-image-viewer style="z-index: 9999;" v-if="imgVisible" :on-close="closeImgViewer" :url-list="imgList" :initial-index="initialIndex" />
  </div>
</template>

<script>
import { deepClone, Util } from '@/common/util'
import { getPlatformMerchantList } from '@api/index'
import DynamicAddTable from './DynamicAddTable'
import tmplDrawer from "./TmplDrawer"
import ChooseRefundOrderDialog from './ChooseRefundOrderDialog.vue'
import { billComputePage, editBillPage, getTmplList, getMetaTmpl, mergeRefundOrder } from '@api/accountManage'
import { payTypeList } from "@/common/constants"
import { localTmplList } from "../constant/baseData"
export default {
  name: 'SystemBillDialog',
  props: {
    billVisible: {
      type: Boolean,
      default: false
    },
    billTmplInfo: {
      type: Object,
      default: () => ({})
    }
  },
  components: {
    DynamicAddTable,
    tmplDrawer,
    ChooseRefundOrderDialog,
    "el-image-viewer": () =>
      import("element-ui/packages/image/src/image-viewer")
  },
  data() {
    return {
      loading: false,
      imgVisible: false,
      initialIndex: 0,
      imgList: [],
      billTypeStr: 'traffic',
      dateStr: '',
      tmplFieldsList: [],
      tableHeader: [],
      originalOrderList: [],
      // 列表数据
      tableList: [],
      isFirst: true,
      // 自有列表数据
      ownOrderList: [],
      // 退款订单列表
      // refundOrderList: [],
      // 用户修改过的列表数据
      tableModifyList: [],
      // 用户删除的ordercodelist
      tableDeleteList: [],
      validationErrors: {},
      receivableAdjustments: [],
      payableAdjustments: [],
      multipleSelecList: [],
      // 筛选弹窗,
      searchDialogConfig: {
        title: '筛选',
        okText: '确定'
      },
      searchVisible: false,
      searchRules: {},
      searchEditFormData: [],
      // 筛选项
      searchAttrObj: {
        // 订单号
        orderCode: {
          editFormData: {
            label: '订单编号',
            name: 'orderCodeKeyword',
            type: 'input',
            maxlength: 50,
            isClear: true
          },
          rule: {
            orderCodeKeyword: [{
              validator: (rule, value, cb) => {
                if (value && !/^[0-9]+$/.test(value)) {
                  return cb(new Error("只能输入数字"))
                } else {
                  cb()
                }
              },
              trigger: "change"
            }]
          }
        },
        // 客户姓名
        customerName: {
          editFormData: {
            label: '客户姓名',
            name: 'customerName',
            type: 'input',
            maxlength: 50,
            isClear: true
          }
        },
        // 交易参考号
        tradeNo: {
          editFormData: {
            label: '交易参考号',
            name: 'tradeNoKeyword',
            type: 'input',
            maxlength: 50,
            isClear: true
          }
        },
        // 商品名称
        goodsName: {
          editFormData: {
            label: '商品名称',
            name: 'goodsNameList',
            type: 'select',
            multiple: 'true',
            optionId: 'confId',
            optionLabel: 'confLabel',
            optionsName: 'goodsList',
            isClear: true
          }
        },
        // 支付时间
        paymentTime: {
          editFormData: {
            label: '支付时间',
            name: 'paymentTime',
            type: 'datePicker',
            isClear: true,
            pickerOptions: 'beforeRangePickerOptions'
          }
        },
        // 支付方式
        payType: {
          editFormData: {
            label: '支付方式',
            name: 'payTypeList',
            type: 'select',
            multiple: 'true',
            optionId: 'confId',
            optionLabel: 'confLabel',
            optionsName: 'recvTypeList',
            isClear: true
          }
        }
      },
      searchForm: {
        orderCodeKeyword: '',
        customerName: '',
        tradeNoKeyword: '',
        goodsNameList: '',
        paymentTime: '',
        payTypeList: ''
      },
      // 分页
      page: {
        //   pageNum: 1,
        //   pageSize: 10,
        total: 0
      },
      headObj: {},
      batchForm: {},
      batchVisible: false,
      dialogErrors: {},
      trafficChangeTxtList: [
        //   {
        //   name: '分账类型',
        //   source: 'ORDER',
        //   attr: 'divisionType',
        //   type: 'select',
        //   optionId: 'confId',
        //   optionLabel: 'confLabel',
        //   optionsName: 'divisionTypeList'
        // },
        // {
        //   name: '分账状态',
        //   source: 'ORDER',
        //   attr: 'divisionStatus',
        //   type: 'select',
        //   optionId: 'confId',
        //   optionLabel: 'confLabel',
        //   optionsName: 'divisionStatusList'
        // },
        // {
        //   name: '对账状态',
        //   source: 'ORDER',
        //   attr: 'reconcileStatus',
        //   type: 'select',
        //   optionId: 'confId',
        //   optionLabel: 'confLabel',
        //   optionsName: 'reconcileStatusList'
        // },
        // {
        //   name: '订单时间',
        //   source: 'ORDER',
        //   attr: 'orderTime',
        //   type: 'time'
        // },
        {
          name: '支付时间',
          source: 'ORDER',
          attr: 'paymentTime',
          type: 'time'
        },
        //  {
        //   name: '支付方式',
        //   source: 'ORDER',
        //   attr: 'payType',
        //   type: 'select',
        //   optionId: 'confId',
        //   optionLabel: 'confLabel',
        //   optionsName: 'payTypeList'
        // },
        // {
        //   name: '流量方套餐比例',
        //   source: 'PACKAGE',
        //   attr: 'trafficFeeCalculateType,trafficFeeCalculateValue',
        //   optionId: 'confId',
        //   optionLabel: 'confLabel',
        //   optionsName: 'trafficFeeCalculateTypeTxtList',
        //   type: 'selectInput'
        // }, {
        //   name: '流量方整单比例',
        //   source: 'ORDER',
        //   attr: 'trafficFeeCalculateType,trafficFeeCalculateValue',
        //   optionId: 'confId',
        //   optionLabel: 'confLabel',
        //   optionsName: 'trafficFeeCalculateTypeTxtList',
        //   type: 'selectInput'
        // }
      ],
      serviceChangeTxtList: [
        //   {
        //   name: '分账类型',
        //   source: 'ORDER',
        //   attr: 'divisionType',
        //   type: 'select',
        //   optionId: 'confId',
        //   optionLabel: 'confLabel',
        //   optionsName: 'divisionTypeList'
        // },
        // {
        //   name: '分账状态',
        //   source: 'ORDER',
        //   attr: 'divisionStatus',
        //   type: 'select',
        //   optionId: 'confId',
        //   optionLabel: 'confLabel',
        //   optionsName: 'divisionStatusList'
        // },
        // {
        //   name: '对账状态',
        //   source: 'ORDER',
        //   attr: 'reconcileStatus',
        //   type: 'select',
        //   optionId: 'confId',
        //   optionLabel: 'confLabel',
        //   optionsName: 'reconcileStatusList'
        // },
        //  {
        //   name: '支付方式',
        //   source: 'ORDER',
        //   attr: 'payType',
        //   type: 'select',
        //   optionId: 'confId',
        //   optionLabel: 'confLabel',
        //   optionsName: 'payTypeList'
        // },
        // {
        //   name: '订单时间',
        //   source: 'ORDER',
        //   attr: 'orderTime',
        //   type: 'time'
        // },
        {
          name: '支付时间',
          source: 'ORDER',
          attr: 'paymentTime',
          type: 'time'
        }],
      // 用于标记表头字段是否可以编辑(唯一标识:source + FieldCode)
      trafficSourceEditList: [
        'ORDER_PACKAGEfinalGoodsCost',
        'ORDERplatformMerchantId',
        'ORDERshopDivisionMoney',
        'ORDERofflinePaidAmount',
        'SUB_ORDERtrafficFeeCalculateType,trafficFeeCalculateValue',
        "ORDERpayType",
        "ORDERremark"
      ],
      serviceSourceEditList: ["SUB_ORDERpartnerFeeCalculateType,partnerFeeCalculateValue", "SUB_ORDERpartnerFeeCalculateCoefficient", "ORDERpayType", "SUB_ORDERsecondPartnerFee", "ORDERremark"],
      trafficEditList: [
        'finalGoodsCost',
        'platformMerchantId',
        'shopDivisionMoney',
        'offlinePaidAmount',
        'trafficFeeCalculateType,trafficFeeCalculateValue',
        "payType",
        "remark"
      ],
      serviceEditList: ["partnerFeeCalculateType,partnerFeeCalculateValue", "partnerFeeCalculateCoefficient", "payType", "secondPartnerFee", "remark"],
      totalAmount: 0,
      totalOrderCount: 0,
      totalReceivable: 0,
      totalPayable: 0,
      totalSplitPaidAmount: 0,
      totalOfflinePaidAmount: 0,
      totalOfflineReconciliation: 0,
      editObj: {
        select: {
          attrList: ['payType', 'platformMerchantId'],
          defaultConf: {
            payType: {
              optionId: 'confId',
              optionLabel: 'confLabel',
              optionsName: 'recvTypeList',
              fn: (val, listIdx, obj) => {
              }
            },
            platformMerchantId: {
              optionId: 'merchantId',
              optionLabel: 'merchantName',
              optionsName: 'PlatformMerchantList',
              batchName: 'platformMerchantName',
              fn: (val, listIdx, obj) => {
                const source = obj.extInfo.source || 'ORDER'
                this.tableList[listIdx][source].platformMerchantName =
                  this.baseData[obj.editObj.optionsName]
                    .find(item => item[obj.editObj.optionId] == val)?.[obj.editObj.optionLabel]
              }
            }
          }
        },
        input: {
          attrList: ['finalGoodsCost', 'shopDivisionMoney', 'offlinePaidAmount', 'partnerFeeCalculateCoefficient', 'secondPartnerFee', 'remark'],
          defaultConf: {
            // 流量方-商品成本
            finalGoodsCost: {
              source: 'ORDER_PACKAGE',
              rule: (value, rowIndex) => {
                const totalPaymentObj = this.tmplFieldsList.find(item => item.fieldCode == 'totalPaymentAmount')
                var errorTxt = ''
                const min = 0
                const max = Math.abs(this.tableList[rowIndex][totalPaymentObj.extInfo.source].totalPaymentAmount || 0).toFixed(2)
                if (value > max || value < min) {
                  errorTxt = `请输入${min}-${max}的数字`
                } else if (value !== null && value !== undefined && value !== '') {
                  const decimalPart = String(value).split('.')[1]
                  if (decimalPart && decimalPart.length > 2) {
                    errorTxt = '最多只能输入两位小数'
                  }
                }
                return errorTxt
              }
            },
            // 流量方总金额
            shopDivisionMoney: {
              source: 'ORDER',
              rule: (value, rowIndex) => {
                const totalPaymentObj = this.tmplFieldsList.find(item => item.fieldCode == 'totalPaymentAmount')
                const orderList = this.tableList.filter(item => item.ORDER.id == this.tableList[rowIndex].ORDER.id)
                var errorTxt = ''
                let max = 0
                let min = 0
                orderList.forEach(item => {
                  max = max + item[totalPaymentObj.extInfo.source].totalPaymentAmount
                })
                max = Math.abs(max).toFixed(2)
                min = parseFloat((max * -1)).toFixed(2)
                if (value > max || value < min) {
                  errorTxt = `请输入${min}-${max}的数字`
                } else if (value !== null && value !== undefined && value !== '') {
                  const decimalPart = String(value).split('.')[1]
                  if (decimalPart && decimalPart.length > 2) {
                    errorTxt = '最多只能输入两位小数'
                  }
                }
                return errorTxt
              }
            },
            // 线下已付金额
            offlinePaidAmount: {
              source: 'ORDER',
              rule: (value, rowIndex) => {
                const totalPaymentObj = this.tmplFieldsList.find(item => item.fieldCode == 'totalPaymentAmount')
                const orderList = this.tableList.filter(item => item.ORDER.id == this.tableList[rowIndex].ORDER.id)
                var errorTxt = ''
                var min = 0
                var max = 0
                orderList.forEach(item => {
                  max = max + item[totalPaymentObj.extInfo.source].totalPaymentAmount
                })
                max = Math.abs(max).toFixed(2)
                min = parseFloat((max * -1)).toFixed(2)
                if (value < min || value > max) {
                  errorTxt = `请输入${min}-${max}的数字`
                } else if (value !== null && value !== undefined && value !== '') {
                  const decimalPart = String(value).split('.')[1]
                  if (decimalPart && decimalPart.length > 2) {
                    errorTxt = '最多只能输入两位小数'
                  }
                }
                return errorTxt
              }
            },
            // 按新政策标准
            partnerFeeCalculateCoefficient: {
              source: 'SUB_ORDER',
              prepend: '分润系数*',
              rule: (value) => {
                var errorTxt = ''
                const min = 0
                const max = 1
                if (value < min || value > max) {
                  errorTxt = `请输入${min}-${max}的数字`
                } else if (value !== null && value !== undefined && value !== '') {
                  const decimalPart = String(value).split('.')[1]
                  if (decimalPart && decimalPart.length > 2) {
                    errorTxt = '最多只能输入两位小数'
                  }
                }
                return errorTxt
              }
            },
            // 服务商对账单 - 服务商2
            secondPartnerFee: {
              source: 'SUB_ORDER',
              rule: (value) => {
                var errorTxt = ''
                const min = -999999
                const max = 999999
                if (value < min || value > max) {
                  errorTxt = `请输入${min}-${max}的数字`
                } else if (value !== null && value !== undefined && value !== '') {
                  const decimalPart = String(value).split('.')[1]
                  if (decimalPart && decimalPart.length > 2) {
                    errorTxt = '最多只能输入两位小数'
                  }
                }
                return errorTxt
              }
            },
            // 备注
            remark: {
              source: 'ORDER',
              inputType: 'text',
              maxlength: 50,
              rule: (value) => {
                var errorTxt = ''
                return errorTxt
              }
            }
          }
        },
        selectInput: {
          attrList: ['SUB_ORDERtrafficFeeCalculateType,trafficFeeCalculateValue', 'SUB_ORDERpartnerFeeCalculateType,partnerFeeCalculateValue'],
          defaultConf: {
            'trafficFeeCalculateType,trafficFeeCalculateValue': {
              optionId: 'confId',
              optionLabel: 'confValue',
              optionList: [
                { confId: 1, confValue: '按毛利' },
                { confId: 2, confValue: '按收入' },
                { confId: 3, confValue: '按固定金额' }
              ],
              source: 'SUB_ORDER',
              suffixFn: (rowIndex, source, selectField, inputField, isBatch = false) => {
                const suffixObj = {
                  1: '%',
                  2: '%',
                  3: '元'
                }
                var suffix = ''
                const obj = isBatch ? this.batchForm : this.tableList[rowIndex][source]
                suffix = suffixObj[obj[selectField]] || ''
                return suffix
              },
              rule: (value, rowIndex, source, headObj, isBatch = false) => {
                var errorTxt = ''
                const obj = isBatch ? this.batchForm : this.tableList[rowIndex][source]
                const typeVal = obj[headObj.editObj.selectField] || ''
                const inputVal = obj[headObj.editObj.inputField] || ''
                switch (typeVal) {
                  case 1:
                    if (inputVal < 0 || inputVal > 100) {
                      errorTxt = '请输入0-100的数字'
                    }
                    break
                  case 2:
                    if (inputVal < 0 || inputVal > 100) {
                      errorTxt = '请输入0-100的数字'
                    }
                    break
                  case 3:
                    if (inputVal < 0 || inputVal > 999999) {
                      errorTxt = '请输入0-999999的数字'
                    }
                    break
                }
                if (inputVal !== null && inputVal !== undefined && inputVal !== '') {
                  // 检查是否包含多个小数点
                  if ((inputVal.toString().match(/\./g) || []).length > 1) {
                    errorTxt = '只能输入一个小数点'
                  } else {
                    const decimalPart = String(inputVal).split('.')[1]
                    if (decimalPart && decimalPart.length > 2) {
                      errorTxt = '最多只能输入两位小数'
                    }
                  }
                }
                return errorTxt
              }
            },
            'partnerFeeCalculateType,partnerFeeCalculateValue': {
              optionId: 'confId',
              optionLabel: 'confValue',
              optionList: [
                { confId: 1, confValue: '按毛利' },
                { confId: 2, confValue: '按收入' },
                { confId: 3, confValue: '按固定金额' }
              ],
              source: 'SUB_ORDER',
              suffixFn: (rowIndex, source, selectField, inputField, isBatch = false) => {
                const suffixObj = {
                  1: '%',
                  2: '%',
                  3: '元'
                }
                var suffix = ''
                const obj = isBatch ? this.batchForm : this.tableList[rowIndex][source]
                suffix = suffixObj[obj[selectField]] || ''
                return suffix
              },
              rule: (value, rowIndex, source, headObj, isBatch = false) => {
                var errorTxt = ''
                const obj = isBatch ? this.batchForm : this.tableList[rowIndex][source]
                const typeVal = obj[headObj.editObj.selectField]
                const inputVal = obj[headObj.editObj.inputField]
                switch (typeVal) {
                  case 1:
                    if (inputVal < 0 || inputVal > 100) {
                      errorTxt = '请输入0-100的数字'
                    }
                    break
                  case 2:
                    if (inputVal < 0 || inputVal > 100) {
                      errorTxt = '请输入0-100的数字'
                    }
                    break
                  case 3:
                    if (inputVal < 0 || inputVal > 999999) {
                      errorTxt = '请输入0-999999的数字'
                    }
                    break
                }
                if (inputVal !== null && inputVal !== undefined && inputVal !== '') {
                  // 检查是否包含多个小数点
                  if ((inputVal.toString().match(/\./g) || []).length > 1) {
                    errorTxt = '只能输入一个小数点'
                  } else {
                    const decimalPart = String(inputVal).split('.')[1]
                    if (decimalPart && decimalPart.length > 2) {
                      errorTxt = '最多只能输入两位小数'
                    }
                  }
                }
                return errorTxt
              }
            }
          }
        }
      },
      changeFieldCodeList: [{
        old: 'platformMerchantName',
        new: 'platformMerchantId'
      }],
      baseData: {
        PlatformMerchantList: [],
        recvTypeList: [{
          confId: 1,
          confLabel: "微信支付"
        },
        {
          confId: 2,
          confLabel: "4S店支付"
        },
        {
          confId: 3,
          confLabel: "POS机收款"
        },
        {
          confId: 4,
          confLabel: "支付宝支付"
        },
        {
          confId: 5,
          confLabel: "嘀加收款"
        },
        {
          confId: 6,
          confLabel: "对公转账"
        },
        {
          confId: 7,
          confLabel: "其他收款"
        }],
        payTypeList: payTypeList,
        trafficFeeCalculateTypeList: [{
          confId: 1,
          confValue: '按毛利'
        },
        {
          confId: 2,
          confValue: '按收入'
        },
        {
          confId: 3,
          confValue: '按固定金额'
        }],
        trafficFeeCalculateTypeTxtList: [{
          confId: 1,
          confLabel: '按毛利',
          suffix: '%'
        },
        {
          confId: 2,
          confLabel: '按收入',
          suffix: '%'
        },
        {
          confId: 3,
          confLabel: '按固定金额',
          suffix: '元'
        }, {
          confId: 4,
          confLabel: '按(产值-流量成本)比例',
          suffix: '%'
        },
        {
          confId: 5,
          confLabel: '按(产值-流量成本-其他费用不包含成本)比例',
          suffix: '%'
        },
        {
          confId: 6,
          confLabel: '按(产值-流量成本-其他费用包含成本)比例',
          suffix: '%'
        }, {
          confId: 7,
          confLabel: '可扩展兜底',
          suffix: ''
        },
        {
          confId: 8,
          confLabel: '按(收入-自定义其他费用)比例',
          suffix: '%'
        },
        {
          confId: 9,
          confLabel: '按(收入-其他费用)比例',
          suffix: '%'
        },
        {
          confId: 10,
          confLabel: '按固定金额*购买数量',
          suffix: '元'
        }],
        // 流量方对账单
        trafficTemplateList: [],
        // 服务商对账单
        serviceTemplateList: [],
        goodsList: []
      },
      defaultWidth: '180px',
      localTmplList: deepClone(localTmplList),
      infoForm: {
        templateId: '',
        fieldsJson: '',
        fieldsTxt: ''
      },
      formRules: {
        templateId: [{ required: false, message: '请选择对账模式', trigger: 'change' }],
        fieldsJson: [{ required: false, message: '请选择对账字段', trigger: 'change' }]
      },
      tmplSelectList: [],
      tmplDrawerVisible: false,
      tmplInfo: {
        type: '',
        tmplSelectList: []
      },
      // 选择退款订单
      chooseVisible: '',
      refundInfo: {}
    }
  },
  mounted() {
    this.initComponent()
  },
  methods: {
    initComponent() {
      this.billTypeStr = this.billTmplInfo.billType == '1' ? 'traffic' : 'service'
      console.log(this.billTmplInfo, 'this.billTmplInfo---')
      this.dateStr = Util.dateFormate(this.billTmplInfo.startDate, 'YYYY年MM月DD日') + '~' + Util.dateFormate(this.billTmplInfo.endDate, 'YYYY年MM月DD日')
      this.tmplFieldsList = JSON.parse(this.billTmplInfo.fixedFieldsJson)
      console.log(this.tmplFieldsList, 'this.tmplFieldsList---')
      this.originalOrderList = this.billTmplInfo?.orderPage?.list || []
      this.orderId = this.billTmplInfo.id
      this.sceneType = this.billTmplInfo.sceneType
      this.totalAmount = this.billTmplInfo.totalAmount
      this.totalOrderCount = this.billTmplInfo.totalOrderCount
      this.totalReceivable = this.billTmplInfo.totalReceivable
      this.totalPayable = this.billTmplInfo.totalPayable
      this.totalSplitPaidAmount = this.billTmplInfo.totalSplitPaidAmount
      this.totalOfflinePaidAmount = this.billTmplInfo.totalOfflinePaidAmount
      this.totalOfflineReconciliation = this.billTmplInfo.totalOfflineReconciliation
      this.infoForm.tmplType = this.billTmplInfo.billType
      this.infoForm.templateId = this.billTmplInfo.templateId || 'all'
      this.infoForm.fieldsJson = JSON.parse(this.billTmplInfo.fieldsJson)
      this.tmplSelectList = this.infoForm.fieldsJson.map(i => i.id)
      this.infoForm.fieldsTxt = this.getFieldsTxt()
      // this.page.pageNum = this.billTmplInfo?.orderPage?.pageNum || 1
      // this.page.pageSize = this.billTmplInfo?.orderPage?.pageSize || 10
      this.page.total = this.billTmplInfo?.orderPage?.total || 0
      this.receivableAdjustments = this.billTmplInfo?.receivableAdjustments || []
      this.payableAdjustments = this.billTmplInfo?.payableAdjustments || []
      this.orderTotalStat = this.billTmplInfo.orderTotalStat
      this.getTmplList()
      this.getPlatformMerchantList()
      this.dealTable()
    },
    getTmplList() {
      const params = {
        pageSize: 9999,
        currentPage: 1
      }
      // 流量方
      getTmplList({ ...params, type: 1 }).then(res => {
        this.baseData.trafficTemplateList = res.list || []
        this.baseData.trafficTemplateList.unshift({
          id: 'all',
          type: 1,
          templateName: '无',
          fieldNames: '',
          fieldIds: []
        })
      })
      // 服务商
      getTmplList({ ...params, type: 2 }).then(res => {
        this.baseData.serviceTemplateList = res.list || []
        this.baseData.serviceTemplateList.unshift({
          id: 'all',
          type: 2,
          templateName: '无',
          fieldNames: '',
          fieldIds: []
        })
      })
    },

    handleTmplChange(e) {
      const item = this.baseData[this.billTypeStr + 'TemplateList'].find(item => item.id == e)
      this.infoForm.fieldsTxt = item?.fieldNames
      this.infoForm.tmplType = item?.type
      this.tmplSelectList = item?.fieldIds
      this.getMetaTmpl()
    },

    getMetaTmpl() {
      const tmplName = this.localTmplList.find(item => item.type == this.infoForm.tmplType)?.name || 'trafficTmpl'
      var list = JSON.parse(localStorage.getItem(tmplName))
      if (list) {
        this.dealFieldsJson(list)
      } else {
        getMetaTmpl({ type: this.infoForm.tmplType }).then(res => {
          this.dealFieldsJson(res)
          localStorage.setItem(tmplName, JSON.stringify(res))
        })
      }
    },

    dealFieldsJson(list, isFindTxt = false) {
      this.tmplList = []
      this.moduleSubList = []
      this.selectedList = []
      list.forEach(item => {
        const subLen = this.moduleSubList.length
        this.moduleSubList.push({
          rowIdx: subLen ? this.moduleSubList[subLen - 1].rowIdx + this.moduleSubList[subLen - 1].rowspan : item.items.length - 1,
          rowspan: item.items.length
        })
        this.tmplList = this.tmplList.concat(item.items)
        item.items.forEach(k => {
          if (k.required == 1) {
            this.selectedList.push(k)
          } else if (this.tmplSelectList.includes(k.id)) {
            this.selectedList.push(k)
          }
        })
      })
      this.$nextTick(() => {
        isFindTxt && (this.infoForm.fieldsTxt = this.selectedList.map(item => item.fieldName).join(','))
        this.infoForm.fieldsJson = JSON.stringify(this.selectedList)
      })
    },

    getFieldsTxt() {
      // var fieldNames = ''
      const tmplName = this.localTmplList.find(item => item.type == this.infoForm.tmplType)?.name || 'trafficTmpl'
      var list = JSON.parse(localStorage.getItem(tmplName))
      if (list) {
        this.dealFieldsJson(list, true)
      } else {
        getMetaTmpl({ type: this.infoForm.tmplType }).then(res => {
          this.dealFieldsJson(res, true)
          localStorage.setItem(tmplName, JSON.stringify(res))
        })
      }
    },

    handleCustVisible() {
      this.tmplDrawerVisible = !this.tmplDrawerVisible
    },

    handleCustTmpl() {
      this.tmplInfo.type = this.billTmplInfo.billType + ''
      this.tmplInfo.tmplSelectList = this.tmplSelectList || []
      this.handleCustVisible()
    },

    handleCustConfirm(obj) {
      this.handleCustVisible()
      this.tmplSelectList = obj?.fieldIds || []
      this.infoForm.fieldsTxt = this.getFieldsTxt()
      this.getMetaTmpl()
    },

    hasError(rowIndex, source, field) {
      if (['payType'].includes(field)) {
        return false
      }
      return this.validationErrors[`${rowIndex}_${source}_${field}`] !== undefined
    },

    getErrorMessage(rowIndex, source, field) {
      if (['payType'].includes(field)) {
        return false
      }
      return this.validationErrors[`${rowIndex}_${source}_${field}`]
    },

    uniqueByProperty(arr, prop) {
      return arr.filter((obj, index, self) =>
        index === self.findIndex((o) => o[prop] === obj[prop])
      )
    },

    // 用于处理修改过的主订单(标记修改过的主订单),并放入tableModifyList中,调测算/提交接口时,作为updatedOrders传给后端。
    dealModify(rowIndex, source, field) {
      const id = this.tableList[rowIndex].ORDER.id
      const isExitIdx = this.tableModifyList.findIndex(item => item.id == id)
      var orders = {}
      if (isExitIdx != -1) {
        this.tableModifyList.splice(isExitIdx, 1)
      }
      var addList = []
      this.tableList.forEach(item => {
        if (item.ORDER.id == id) {
          addList.push(item)
        }
      })
      var orders = deepClone(this.uniqueByProperty(addList.map(item => item.ORDER), 'id'))
      addList.forEach((item, idx) => {
        let packages = {
          ...item.PACKAGE,
          subOrders: []
        }
        if (item.subRowSpan) {
          for (let i = 0; i < item.subRowSpan; i++) {
            packages.subOrders.push(addList[idx + i].SUB_ORDER)
          }
          let orderIdx = orders.findIndex(k => k.id == item.ORDER.id)
          if (!orders[orderIdx].hasOwnProperty('packages')) {
            orders[orderIdx].packages = []
          }
          orders[orderIdx].packages.push(deepClone(packages))
        }
      })
      this.tableModifyList.push(...orders)
    },

    // 用户修改-新增
    modifyAdd(rowIndex, source, field, fieldConfig) {
      this.dealModify(rowIndex, source, field)
      this.billCompute(rowIndex, source, field, fieldConfig)
    },

    // 用户修改-删除(用于标记用户删除的主订单),并放入tableDeleteList中,调测算/提交接口时,作为excludeBillOrderCodes传给后端。
    modifyDelete(id) {
      const isExitIdx = this.tableModifyList.findIndex(item => item.id == id)
      if (isExitIdx != -1) {
        this.tableModifyList.splice(isExitIdx, 1)
      }
      this.tableDeleteList.push(id)
      this.billCompute()
    },

    // 测算
    billCompute(rowIndex, source, field, fieldConfig) {
      if (field) {
        this.validateField(rowIndex, source, field, fieldConfig)
      }
      this.billComputePage()
    },

    getSearchForm() {
      const params = deepClone(this.searchForm)
      const dateFormatList = [{
        attr: 'paymentTime',
        startAttr: 'paymentTimeStart',
        endAttr: 'paymentTimeEnd'
      }]
      dateFormatList.forEach(item => {
        if (params[item.attr] && params[item.attr].length) {
          params[item.startAttr] = Util.dateFormate(params[item.attr][0], 'YYYY-MM-DD 00:00:00')
          params[item.endAttr] = Util.dateFormate(params[item.attr][1], 'YYYY-MM-DD 23:59:59')
          delete params[item.attr]
        }
      })
      return params
    },
    billComputePage(noChangeFixedSum = false, fn = null) {
      console.log(this.tableList, 'this.tableList---')
      this.loading = true
      console.log(this.tableModifyList, 'this.tableModifyList----')
      const searchParams = this.getSearchForm()
      const dynamicForm = {
        id: this.orderId,
        updatedOrders: deepClone(this.tableModifyList),
        // excludeBillOrderCodes: deepClone(this.tableDeleteList),
        orderIdList: deepClone(this.tableDeleteList),
        receivableAdjustments: this.$refs.dynamicReceiveAdd?.dynamicForm.tableData || [],
        payableAdjustments: this.$refs.dynamicAdd.dynamicForm.tableData,
        ...searchParams
        // orderCurrentPage: this.page.pageNum,
        // orderPageSize: this.page.pageSize
      }
      billComputePage({ json: JSON.stringify(dynamicForm) }).then(res => {
        this.originalOrderList = res.orderPage?.list || []
        this.totalAmount = res.totalAmount
        if (!noChangeFixedSum) {
          this.totalOrderCount = res.totalOrderCount
          this.totalReceivable = res.totalReceivable
          this.totalPayable = res.totalPayable
          this.totalPayable = res.totalPayable
          this.totalSplitPaidAmount = res.totalSplitPaidAmount
          this.totalOfflinePaidAmount = res.totalOfflinePaidAmount
          this.totalOfflineReconciliation = res.totalOfflineReconciliation
        }
        this.orderTotalStat = res.orderTotalStat
        // this.page.pageNum = res.orderPage?.pageNum || 1
        // this.page.pageSize = res.orderPage?.pageSize || 10
        this.page.total = res.orderPage?.total || 0
        this.dealTableData(fn)
      }).finally(() => {
        this.loading = false
      })
    },

    validateField(rowIndex, source, field, fieldConfig) {
      const value = this.tableList[rowIndex][source][field]
      // const headObj = this.tmplFieldsList.find(i => i.fieldCode == field)
      var key = `${rowIndex}_${source}_${field}`
      // console.log(rowIndex, source, field, fieldConfig, '0000000')
      if (this.judgeDisable(rowIndex, source, fieldConfig)) {
        return true
      }
      if (['remark'].includes(fieldConfig.fieldCode)) {
        return true
      }
      if (fieldConfig?.editType === 'selectInput') {
        const obj = this.tableList[rowIndex][source]
        const selectVal = obj[fieldConfig.editObj.selectField]
        const inputVal = obj[fieldConfig.editObj.inputField]
        if (selectVal === undefined || selectVal === null || selectVal === '') {
          this.$set(this.validationErrors, `${rowIndex}_${source}_${fieldConfig.editObj.selectField}`, '此项为必填项')
          return false
        }
        if (inputVal === undefined || inputVal === null || inputVal === '') {
          this.$set(this.validationErrors, `${rowIndex}_${source}_${fieldConfig.editObj.inputField}`, '此项为必填项')
          return false
        }
      } else if (value === undefined || value === null || value === '') {
        this.$set(this.validationErrors, key, '此项为必填项')
        return false
      }

      if (fieldConfig?.editObj?.rule) {
        let errorTxt = fieldConfig.editObj.rule(value, rowIndex, source, fieldConfig.editType == 'selectInput' ? fieldConfig : field)
        if (errorTxt) {
          if (fieldConfig.editType === 'selectInput') {
            this.$set(this.validationErrors, `${rowIndex}_${source}_${fieldConfig.editObj.inputField}`, errorTxt)
          } else {
            this.$set(this.validationErrors, key, errorTxt)
          }
          return false
        }
      }

      // 验证通过,清除错误
      if (this.validationErrors[key]) {
        this.$delete(this.validationErrors, key)
      }
      return true
    },

    validateForm() {
      let isValid = true
      this.validationErrors = {}
      const noValidList = ['remark']
      this.tableList.forEach((row, rowIndex) => {
        Object.keys(row).forEach(source => {
          Object.keys(row[source]).forEach(field => {
            const fieldConfig = this.getFieldConfig(field, source)
            // let headObj = this.tmplFieldsList.find(i => i.fieldCode == field)
            if (!noValidList.includes(field) && fieldConfig && this.isEditableField(fieldConfig, field)) {
              if (!this.validateField(rowIndex, source, field, fieldConfig)) {
                isValid = false
              }
            }
          })
        })
      })

      return isValid
    },

    getFieldConfig(field, source) {
      return this.tmplFieldsList.find(item =>
        (item.fieldCode === field ||
          (item.editType === 'selectInput' &&
            (item.editObj.selectField === field || item.editObj.inputField === field))) &&
        (item.extInfo?.source || 'ORDER') === source
      )
    },

    isEditableField(fieldConfig, field) {
      return this[this.billTypeStr + 'EditList'].some(editField =>
        editField === field ||
        (fieldConfig.editType === 'selectInput' &&
          (editField.includes(fieldConfig.editObj.selectField) ||
            editField.includes(fieldConfig.editObj.inputField))))
    },

    handleSelectChange(val, rowIndex, fieldConfig) {
      if (fieldConfig.editObj.fn) {
        fieldConfig.editObj.fn(val, rowIndex, fieldConfig)
      }
      this.validateField(rowIndex, fieldConfig.extInfo.source || 'ORDER', fieldConfig.fieldCode, fieldConfig)
    },

    handleSelectInputChange(rowIndex, fieldConfig, isApi = true) {
      const source = fieldConfig.extInfo.source || 'ORDER'
      this.validateField(rowIndex, source, fieldConfig.editObj.selectField, fieldConfig)
      this.validateField(rowIndex, source, fieldConfig.editObj.inputField, fieldConfig)
      isApi && this.modifyAdd(rowIndex, source, fieldConfig.fieldCode, fieldConfig)
    },

    // 选择退款订单
    changeChooseVisible() {
      this.chooseVisible = !this.chooseVisible
    },

    handleChooseRefundOrder() {
      this.refundInfo = {
        sceneType: this.sceneType,
        shopMerchantId: this.billTmplInfo.shopMerchantId
      }
      this.changeChooseVisible()
    },

    transferRefundOrder(orderCodeScope) {
      const params = {
        id: this.orderId,
        updatedOrders: []
      }
      orderCodeScope.forEach(item => {
        params.updatedOrders.push({
          orderCode: item.orderCode,
          shopDivisionMoney: item.shopDivisionMoneyInput
        })
      })
      this.loading = true
      mergeRefundOrder(params).then(res => {
        console.log(res, 'res---')
        // this.refundOrderList = deepClone(res)
        // this.tableModifyList = this.refundOrderList
        this.handleResetSearch()
        this.isFirst = true
        this.billComputePage()
      }).finally(() => {
        this.loading = false
      })
    },

    chooseOrderConfirm(orderCodeScope) {
      console.log(orderCodeScope, 'orderCodeScope---')
      // this.infoForm.orderCodeScope = orderCodeScope
      this.transferRefundOrder(orderCodeScope)
      this.changeChooseVisible()
    },

    // 筛选项弹窗
    searchDialogVisible() {
      this.searchVisible = !this.searchVisible
    },

    handleResetSearch() {
      this.searchForm = {
        orderCodeKeyword: '',
        customerName: '',
        tradeNoKeyword: '',
        goodsNameList: '',
        paymentTime: '',
        payTypeList: ''
      }
    },

    handleOpenSearch(obj) {
      this.headObj = this.tmplFieldsList[obj.$index]
      const fieldCode = this.headObj.fieldCode
      const extInfo = this.headObj.extInfo
      const itemObj = this.searchAttrObj[fieldCode]
      console.log(this.headObj)
      this.searchEditFormData = [deepClone(itemObj.editFormData)]
      if (fieldCode == 'goodsName') {
        this.baseData.goodsList = []
        const list = this.ownOrderList
        list.forEach(item => {
          if (!this.baseData.goodsList.map(i => i.confId).includes(item[extInfo.source][fieldCode])) {
            this.baseData.goodsList.push({
              confId: item[extInfo.source][fieldCode],
              confLabel: item[extInfo.source][fieldCode]
            })
          }
        })
      }
      this.searchDialogVisible()
    },

    handleSearchConfirm() {
      this.validationErrors = {}
      this.searchDialogVisible()
      // console.log(this.searchForm, 'searchform')
      this.billComputePage(true)
    },

    handleConfirm() {
      this.handleResetSearch()
      this.isFirst = true
      this.billComputePage(false, () => {
        const validFlag = this.billTypeStr == 'traffic' ? (this.$refs.dynamicReceiveAdd.validateForm() && this.$refs.dynamicAdd.validateForm()) : this.$refs.dynamicAdd.validateForm()
        if (this.validateForm() && validFlag) {
          const dynamicForm = {
            id: this.orderId,
            updatedOrders: deepClone(this.tableModifyList),
            orderIdList: deepClone(this.tableDeleteList),
            receivableAdjustments: this.$refs.dynamicReceiveAdd?.dynamicForm.tableData || [],
            payableAdjustments: this.$refs.dynamicAdd?.dynamicForm.tableData || [],
            sceneType: this.sceneType,
            templateId: this.infoForm.templateId == 'all' ? '' : this.infoForm.templateId,
            fieldsJson: this.infoForm.fieldsJson
          }
          // console.log(dynamicForm, 'dynamicForm')
          this.loading = true
          editBillPage({ json: JSON.stringify(dynamicForm) }).then(res => {
            this.$message.success("操作成功")
            this.$emit('handleConfirm')
          }).finally(() => {
            this.loading = false
          })
        } else {
          this.$message.error('请检查表单中的报错项')
        }
      })
    },

    handleClose() {
      this.$emit('handleClose')
    },

    getPlatformMerchantList() {
      getPlatformMerchantList({}).then(res => {
        res.unshift({
          merchantId: -1,
          merchantName: '嘀加智慧云'
        })
        this.baseData.PlatformMerchantList = res
      })
    },

    // 处理动态表头信息,并将该列字段的特有属性写入,方便对表格里面的项做处理
    dealTable() {
      this.tableHeader = []
      const moduleList = [...new Set(this.tmplFieldsList.map(item => item.moduleName))]
      const changeCodeOldList = this.changeFieldCodeList.map(item => item.old)
      const editList = this[this.billTypeStr + 'EditList']
      const txtList = this[this.billTypeStr + 'ChangeTxtList']

      moduleList.forEach(item => {
        let list = this.tmplFieldsList.filter(k => k.moduleName == item)
        list.forEach(k => {
          k.extInfo = JSON.parse(k.extInfo)
          let codeIdx = changeCodeOldList.findIndex(m => m == k.fieldCode)
          if (codeIdx != -1 && editList.includes(this.changeFieldCodeList[codeIdx].new)) {
            k.fieldCode = this.changeFieldCodeList[codeIdx].new
          }

          if (editList.includes(k.fieldCode)) {
            if (this.editObj.select.attrList.includes(k.fieldCode)) {
              k.editType = 'select'
              k.width = '120px'
              k.editObj = {
                ...this.editObj.select.defaultConf[k.fieldCode],
                width: '110px'
              }
            }
            if (this.editObj.input.attrList.includes(k.fieldCode)) {
              k.editType = 'input'
              k.inputType = this.editObj.input.defaultConf[k.fieldCode].inputType || 'number'
              k.maxlength = this.editObj.input.defaultConf[k.fieldCode].maxlength || ''
              k.width = '100px'
              k.editObj = {
                ...this.editObj.input.defaultConf[k.fieldCode],
                width: '90px'
              }
              if (k.fieldCode == 'partnerFeeCalculateCoefficient') {
                k.width = '180px'
                // k.editObj.width = '110px'
              }
            }
            if (this.editObj.selectInput.attrList.includes(k.extInfo.source + k.fieldCode)) {
              k.editType = 'selectInput'
              k.editObj = {
                selectField: k.fieldCode.split(',')[0],
                inputField: k.fieldCode.split(',')[1],
                inputType: 'number',
                ...this.editObj.selectInput.defaultConf[k.fieldCode]
              }
              k.width = '193px'
            }
          } else {
            const widthObj = {
              serialNo: '40px',
              orderCode: '86px',
              customerName: '74px'
            }
            k.width = widthObj[k.fieldCode] || '80px'
          }

          const txtObj = txtList.find(m => (m.source + m.attr) == (k.extInfo.source + k.fieldCode))
          if (txtObj) {
            if (txtObj.type == 'selectInput') {
              k.txtType = 'selectInput'
              k.txtObj = {
                selectField: k.fieldCode.split(',')[0],
                inputField: k.fieldCode.split(',')[1]
              }
            }
          }
        })
        this.tableHeader.push({
          moduleName: item,
          items: list
        })
      })
      // console.log(this.tableHeader, 'v---')
      this.dealTableData()
    },

    // 处理表格里面的数据,需结合表头这个字段的特有属性进行处理
    dealTableData(fn = null) {
      this.tableList = []
      let serialNo = 0
      const txtList = this[this.billTypeStr + 'ChangeTxtList']
      this.originalOrderList.forEach(item => {
        let { packages, ...orderOtherObj } = item
        serialNo = serialNo + 1
        let subLen = 0
        let subFirstIdx = 0
        item.packages.forEach((k, kIdx) => {
          let { subOrders, ...packagesOtherObj } = k
          k.subOrders.forEach((m, mIdx) => {
            this.tableList.push({
              ORDER: deepClone({ ...orderOtherObj, serialNo: serialNo }),
              PACKAGE: deepClone(packagesOtherObj),
              SUB_ORDER: deepClone(m)
            })
            let targetIdx = this.tableList.length - 1
            if (kIdx == 0 && mIdx == 0) {
              subFirstIdx = targetIdx
            }
            if (mIdx == 0) {
              // 行合并
              this.tableList[targetIdx].subRowSpan = k.subOrders.length
              subLen = subLen + k.subOrders.length
            } else {
              this.tableList[targetIdx].subRowSpan = 0
            }
          })
        })
        this.tableList[subFirstIdx].packRowSpan = subLen
      })
      this.tableList.forEach(item => {
        txtList.forEach(m => {
          if (m.type == 'select') {
            item[m.source][m.attr] = this.baseData[m.optionsName].find(n => n[m.optionId] == item[m.source][m.attr])?.[m.optionLabel] || '-'
          } else if (m.type == 'selectInput') {
            const source = m.source
            const selectField = m.attr.split(',')[0]
            const inputField = m.attr.split(',')[1]
            const selectObj = this.baseData[selectField + 'TxtList'].find(n => n[m.optionId] == item[m.source][selectField])
            const selectTxt = selectObj?.[m.optionLabel]
            item[m.source][selectField] = selectTxt || ''
            item[m.source][inputField] = item[m.source][inputField] + selectObj?.suffix
          } else if (m.type == 'time') {
            item[m.source][m.attr] = item[m.source][m.attr] ? Util.dateFormate(item[m.source][m.attr], 'YYYY-MM-DD HH:mm:ss') : '-'
          }
        })
      })
      if (this.isFirst) {
        this.ownOrderList = deepClone(this.tableList)
        this.isFirst = false
      }
      if (fn) {
        fn()
      }
      // console.log(this.originalOrderList, 'this.originalOrderList----')
      // console.log(this.tableList, 'this.tableList---')
    },

    // 判断是否不可编辑
    judgeDisable(rowIndex, source, fieldConfig) {
      const value = this.tableList[rowIndex]
      var isDisable = false
      if (!fieldConfig) {
        return isDisable
      }
      /**
       * 流量方 - traffic;服务商 - service
       * sourceType:1-订单;2-退款
       * 流量方 && 退款:流量方品类比例不能编辑
       *  */
      if (this.billTypeStr == 'traffic' && value.ORDER.sourceType != 1) {
        if (['SUB_ORDERtrafficFeeCalculateType,trafficFeeCalculateValue'].includes(source + fieldConfig.fieldCode)) {
          isDisable = true
        }
      }
      /**
       * 流量方 - traffic;服务商 - service
       * sourceType:1-订单;2-退款
       * 服务商 && 正常订单:服务费2不能编辑
       * 服务商 && 退款:服务商品类比例、按新政策标准不能编辑
       *  */
      if (this.billTypeStr == 'service') {
        if (value.ORDER.sourceType == 1) {
          if (['SUB_ORDERsecondPartnerFee', 'ORDERpayType'].includes(source + fieldConfig.fieldCode)) {
            isDisable = true
          }
        }
        if (value.ORDER.sourceType != 1) {
          if (['SUB_ORDERpartnerFeeCalculateType,partnerFeeCalculateValue', 'SUB_ORDERpartnerFeeCalculateCoefficient', 'ORDERpayType'].includes(source + fieldConfig.fieldCode)) {
            isDisable = true
          }
        }
      }
      /** editable为false,平台方和支付方式不能编辑 */
      // if (value.ORDER.editable == false) {
      //   if (['ORDERplatformMerchantId', 'ORDERpayType'].includes(source + fieldConfig.fieldCode)) {
      //     isDisable = true
      //   }
      // }
      return isDisable
    },
    // 判断表头字段是否可以批量编辑
    judgeImgShow(obj) {
      const list = deepClone(this[this.billTypeStr + 'SourceEditList'])
      const editList = []
      const batchEditAtttrList = ['ORDERplatformMerchantId', 'SUB_ORDERtrafficFeeCalculateType,trafficFeeCalculateValue', 'SUB_ORDERpartnerFeeCalculateType,partnerFeeCalculateValue', 'SUB_ORDERpartnerFeeCalculateCoefficient']
      list.forEach(item => {
        if (batchEditAtttrList.includes(item)) {
          editList.push(item)
        }
      })
      const source = this.tmplFieldsList[obj.$index].extInfo.source
      const fieldCode = this.tmplFieldsList[obj.$index].fieldCode
      return editList.includes(source + fieldCode)
    },

    // 筛选项
    judgeFilterImgShow(obj) {
      const fieldCode = this.tmplFieldsList[obj.$index].fieldCode
      const show = Object.keys(this.searchAttrObj).includes(fieldCode)
      let icon = 'icon-filter'
      if (show) {
        const val = this.searchForm[this.searchAttrObj[fieldCode].editFormData.name]
        icon = ((Array.isArray(val) && val.length) || (!Array.isArray(val) && val)) ? 'icon-filter-check' : 'icon-filter'
      }
      return {
        show,
        icon
      }
    },
    // 批量修改弹窗 - 验证表单
    batchValidateForm() {
      const value = this.batchForm[this.headObj.fieldCode]
      this.dialogErrors = {};
      let isValid = true;

      // 必填校验
      // if (this.headObj.required) {
      if (this.headObj.editType === 'selectInput') {
        const selectVal = this.batchForm[this.headObj.editObj.selectField]
        const inputVal = this.batchForm[this.headObj.editObj.inputField]
        if (selectVal === undefined || selectVal === null || selectVal === '') {
          this.dialogErrors[this.headObj.editObj.selectField] = '请选择';
          isValid = false;
        }
        if (inputVal === undefined || inputVal === null || inputVal === '') {
          this.dialogErrors[this.headObj.editObj.inputField] = '请输入';
          isValid = false;
        }
      } else if (value === undefined || value === null || value === '') {
        this.dialogErrors[this.headObj.fieldCode] = this.headObj.editType === 'select' ? '请选择' : '请输入';
        isValid = false;
      }
      // }
      if (this.headObj?.editObj?.rule) {
        let errorTxt = this.headObj.editObj.rule(value, '', '', this.headObj.editType == 'selectInput' ? this.headObj : this.headObj.fieldCode, true)
        if (errorTxt) {
          isValid = false;
          if (this.headObj.editType === 'selectInput') {
            this.dialogErrors[this.headObj.editObj.inputField] = errorTxt;
          } else {
            this.dialogErrors[this.headObj.fieldCode] = errorTxt;
          }
          return false
        }
      }
      return isValid;
    },
    closeImgViewer() {
      this.imgVisible = false
    },
    handleReviewImg(row) {
      this.imgList = []
      row.ORDER.payVoucherList.forEach(item => {
        this.imgList.push(item.payVoucher)
      })
      if (!this.imgList.length) {
        return true
      }
      this.imgVisible = !this.imgVisible
    },
    handlePreviewClose() {
      console.log(111)
    },
    handelBatchVisible() {
      this.batchVisible = !this.batchVisible
    },
    handleBatchClose() {
      this.dialogErrors = {}
      this.handelBatchVisible()
      this.headObj = {}
    },
    handleBatchConfirm() {
      // console.log(this.multipleSelecList)
      let idList = this.multipleSelecList.map(item => item.ORDER.id)
      if (this.batchValidateForm()) {
        this.tableList.forEach((item, idx) => {
          if (idList.includes(item.ORDER.id)) {
            // let exitEditable = this.headObj.editObj?.hasOwnProperty('editableAttr') || false
            let editable = !this.judgeDisable(idx, this.headObj.extInfo.source, this.headObj)
            if (editable) {
              if (this.headObj.editType == 'selectInput') {
                this.tableList[idx][this.headObj.extInfo.source || 'ORDER'][this.headObj.editObj.selectField] = this.batchForm[this.headObj.editObj.selectField]
                this.tableList[idx][this.headObj.extInfo.source || 'ORDER'][this.headObj.editObj.inputField] = this.batchForm[this.headObj.editObj.inputField]
              } else if (this.headObj.editType == 'select') {
                this.tableList[idx][this.headObj.extInfo.source || 'ORDER'][this.headObj.fieldCode] = this.batchForm[this.headObj.fieldCode]
                if (this.headObj.editObj.batchName) {
                  this.tableList[idx][this.headObj.extInfo.source || 'ORDER'][this.headObj.editObj.batchName] =
                    this.baseData[this.headObj.editObj.optionsName]
                      .find(item => item[this.headObj.editObj.optionId] == this.batchForm[this.headObj.fieldCode])?.[this.headObj.editObj.optionLabel]
                }
              } else {
                this.tableList[idx][this.headObj.extInfo.source || 'ORDER'][this.headObj.fieldCode] = this.batchForm[this.headObj.fieldCode]
              }
            }
          }
        })
        var orders = this.uniqueByProperty(this.multipleSelecList.map(item => item.ORDER), 'id')
        orders.forEach((item, idx) => {
          const rowIdx = this.tableList.findIndex(k => k.ORDER.id == item.id)
          this.dealModify(rowIdx, this.headObj.extInfo.source, this.headObj.fieldCode)
        })
        this.$nextTick(() => {
          this.handleBatchClose()
          this.billCompute()
        })
      }
    },
    handleBatch(obj) {
      if (!this.multipleSelecList.length) {
        this.$message.warning('请选择数据');
        return true
      }
      this.headObj = this.tmplFieldsList[obj.$index]
      if (this.headObj.editType == 'selectInput') {
        this.$set(this.batchForm, this.headObj.editObj.selectField, '')
        this.$set(this.batchForm, this.headObj.editObj.inputField, '')
      } else {
        this.$set(this.batchForm, this.headObj.fieldCode, '')
      }
      this.handelBatchVisible()
    },
    // 表格的合计字段,根据后端来的数据写入
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          return;
        }
        if (index === 1) {
          sums[index] = '合计';
          return;
        }
        const headObj = this.tmplFieldsList[index]
        const source = headObj?.extInfo?.source || ''
        switch (source) {
          case 'ORDER':
            sums[index + 1] = this.orderTotalStat[headObj.fieldCode] || '-'
            break;
          case 'PACKAGE':
            sums[index + 1] = this.orderTotalStat.packages[0][headObj.fieldCode] || '-'
            break;
          case 'SUB_ORDER':
            sums[index + 1] = this.orderTotalStat.packages[0].subOrders[0][headObj.fieldCode] || '-'
            break
        }
      });

      return sums;
    },

    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      /** 用于标识数据来源(ORDER、PACKAGE、SUB_ORDER)
       * SUB_ORDER - 无需合并单元格;ORDER、PACKAGE - 需合并单元格
       */
      const source = this.tmplFieldsList.find(item => item.fieldCode == column.property)?.extInfo?.source || 'ORDER'
      if (['PACKAGE'].includes(source)) {
        return {
          rowspan: row.subRowSpan,
          colspan: row.subRowSpan ? 1 : 0
        }
      }
      if (['ORDER'].includes(source)) {
        return {
          rowspan: row.packRowSpan,
          colspan: row.packRowSpan ? 1 : 0
        }
      }
    },

    handleDelete(rowIndex, row) {
      if (this.tableList.length == 1) {
        this.$message.error("至少选择一个")
        return true
      }
      const id = row.ORDER.id
      this.validationErrors = {}
      let list = []
      this.tableList.forEach(item => {
        if (item.ORDER.id != id) {
          list.push(item)
        }
      })
      let ownList = []
      this.ownOrderList.forEach(item => {
        if (item.ORDER.id != id) {
          ownList.push(item)
        }
      })
      this.tableList = deepClone(list)
      this.ownOrderList = deepClone(ownList)
      this.modifyDelete(id)
    },

    // 输入框
    selectAddAttr(val, rowIndex, fieldConfig) {
      this[fieldConfig.editObj.fn(val, rowIndex, fieldConfig)]
      this.handleSelectChange(val, rowIndex, fieldConfig)
      this.modifyAdd(rowIndex, fieldConfig.extInfo.source || 'ORDER', fieldConfig.fieldCode, fieldConfig)
    },

    handleSelectionChange(selection) {
      // 处理选中行变化
      this.multipleSelecList = selection
    },

    handleInputDown(e, rowIndex, source, fieldConfig) {
    },

    maxLengthInput(e, item) {
      // 处理输入长度限制
    }

    // handleSizeChange(value) {
    //   this.page.pageSize = value
    //   this.billCompute()
    // },
    // handleCurrentChange(value) {
    //   this.page.pageNum = value
    //   this.billCompute()
    // },
  }
}
</script>

<style lang="scss" scoped>
::v-deep.bill-drawer {
  .el-drawer__header {
    padding: 0;
    margin: 0;
    border-bottom: 1px solid #e5e5e5;
  }
  .drawer-title {
    height: 26px;
    line-height: 26px;
    color: #333333;
    font-size: 18px;
    padding: 17px 20px;
    font-weight: bold;
  }
}
.privacyDrawer {
  box-sizing: border-box;
  padding: 20px;
  overflow: scroll;
  height: auto;
  max-height: calc(100vh - 148px);
}
.flex {
  display: flex;
  justify-content: space-between;
}

.tmpl-box {
  display: flex;
}
.fields-txt {
  width: 305px;
  display: inline-block;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  margin-right: 8px;
}
.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.refund-img {
  display: inline-block;
  box-sizing: border-box;
  width: 16px;
  height: 16px;
  line-height: 16px;
  // font-size: 8px;
  // padding: 2px;
  border-radius: 3px;
  color: #ffffff;
  margin: 0 2px 0 0;
  // background: linear-gradient(#ff8496 0%, #ff4e61 100%);
}

.el-form-item__error {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: relative;
  top: 0;
  left: 0;
}

.is-error {
  .el-input__inner {
    border-color: #f56c6c;
  }
}

.select-input-container {
  position: relative;

  ::v-deep input[type="number"] {
    padding: 0 16px 0 8px;
  }
  .el-form-item__error {
    position: static;
    margin-top: 2px;
  }

  .input-with-select {
    .el-select {
      &.is-error {
        .el-input__inner {
          border-color: #f56c6c;
        }
      }
    }

    &.is-error {
      .el-input-group__prepend {
        .el-input__inner {
          border-right-color: #f56c6c;
        }
      }
      .el-input__inner {
        border-left-color: #dcdfe6;
      }
    }

    .el-input-group__prepend {
      .el-input__inner {
        font-size: 12px;
      }
    }
  }
}
::v-deep .el-input__suffix .inputSuffix {
  position: absolute;
  left: -12px;
  top: 8px;
  // transition: all 0.3s;
  font-size: 12px;
}
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
::v-deep input::-webkit-outer-spin-button {
  -webkit-appearance: none !important;
}
/*设置number类型的input外观*/
::v-deep input[type="number"] {
  -moz-appearance: textfield;
}
.tb-header-cell {
  box-sizing: border-box;
  text-align: center;
  // white-space: nowrap;
  display: inline-block; /* 或者 inline */
  font-size: 12px;
}
.tb-cell {
  padding: 0;
  text-align: center;
  font-size: 12px;
}
::v-deep .el-table .cell {
  padding: 0px 6px !important;
  text-align: center;
  font-size: 12px;
}

::v-deep .el-select .el-input__inner {
  font-size: 12px;
  padding-left: 8px;
}

::v-deep .el-input__inner {
  font-size: 12px;
  padding: 0 8px;
}

::v-deep .el-select-dropdown__item {
  font-size: 12px;
}

::v-deep .el-table th {
  font-size: 12px;
}

::v-deep .el-table .el-table__header th {
  font-size: 12px;
}
::v-deep .el-table__footer-wrapper tbody td {
  padding: 14px;
  text-align: center;
  font-size: 12px;
}
.total-box {
  display: flex;
  flex-wrap: wrap;
  width: calc(100% - 200px);
  div {
    width: 25%;
    padding: 2px 0;
    // flex: 1;
  }
}
.batch-box {
  text-align: center;
  margin: 10px 36px;
}
.red-txt {
  color: #eb4e4e;
  font-size: 14px;
  margin: 8px 0;
}
.txt-blue {
  cursor: pointer;
  color: #2a58ad;
}
.trade-no {
  position: relative;
}
.pay-voucher-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 83px;
  height: 50px;
  opacity: 1;
}
.footer {
  position: absolute;
  bottom: 0;
  right: 0;
  box-sizing: border-box;
  width: 100%;
  height: 84px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  // text-align: right;
  padding: 0 30px;
  background: #ffffff;
  .btn-box {
    background: #ffffff;
    width: 200px;
    text-align: right;
  }
  .btn {
    height: 32px;
    padding: 8px 20px;
  }
}
</style>