anonTaskCreate.vue 74.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
<route lang="yaml">
  name: anonTaskCreate
</route>

<template>
  <div class="container_wrap full" v-loading="fullscreenLoading" ref="containerRef">
    <div class="content_main">
      <!-- 顶部步骤条, 需根据不同的条件显示不同的步骤 -->
      <div class="top_tool_wrap">
        <StepBar :steps-info="stepsInfo" :style="{ width: stepsInfo.list.length == 2 ? '30%' : '60%' }" />
      </div>
      <!-- 第一步 数据输入 -->
      <div class="operator_panel_wrap" v-show="step == 0">
        <ContentWrap id="id-baseInfo" title="数据选择" description="" style="margin-top: 8px;">
          <!-- 数据选择相关属性表单设置 -->
          <Form ref="formRef" :itemList="dataSelectInfoItems" :rules="dataSelectInfoFormRules"
            formId="model-select-edit" col="col3 custom-form" @select-change="handleDataSelectFormSelectChange"
            @uploadFileChange="uploadFileChange" @checkboxChange="handleDataSelectFormCheckboxChange" />
        </ContentWrap>
        <!-- 抽样预览的表单填写配置,及表格展示 -->
        <ContentWrap v-show="formRef?.formInline?.dataSource != 3" id="id-previewData" title="数据抽样预览" description=""
          style="margin-top: 16px;">
          <!-- 选择抽样预览的表单设置 -->
          <Form ref="dataSimpleFormRef" :itemList="dataSimpleFormItems" :rules="dataSimpleFormRules"
            formId="data-simple-edit" col="col3 fixwidth-form" @switch-change="handleDataSimpleFormSwitchChange"
            @input-change="handleDataSimpleFormChange" />
          <!-- 抽样预览的数据表格设置 -->
          <div class="table-v2-main" v-show="dataSimpleFormRef?.formInline?.enableSamplingRate == 'Y'"
            v-loading="sampleTableDataLoading">
            <CommonTable 
              v-show="sampleTableFields.length" 
              :data="sampleTableData"
              :fields="sampleTableFields"
              :loading="sampleTableDataLoading"
              :height="'100%'"
              :show-index="true"
              :style="{ width: '100%', height: '240px' }"
            />
            <!-- 无抽样数据时显示占位图片信息 -->
            <div v-show="!sampleTableFields.length" class="main-placeholder">
              <img src="../../assets/images/no-data.png" :style="{ width: '96px', height: '96px' }" />
              <div class="empty-text">暂无抽样数据</div>
            </div>
          </div>
        </ContentWrap>
        <!-- 数据来源为文件夹时显示提取文件进度及结果分析 -->
        <ContentWrap v-show="formRef?.formInline?.dataSource == 3" id="id-folder" title="提取文件" description=""
          style="margin-top: 16px;">
          <div class="folder-main">
            <el-button v-show="!clickSelectNode.path && !Object.keys(dicomStatisticsData)?.length" :icon="Upload"
              class="mr8" @click=uploadFolder>上传文件</el-button>
            <!-- 弹框展示服务器文件夹目录,并选择 -->
            <Dialog ref="dialogRef" :dialog-info="uploadFileDialogInfo" @btnClick="dialogBtnClick">
              <template #extra-content>
                <div class="folder-main-content" v-loading="uploadFileDialogInfo.contentLoading">
                  <Tree ref="treeInfoRef" :treeInfo="folderTreeInfo" @nodeClick="nodeClick" key="path"
                    @loadNode="loadFolderTreeNode" />
                </div>
                <div class="folder-foot">{{ '当前选中文件夹路径:' + (dialogOpenSelectNode.path || '--') }}</div>
              </template>
            </Dialog>
            <div v-show="clickSelectNode.path && dicomStatisticsData.state" class="folder-foot">{{ '当前提取文件夹路径:' +
              (clickSelectNode.path || '--') }}
            </div>
            <!-- 正在扫描的状态 -->
            <div class="folder-progress"
              v-show="clickSelectNode.path && (dicomStatisticsData.state == 'S' || !Object.keys(dicomStatisticsData)?.length)">
              <div class="folder-title">正在扫描</div>
              <el-progress :percentage="!dicomStatisticsData.progress ? 0 : changeNum(dicomStatisticsData.progress, 2)" :stroke-width="12" striped striped-flow
                :show-text="false" :duration="8" />
              <div v-show="Object.keys(dicomStatisticsData)?.length" style="display: flex;justify-content: space-between;"><span class="cnt">{{ '共扫描' +
                  changeNum(dicomStatisticsData.total, 0) + '个文件' }}</span><span v-show="dicomStatisticsData.remainingTime" class="desc">{{ '剩' +
                     transferTime(dicomStatisticsData.remainingTime)
                  }}</span></div>
              <div style="display: flex;justify-content: center;margin-top: 4px;"><el-button :icon="RefreshRight" link @click="refreshFolderResult" v-preReClick>刷新进度</el-button></div>
            </div>
            <!-- 正在解析的状态 -->
            <div class="folder-progress"
              v-show="clickSelectNode.path && (dicomStatisticsData.state == 'R')">
              <div class="folder-title">正在解析</div>
              <el-progress :percentage="!dicomStatisticsData.progress ? 0 : changeNum(dicomStatisticsData.progress, 2)" :stroke-width="12" striped striped-flow
                :show-text="false" :duration="8" />
              <div style="display: flex;justify-content: space-between;"><span class="cnt">{{ '共' +
                  changeNum(dicomStatisticsData.total, 0) +
                  '个文件, 已解析'
                  + (!dicomStatisticsData.progress ? 0 : changeNum(dicomStatisticsData.progress, 2)) + '%' }}</span><span v-show="dicomStatisticsData.remainingTime" class="desc">{{ '剩' +
                     transferTime(dicomStatisticsData.remainingTime)
                  }}</span></div>
                <div style="display: flex;justify-content: center;margin-top: 4px;"><el-button :icon="RefreshRight" link @click="refreshFolderResult" v-preReClick>刷新进度</el-button></div>
            </div>
            <!-- 解析失败的状态 -->
            <div class="folder-progress" v-show="clickSelectNode.path && dicomStatisticsData.state == 'E'">
              <div class="folder-title">
                <el-icon class="title-icon fail">
                  <CircleCloseFilled />
                </el-icon><span>解析失败</span>
              </div>
              <el-progress :percentage="!dicomStatisticsData.progress ? 0 : changeNum(dicomStatisticsData.progress, 2)" :stroke-width="12" color="#F30000"
                :show-text="false" />
              <div style="display: flex;justify-content: space-between;"><span class="cnt">{{ '已成功解析' +
                changeNum(dicomStatisticsData.successCount, 0) + '个文件, 失败' + changeNum(dicomStatisticsData.errorCount,
                  0) + '个文件' }}</span><span class="desc">{{ '共耗时'
                    + calculateElapsedTime(dicomStatisticsData.parsingTime, dicomStatisticsData.parsingCompletedTime)
                  }}</span></div>
              <div style="text-align: center;">
                <el-button @click="reAnalyzing">重试</el-button>
                <el-button @click=deleteFolder>删除文件,重新上传解析</el-button>
              </div>
            </div>
            <!-- 解析成功状态 -->
            <div class="folder-progress"
              v-show="clickSelectNode.path && dicomStatisticsData.state == 'Y' && dicomStatisticsData.errorCount === 0">
              <div class="folder-title">
                <el-icon class="title-icon success">
                  <svg-icon name="icon-success" />
                </el-icon><span>解析成功</span>
              </div>
              <el-progress :percentage="dicomStatisticsData.progress == 100 ? 100 : changeNum(dicomStatisticsData.progress, 2)" :stroke-width="12" color="#4FA55D"
                :show-text="false" />
              <div style="display: flex;justify-content: space-between;"><span class="cnt">{{ '已成功解析' +
                changeNum(dicomStatisticsData.successCount, 0)
                + '个文件,失败' + changeNum(dicomStatisticsData.errorCount, 0) + '个文件' }}</span><span class="desc">{{ '共耗时'
                    +   calculateElapsedTime(dicomStatisticsData.parsingTime, dicomStatisticsData.parsingCompletedTime)
                  }}</span>
              </div>
            </div>
          </div>
          <!-- 解析成功之后需要显示预览文件,和删除重新上传文件按钮 -->
          <div v-show="clickSelectNode.path && folderFileTableInfo.data?.length" class="preview-title">预览文件仅展示5条数据
          </div>
          <Table v-show="clickSelectNode.path && folderFileTableInfo.data?.length" :tableInfo="folderFileTableInfo">
          </Table>
          <div v-show="clickSelectNode.path && dicomStatisticsData.state == 'Y'" class="folder-bottom"><el-button
              @click=deleteFolder>删除文件,重新上传解析</el-button></div>
        </ContentWrap>
      </div>
      <!-- 第二步 配置匿名化方案,单独抽取vue组件页面 -->
      <anonTaskStepTwo ref="anonTaskStepTwoRef" v-show="step == 1" :anonTaskRules="detailInfo.anonTaskRules"
        :isFile="formRef?.formInline?.file?.length > 0" :anonPrivacyMode="detailInfo.anonPrivacyMode"
        :fieldTypeList="fieldTypeList" :fieldNameList="sampleTableFields">
      </anonTaskStepTwo>
      <!-- 第三步 结果分析 -->
      <div class="operator_panel_wrap" v-show="step == 2">
        <ContentWrap class="anlysis-content-wrap" id="analysis-result" title="匿名结果分析" description=""
          style="margin-top: 8px;">
          <div class="wait-result-div" v-show="!isExecEnd">
            <img class="loading-img" src="../../assets/images/loading.gif" />
            <div class="desc">正在进行匿名化处理,请稍候...</div>
            <el-button :icon="RefreshRight" link @click="refreshQueryData" v-preReClick>刷新查看结果</el-button>
          </div>
          <!-- 展示执行失败页面 -->
          <div class="wait-result-div" v-show="isExecEnd && analysisResultInfo.status == 'E'">
            <el-icon class="failed">
              <CircleCloseFilled />
            </el-icon>
            <div class="error-desc">{{ '执行失败,请返回上一步修改配置或联系管理员' }}</div>
            <div v-show="analysisResultInfo.errorMsg" class="error-desc">{{ '【' + analysisResultInfo.errorMsg + '】' }}
            </div>
          </div>
          <!-- 执行成功的报告结果查看页面 -->
          <anonResultAnalysis v-show="isExecEnd && analysisResultInfo.status == 'Y'" ref="resultReportRef"
            v-loading="downloadLoading" :analysis-result-info="analysisResultInfo" :is-word-style="isWordStyle"
            :element-loading-text="loadingText" :analysis-result-loading="analysisResultLoading"
            :analysis-result-table-fields="analysisResultTableFields" :old-anon-task-value-info="oldAnonTaskValueInfo"
            :container-width="containerWidth" :origin-result-table-field-column="originResultTableFieldColumn"
            :page-info="pageInfo" :result-data="resultData" :fullResultData="fullResultData" @page-change="pageChange">
          </anonResultAnalysis>
          <!-- 连接器只能查看报告 -->
          <!-- <template #header>
            <el-button v-show="isExecEnd && analysisResultInfo.status == 'Y' && !isWordStyle" type="primary"
              v-loading="!!downPromise" @click="transfer">生成Word评估报告</el-button>
            <div v-show="isWordStyle">
              <el-button @click="isWordStyle = false">返回</el-button>
              <el-button type="primary" @click="downloadWord">下载评估报告</el-button>
            </div>
          </template> -->
        </ContentWrap>
      </div>
      <!-- 匿名化结果展示 -->
      <div class="operator_panel_wrap step-result" v-show="step == 3" style="height: calc(100% - 88px);">
        <ContentWrap id="analysis-result" title="匿名化数据结果" description="" style="margin-top: 8px;height: 100%;">
          <!-- 匿名化结果数据查看页面,单独抽取业务组件,新开页面要使用 -->
          <anonResultView :is-page="false"
            :execGuid="analysisResultInfo.status == 'Y' && step == 3 ? taskExecGuid : ''">
          </anonResultView>
        </ContentWrap>
      </div>
    </div>
    <!-- 底部按钮,需要根据当前步骤条来展示对应的按钮 -->
    <div class="bottom_tool_wrap">
      <template v-if="step == 0">
        <el-button @click="cancelTask">取消</el-button>
        <!-- 匿名化评测情况下只有2个步骤条,根据传参选择对应的处理函数 -->
        <el-button type="primary"
          :disabled="formRef?.formInline?.handleType == '02' && formRef?.formInline?.dataSource == 3 && dicomStatisticsData?.state != 'Y'"
          @click="changeStepHandlers[formRef?.formInline?.handleType == '02' ? 3 : 2]()">下一步</el-button>
      </template>
      <template v-else-if="step == 1">
        <el-button @click="changeStepHandlers['lastStep'](1)">上一步</el-button>
        <el-button type="primary" @click="changeStepHandlers['3']()">下一步</el-button>
      </template>
      <template v-else-if="step == 2">
        <el-button @click="changeStepHandlers.lastStep(formRef?.formInline?.handleType == '02' ? 1 : 2)">上一步</el-button>
        <el-button v-show="formRef?.formInline?.handleType != '02'" type="primary"
          :disabled="analysisResultInfo.status == 'R' || (isExecEnd && analysisResultInfo.status == 'E')"
          @click="changeStepHandlers['4']()">下一步</el-button>
        <el-button type="primary" v-show="formRef?.formInline?.handleType == '02'"
          :disabled="analysisResultInfo.status == 'R' || (isExecEnd && analysisResultInfo.status == 'E')" v-preReClick
          @click="closeTask">关闭</el-button>
      </template>
      <template v-else>
        <el-button @click="changeStepHandlers.lastStep(3)">上一步</el-button>
        <el-button type="primary" v-preReClick @click="exportResult">导出</el-button>
      </template>
    </div>
  </div>
</template>

<script lang="ts" setup name="anonTaskCreate">
import {
  dataSourceTypeList,
  getAnonTaskDetail,
  getParamsList,
  chTransformEn,
  getAnonAnalyzeResult1,
  getAnonAnalyzePageData,
  getDatabase,
  getDsTableByDs,
  getDsTableFieldColumn,
  getDsTableSampleData,
  saveAnonTask,
  updateAnonTask,
  exportAnonExecData,
  htmlToWord,
  scanFolder,
  getDicomMeta,
  getDicomStatistics,
  retryDicom
} from '@/api/modules/dataAnonymization';
import {
  parseAndDecodeUrl,
  getDownFileSignByUrl,
  obsDownloadRequest
} from "@/api/modules/obsService";
import {
  getAreaData
} from "@/api/modules/queryService";
import useUserStore from "@/store/modules/user";
import { useValidator } from '@/hooks/useValidator';
import { TableColumnWidth } from '@/utils/enum';
import anonTaskStepTwo from './anonTaskStepTwo.vue';
import * as XLSX from 'xlsx';
import { ElMessage } from 'element-plus';
import { isEqual, cloneDeep } from "lodash-es";
import { changeNum, download } from "@/utils/common";
import anonResultView from './anonResultView.vue';
import useDataAnonymizationStore from "@/store/modules/dataAnonymization";
import { RefreshRight, CircleCloseFilled, Right } from "@element-plus/icons-vue";
import { commonPageConfig } from '@/components/PageNav';
import { Upload } from "@element-plus/icons-vue";
import anonResultAnalysis from './components/anonResultAnalysis.vue';
import html2canvas from 'html2canvas';
import { calcColumnWidth } from '@/utils';

const anonymizationStore = useDataAnonymizationStore();
const { proxy } = getCurrentInstance() as any;
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const fullPath = route.fullPath;
const taskGuid = ref(route.query.guid);
/** 提交保存和编辑后的执行guid */
const taskExecGuid = ref('');
/** 是否执行结束,用于第四步获取执行结果 */
const isExecEnd = ref(false);
const { required } = useValidator();
const fullscreenLoading = ref(false);
const containerRef = ref();

const qualifiedIdentifierFloderList = ref([{
  enName: 'patient_birth_date',
  chName: '患者出生日期',
}, {
  enName: 'patient_birth_time',
  chName: '患者出生时间'
}, {
  enName: 'patient_sex',
  chName: '患者性别'
}, {
  enName: 'patient_age',
  chName: '患者年龄'
}, {
  enName: 'patient_weight',
  chName: '患者体重'
}, {
  enName: 'pregnancy_status',
  chName: '怀孕状态'
}, {
  enName: 'military_rank',
  chName: '军衔'
}, {
  enName: 'branch_of_service',
  chName: '服役分支'
}, {
  enName: 'ethnic_group',
  chName: '种族'
}, {
  enName: 'occupation',
  chName: '职业'
}]);

const containerWidth = ref(containerRef.value?.offsetWidth || 0)

const step = ref(0);
const originStepsInfo = ref({
  step: step.value,
  list: [
    { title: '数据输入', value: 1 },
    { title: '配置匿名化方案', value: 2 },
    { title: '匿名结果分析', value: 3 },
    { title: '结果输出', value: 4 }
  ]
})
const stepsInfo = ref(originStepsInfo.value);

/** 已匿名化出具报告的 */
const reportStepsInfo = ref({
  step: step.value,
  list: [
    { title: '数据输入', value: 1 },
    //  { title: '配置匿名化方案', value: 2 },
    { title: '匿名结果分析', value: 2 },
    // { title: '结果输出', value: 4 }
  ]
})

/** 数据源列表 */
const dataSourceList: any = ref([]);

/** 数据源对应的数据表 */
const dsTableList: any = ref([]);

/** 数据共享类型字段列表 */
const dataSharingTypeList = ref([]);

/** 匿名化处理类型 */
const handleTypeList = ref([]);

const getParentAreaPromise: any = ref(null);
const getAreaDataPromise: any = ref({});
const getAreaDatas: any = ref({});
const parentAreaData: any = ref([]);

const getArea = (node, resolve) => {
  const { level } = node
  let params = {
    parentGuid: node.value
  }
  if (!node.value) {
    if (getParentAreaPromise.value) {
      getParentAreaPromise.value.then((res: any) => {
        resolve(res);
      })
    } else {
      resolve(parentAreaData.value);
    }
    return;
  }
  if (node.loaded) {
    resolve([]);
    return;
  }
  if (getAreaDatas.value[node.value]?.length) {
    resolve(getAreaDatas.value[node.value]);
    return;
  }
  if (!getAreaDataPromise.value[node.value]) {
    getAreaDataPromise.value[node.value] = getAreaData(params).then((res: any) => {
      node.loaded = true;
      getAreaDataPromise.value[node.value] = null;
      if (res?.code == proxy.$passCode) {
        const data = res.data ?? []
        data.map(item => {
          item.leaf = level >= 1
        })
        resolve(data)
        getAreaDatas.value[node.value] = data;
        return data;
      }
    })
  } else {
    getAreaDataPromise.value[node.value].then((data) => {
      getAreaDataPromise.value[node.value] = null;
      node.loaded = true;
      data.map(item => {
        item.leaf = level >= 1
      })
      resolve(data)
    })
  }
}

const formRef = ref();

/** 数据选择的表单配置信息 */
const dataSelectInfoItems = ref([{
  label: '数据集名称',
  type: 'input',
  placeholder: '请输入',
  field: 'taskName',
  maxlength: 15,
  default: '',
  required: true,
  filterable: true,
  clearable: true,
  visible: true,
}, {
  label: '数据共享类型',
  type: 'select',
  placeholder: '请选择',
  field: 'dataSharingTypeCode',
  default: '01',
  options: dataSharingTypeList.value,
  props: {
    label: "label",
    value: "value",
  },
  required: true,
  filterable: true,
  clearable: true,
  visible: true,
},
{
  label: '所属地域',
  type: "cascader",
  placeholder: "请选择",
  field: "coverageArea",
  default: [],
  showAllLevels: true,
  props: {
    label: 'name',
    value: 'guid',
    lazy: true,
    checkStrictly: true,
    lazyLoad: getArea,
    multiple: false,
  },
  collapse: true,
  tagsTooltip: true,
  //     filterable: true,
  clearable: true,
  required: false, //不选默认表示全国。
  //col: 'checkbox-right',
  visible: true
},
// { 去掉,直接用数据集总行数/全国人口总数计算
//   label: '患者占总人口比',
//   type: 'input',
//   placeholder: '数值,支持小数点9位',
//   field: 'patientPopulationRate',
//   maxlength: 11,
//   min: 0,
//   max: 1,
//   inputType: 'scoreNumber',
//   decimalCnt: 9,
//   default: '',
//   required: false,
//   filterable: true,
//   clearable: true,
//   visible: true,
// },
{
  label: '处理类型',
  type: 'select',
  placeholder: '请选择',
  field: 'handleType',
  default: '01',
  options: handleTypeList.value,
  props: {
    label: "label",
    value: "value",
  },
  required: true,
  filterable: true,
  clearable: true,
  visible: true,
},
{
  label: '数据来源',
  type: 'select',
  placeholder: '请选择',
  field: 'dataSource',
  default: 1,
  options: dataSourceTypeList,
  props: {
    label: "label",
    value: "value",
  },
  required: true,
  filterable: true,
  visible: true,
}, {
  label: '数据源',
  type: 'select',
  placeholder: '请选择',
  field: 'dataSourceGuid',
  default: '',
  options: dataSourceList.value,
  props: {
    label: 'databaseNameZh',
    value: 'guid'
  },
  filterable: true,
  visible: true,
  required: true
}, {
  label: "数据表",
  type: "select",
  placeholder: "请选择",
  field: "tableName",
  options: dsTableList.value,
  props: {
    label: 'tableComment',
    value: 'tableName'
  },
  default: '',
  filterable: true,
  clearable: true,
  required: true,
}, {
  label: "准标识符",
  type: "select",
  placeholder: "请选择",
  field: "qualifiedIdentifier",
  options: dsTableList.value,
  props: {
    label: 'chName',
    value: 'enName'
  },
  default: [],
  multiple: true,
  collapse: true,
  tagsTooltip: true,
  filterable: true,
  clearable: true,
  required: true,
  visible: false,
}, {
  label: '文件上传',
  tip: '支持扩展名:xlsx、xls、csv,文件大小不超过10MB',
  type: 'upload-file',
  accept: '.xlsx, .xls, .csv',
  limitSize: 10,
  limit: 1,
  isExcel: true,
  required: true,
  default: <any>[],
  block: false,
  col: 'wid60',
  visible: false,
  field: 'file',
},]);

const dataSelectInfoFormRules = ref({
  taskName: [required('请输入数据集名称')],
  dataSharingTypeCode: [required('请选择数据共享类型')],
  // patientPopulationRate: [required('请输入患者占总人口比')],
  dataSourceGuid: [required('请选择数据源')],
  handleType: [required('请选择处理类型')],
  tableName: [required('请选择数据表')],
  qualifiedIdentifier: [{ type: 'array', required: true, trigger: 'change', message: "请选择准标识符" }],
  file: [{
    validator: (rule: any, value: any, callback: any) => {
      if (!value?.length) {
        callback(new Error('请上传文件'))
      } else {
        callback();
      }
    }, trigger: 'change'
  }]
});

/** 最新选中的数据源 */
const currDatasourceSelect: any = ref({});

/** 数据基本信息选择表单下拉变化对应的处理函数 */
const dataSelectFormSelectChangeHandlers = {
  dataSource: (val, row, formInfo) => {
    dataSelectInfoItems.value[5].visible = val == 1;
    dataSelectInfoItems.value[6].visible = val == 1;
    dataSelectInfoItems.value[8].visible = val == 2;
    setDataSelectFormItems(Object.assign({}, formInfo, { file: !formInfo['file'] ? [] : formInfo['file'] }))
    sampleTableFields.value = [];
    parseFileDataSum.value = [];
    sampleTableData.value = [];
  },
  dataSourceGuid: async (val, row, formInfo) => {
    if (!val) {
      currDatasourceSelect.value = [];
      sampleTableFields.value = [];
      parseFileDataSum.value = [];
      sampleTableData.value = [];
      setDataSelectFormItems(Object.assign({}, formInfo, { file: !formInfo['file'] ? [] : formInfo['file'], tableName: '', qualifiedIdentifier: [] }))
      let item = dataSelectInfoItems.value.find(d => d.field == 'tableName');
      item && (item.options = dsTableList.value);
      return;
    }
    let dsInfo = currDatasourceSelect.value = dataSourceList.value.find(d => d.guid == val);
    //清除数据表得值,重新获取下拉列表
    const res: any = await getDsTableByDs({
      pageSize: -1,
      pageIndex: 1,
      dataSourceGuid: val,
      database: dsInfo.databaseNameEn,
      databaseType: dsInfo.databaseType,
      tableName: '',
      hadFlag: false
    });
    if (res.code == proxy.$passCode) {
      dsTableList.value = res.data?.records || [];
      setDataSelectFormItems(Object.assign({}, formInfo, { file: !formInfo['file'] ? [] : formInfo['file'], tableName: '', qualifiedIdentifier: [] }))
      let item = dataSelectInfoItems.value.find(d => d.field == 'tableName');
      item && (item.options = dsTableList.value);
    } else {
      proxy.$ElMessage.error(res.msg);
    }
    sampleTableFields.value = [];
    parseFileDataSum.value = [];
    sampleTableData.value = [];
  },
  tableName: (val, row, formInfo) => { 
    if (!val) {
      sampleTableFields.value = [];
      sampleTableData.value = [];
      return;
    }
    getDsTableFieldColumn({
      pageSize: 50,
      pageIndex: 1,
      dataSourceGuid: currDatasourceSelect.value.guid,
      database: currDatasourceSelect.value.databaseNameEn,
      databaseType: currDatasourceSelect.value.databaseType,
      tableName: val,
    }).then((res: any) => {
      if (res.code == proxy.$passCode) {
        sampleTableFields.value = res.data?.map(d => {
          d.fieldDataType = d.dataType;
          d.enName = d.columnName;
          d.chName = d.columnZhName;
          return d;
        }) || [];
        /** 判断有抽样数据,需要查询接口 */
        getSampleDataByDsTable();
      } else {
        ElMessage.error(res.msg);
      }
    });
  },
  handleType: (val, row, formInfo) => {
    setDataSelectFormItems(formInfo);
  }
}

const handleDataSelectFormSelectChange = async (val, row, formInfo) => {
  dataSelectFormSelectChangeHandlers[row.field]?.(val, row, formInfo);
}

const setDataSelectFormItems = (info, isDetail = false) => {
  dataSelectInfoItems.value.forEach(item => {
    item.default = info[item.field];
    if (item.field == 'coverageArea') {
      // item && item.children?.length && (item.children[0].visible = info['coverageArea'] != 'all');
      if (!isDetail) {
        return;
      }
      let coverageArea = info.coverageArea;
      if (coverageArea && Array.isArray(coverageArea) && coverageArea.length > 0) {
        item.default = coverageArea[0] as any;
        let p: any = [];
        coverageArea?.forEach(area => {
          if (p.includes(area[0])) {
            return;
          }
          p.push(area[0]);
          getArea({ value: area[0], level: 1 }, () => { })
        });
        let ps: any = []
        for (const key in getAreaDataPromise.value) {
          ps.push(getAreaDataPromise.value[key])
        }
        Promise.all(ps).then(() => {
          item.default = coverageArea[0];
        });
      } else {
        item.default = '';
      }
    } else if (item.field == 'qualifiedIdentifier') {
      item.visible = info['handleType'] == '02' && info['dataSource'] != 3;
      if (info['dataSource'] == 3) {
        item.options = qualifiedIdentifierFloderList.value;
      }
    }
  });
  stepsInfo.value = info.handleType == '02' ? reportStepsInfo.value : originStepsInfo.value;
}

const handleDataSelectFormCheckboxChange = (val, info, row) => {
  row.field == 'coverageArea' && setDataSelectFormItems(info);
}

const dataSimpleFormRef = ref();

/** 抽样数据预览 */
const dataSimpleFormItems = ref([{
  label: '抽样开关',
  type: 'switch',
  field: 'enableSamplingRate',
  default: 'N',
  col: 'autoWidth',
  activeValue: 'Y',
  inactiveValue: 'N'
}, {
  label: '抽样比例(%)',
  type: 'input',
  placeholder: '请输入',
  field: 'samplingRate',
  maxlength: 3,
  min: 0, //可以是0条。万一只是想看下字段呢
  max: 100,
  inputType: 'integerNumber',
  default: 10,
  required: true,
  filterable: true,
  clearable: true,
  visible: false,
}]);

const dataSimpleFormRules = ref({
  samplingRate: [required('请填写抽样比例')],
});

const oldSamplingRate = ref('10');

const handleDataSimpleFormSwitchChange = (val, info) => {
  if (val == 'N') {
    oldSamplingRate.value = info.samplingRate;
  } else {
    dataSimpleFormItems.value[1].default = oldSamplingRate.value || 10;
  }
  dataSimpleFormItems.value[1].visible = val == 'Y';
  dataSimpleFormItems.value[0].default = info.enableSamplingRate || 'N';
  if (formRef.value?.formInline?.file?.length) {
    transferSampleData();
  } else {
    getSampleDataByDsTable();
  }
}

/** 输入抽样比例值改变 */
const handleDataSimpleFormChange = (val) => {
  if (formRef.value?.formInline?.file?.length) {
    transferSampleData();
  } else {
    getSampleDataByDsTable();
  }
}

/** 样本表格加载中 */
const sampleTableDataLoading = ref(false);

/** 样本表格的数据 */
const sampleTableData: any = ref([]);

/** 样本表格的字段 */
const sampleTableFields: any = ref([]);

/** otherWidth表示使用标题宽度时添加标题排序图标等宽度 */
const calcTableColumnWidth = (data: any[], prop, title, otherWidth = 0) => {
  let d: any[] = [];
  data.forEach((dt) => d.push(dt[prop]));
  return calcColumnWidth(
    d,
    title,
    {
      fontSize: 14,
      fontFamily: "SimSun",
    },
    {
      fontSize: 14,
      fontFamily: "SimSun",
    },
    otherWidth
  );
};

watch(() => sampleTableFields.value, (val) => {
  let formInfo = formRef.value.formInline;
  if (formInfo.dataSource == 3) {
    return;
  }
  let item = dataSelectInfoItems.value.find(selectItem => selectItem.field == 'qualifiedIdentifier');
  item && (item.options = val);
  if (formInfo.handleType == '02' && !(taskGuid.value && (formInfo.file?.[0] && formInfo.file?.[0]?.url == detailInfo.value.filePath?.url || (formInfo.tableName && formInfo.tableName == detailInfo.value.tableName)))) {//需要同步清除准标识符的字段选择
    setDataSelectFormItems(Object.assign({}, formInfo, { file: !formInfo['file'] ? [] : formInfo['file'], qualifiedIdentifier: [] }))
  }
}, {
  deep: true
})



/** 解析的总的表格数据,方便后面修改抽样比例时使用 */
const parseFileDataSum: any = ref([]);
const currentSheet: any = ref();
const parseFileData = (fileRaw) => {
  sampleTableDataLoading.value = true;
  fileRaw.arrayBuffer().then(async (f) => {
    const wb = XLSX.read(f, {
      raw: false, cellDates: true
    });
    const sheet = wb.Sheets[wb.SheetNames[0]];
    currentSheet.value = sheet;
    const json: any[] = XLSX.utils.sheet_to_json(sheet, { header: 1 });
    if (json.length == 0) {
      sampleTableFields.value = [];
      sampleTableData.value = [];
    } else {
      try {
        const res: any = await chTransformEn(json[0]);
        if (res?.code != proxy.$passCode) {
          sampleTableDataLoading.value = false;
          proxy.$ElMessage.error(res.msg);
          return;
        }
        let fields = res.data || [];
        sampleTableFields.value = fields?.map((j, index) => {
          return {
            index: index,
            enName: j.enName + '',
            chName: j.chName + '',
            dataType: 'varchar'
          }
        }) || [];
        parseFileDataSum.value = json;
        /** 粗略算出字段类型 */
        json.slice(1, 10).forEach((info, row) => {
          json[0].forEach((name, col) => {
            if (info[col] === "" || info[col] == null || sampleTableFields.value[col].dataType != 'varchar') {
              return;
            } else {
              var cellRef = XLSX.utils.encode_cell({ r: row + 1, c: col });
              var cell = sheet[cellRef];
              let v = cell.w || info[col];
              let isNum = cell.t == 'n';
              if (isNum) {
                if (v.includes('.') && sampleTableFields.value[col].dataType != 'decimal') {
                  sampleTableFields.value[col].dataType = 'decimal';
                } else {
                  sampleTableFields.value[col].dataType = 'int';
                }
              }
            }
          });
        })
        transferSampleData();
        sampleTableDataLoading.value = false;
      } catch (error) {
        sampleTableDataLoading.value = false;
      }
    }
  });
}

/** 获取文件解析后根据抽样比例得出的表格数据,默认查看前500条数据 */
const transferSampleData = () => {
  let samplingRate = dataSimpleFormRef.value?.formInline?.samplingRate;
  if (parseFileDataSum.value.length > 1 && samplingRate) {
    let totalCnt = parseFileDataSum.value.length - 1;
    let cnt = Math.ceil(samplingRate * 0.01 * totalCnt) + 1;
    sampleTableData.value = parseFileDataSum.value.slice(1, cnt > 500 ? 501 : cnt).map((info, row) => {
      let object = {};
      parseFileDataSum.value[0].forEach((chName, col) => {
        let name = sampleTableFields.value[col].enName;
        var cellRef = XLSX.utils.encode_cell({ r: row + 1, c: col });
        var cell = currentSheet.value[cellRef];
        let v = cell.w || info[col];
        object[name] = v;
      });
      return object;
    });
  } else {
    sampleTableData.value = [];
  }
}

/** 获取选择的数据库表根据抽样比例得出的表格数据 */
const getSampleDataByDsTable = () => {
  const tableName = formRef.value?.formInline?.tableName;
  if (!currDatasourceSelect.value.guid || !tableName) {
    sampleTableFields.value = [];
    sampleTableData.value = [];
    return;
  }
  let samplingRate = dataSimpleFormRef.value?.formInline?.samplingRate;
  if (!samplingRate) {
    sampleTableData.value = [];
    return;
  }
  let totalCnt = dsTableList.value.find(t => t.tableName == tableName)?.tableRows || 0;
  let cnt = Math.ceil(samplingRate * 0.01 * totalCnt);
  if (!cnt) {
    sampleTableData.value = [];
    return;
  }
  sampleTableDataLoading.value = true;
  getDsTableSampleData({
    limitNum: cnt > 500 ? 500 : cnt,
    pageSize: cnt > 500 ? 500 : cnt,
    pageIndex: 1,
    dataSourceGuid: currDatasourceSelect.value.guid,
    database: currDatasourceSelect.value.databaseNameEn,
    databaseType: currDatasourceSelect.value.databaseType,
    tableName: tableName,
    hadFlag: false,
  }).then((res: any) => {
    sampleTableDataLoading.value = false;
    if (res.code == proxy.$passCode) {
      sampleTableData.value = res.data?.datas || [];
    } else {
      sampleTableData.value = [];
      ElMessage.error(res.msg);
    }
  });
}

const uploadFileChange = (file) => {
  sampleTableData.value = [];
  if (!file.length) {
    sampleTableFields.value = [];
    sampleTableData.value = [];
    return;
  }
  let fileRaw = file[0].file;
  parseFileData(fileRaw);
}

/*** ----------------------- 解析扫描文件 ------------------------------  */

/** 上传选择文件夹对话框 */
const uploadFileDialogInfo = ref({
  visible: false,
  size: 700,
  direction: "column",
  header: {
    title: "选择文件夹",
  },
  type: '',
  contents: [],
  footer: {
    btns: [
      { type: "default", label: "取消", value: "cancel" },
      { type: "primary", label: "确定", value: "submit", loading: false },
    ],
  },
  contentLoading: false,
});

const folderRefreshTimer = ref();

const processFolderRefresh = async (isRefresh = false) => {
  // 组件已卸载时不再执行
  if (!containerRef.value) {
    return;
  }
  await getDicomStatisticsData(taskGuid.value, isRefresh);
  if (!dicomStatisticsData.value.state || dicomStatisticsData.value.state == 'S' || dicomStatisticsData.value.state == 'R') {
    if (folderRefreshTimer.value) {
      return;
    }
    folderRefreshTimer.value = setInterval(async () => {
      processFolderRefresh();
    }, 10000);
  } else if (dicomStatisticsData.value.state == 'Y') {
    getDicomMetaData(taskGuid.value);
    analysisResultInfo.value = {};
    if (folderRefreshTimer.value) {
      clearInterval(folderRefreshTimer.value);
      folderRefreshTimer.value = null;
    }
    // processStepThreeResultView();
  } else if (dicomStatisticsData.value.state == 'E') {
    if (folderRefreshTimer.value) {
      clearInterval(folderRefreshTimer.value);
      folderRefreshTimer.value = null;
    }
  }
}

/** 随时点击刷新查看结果。 */
const refreshFolderResult = () => {
  if (getFolderResultPromise.value) {
    return;
  }
  if (folderRefreshTimer.value) {
    clearInterval(folderRefreshTimer.value);
    folderRefreshTimer.value = null;
  }
  processFolderRefresh(true);
}

// TODO,需要将selectNode与oldSelectNode即对话框展开的做区分处理。

const dialogBtnClick = (btn) => {
  if (btn.value == 'submit') {
    clickSelectNode.value = dialogOpenSelectNode.value;
    if (!clickSelectNode.value.path) {
      proxy.$ElMessage.error('请先选择文件夹');
      return;
    }
    let saveParams = { ...formRef.value.formInline };
    if (saveParams.coverageArea?.length) {
      saveParams.coverageArea = [saveParams.coverageArea];
    } else {
      saveParams.coverageArea = [];
    }
    saveParams.filePath = {
      url: clickSelectNode.value.path
    };
    saveParams.samplingRate = null;
    if (taskGuid.value) {
      saveParams.guid = taskGuid.value;
    }
    dicomStatisticsData.value = {};
    folderFileTableInfo.value.data = [];
    if (!taskGuid.value) { //保存
      uploadFileDialogInfo.value.footer.btns[1].loading = true;
      saveAnonTask(saveParams).then(async (res: any) => {
        uploadFileDialogInfo.value.footer.btns[1].loading = false;
        if (res.code == proxy.$passCode) {
          taskGuid.value = res.data?.taskGuid;
          taskExecGuid.value = res.data?.lastExecGuid;
          uploadFileDialogInfo.value.visible = false;
          anonymizationStore.setIsAnonPageRefresh(true);
          isExecEnd.value = false;
          oldAnonTaskValueInfo.value = saveParams;
          oldAnonTaskValueInfo.value.guid = taskGuid.value;
          if (folderRefreshTimer.value) {
            clearInterval(folderRefreshTimer.value);
            folderRefreshTimer.value = null;
          }
          await 100;
          processFolderRefresh();
        } else {
          ElMessage.error(res.msg);
        }
      });
    } else { //更新
      uploadFileDialogInfo.value.footer.btns[1].loading = true;
      updateAnonTask(saveParams).then(async (res: any) => {
        uploadFileDialogInfo.value.footer.btns[1].loading = false;
        if (res.code == proxy.$passCode) {
          taskExecGuid.value = res.data;
          uploadFileDialogInfo.value.visible = false;
          anonymizationStore.setIsAnonPageRefresh(true);
          isExecEnd.value = false;
          oldAnonTaskValueInfo.value = saveParams;
          if (folderRefreshTimer.value) {
            clearInterval(folderRefreshTimer.value);
            folderRefreshTimer.value = null;
          }
          await 100;
          processFolderRefresh();
        } else {
          ElMessage.error(res.msg);
        }
      })
    }
  } else if (btn.value == 'cancel') {
    //  clickSelectNode.value = {};
    dialogOpenSelectNode.value = {};
    uploadFileDialogInfo.value.visible = false;
  }
};

const folderTreeInfo = ref({
  id: "data-pickup-tree",
  filter: true,
  queryValue: "",
  queryPlaceholder: "输入关键字搜索",
  props: {
    label: "name",
    value: "path",
    isLeaf: "isLeaf",
  },
  prefix: {
    type: 'prefixIcon'
  },
  nodeKey: 'path',
  lazy: true,
  expandedKey: [],
  currentNodeKey: '',
  expandOnNodeClick: true,
  data: <any>[],
  //customFilter: true,
  loading: false
});

const clickSelectNode: any = ref({});

const nodeClick = (data, node) => {
  dialogOpenSelectNode.value = data;
}

const loadFolderTreeNode = (node, resolve) => {
  if (node.level === 0 || node.isLeaf) {
    return resolve([]);
  }
  scanFolder(node.data.path).then((res: any) => {
    if (res?.code == proxy.$passCode) {
      resolve(res.data || []);
    } else {
      ElMessage.error(res.msg);
    }
  })
}

const dialogOpenSelectNode: any = ref({})

const uploadFolder = () => {
  // 先检查信息是否填写完整。
  formRef.value?.ruleFormRef?.validate((valid) => {
    if (valid) {
      let formInline = formRef.value?.formInline;
      if (formInline.handleType == '01' && formInline.dataSource == 3) {
        proxy.$ElMessage.warning('暂不支持处理类型为数据匿名化处理的文件夹数据,请修改');
        return;
      }
      clickSelectNode.value = {};
      dialogOpenSelectNode.value = {};
      uploadFileDialogInfo.value.visible = true;
      folderTreeInfo.value.loading = true;
      scanFolder().then((res: any) => {
        folderTreeInfo.value.loading = false;
        if (res?.code == proxy.$passCode) {
          folderTreeInfo.value.data = res.data || [];
        } else {
          ElMessage.error(res.msg);
        }
      })
    } else {
      proxy.$ElMessage.warning('请先填写完整数据选择基本信息');
    }
  })
}

const deleteFolder = () => {
  proxy.$openMessageBox("确定要删除该文件夹扫描解析结果,重新上传吗?", () => {
    clickSelectNode.value = {};
    folderFileTableInfo.value.data = [];
    dicomStatisticsData.value = {};
  }, () => {
    proxy.$ElMessage.info("已取消删除");
  })
}

/** 重试 */
const reAnalyzing = () => {
  fullscreenLoading.value = true;
  retryDicom(taskGuid.value).then((res: any) => {
    fullscreenLoading.value = false;
    if (res?.code == proxy.$passCode) {
      if (folderRefreshTimer.value) {
        clearInterval(folderRefreshTimer.value);
        folderRefreshTimer.value = null;
      }
      processFolderRefresh();
    } else {
      res?.msg && ElMessage.error(res.msg);
    }
  })
}

/** 上传成功之后的文件信息 */
const folderFileTableInfo = ref({
  id: "exec-contract-table",
  height: '212px',
  fields: <any>[],
  data: [],
  showPage: false,
  actionInfo: {
    show: false
  },
  loading: false
});

const dicomMetaData: any = ref({});
const metaDataWidthsJson = ref({
  '患者姓名': 140,
  '患者ID': 140,
  '患者出生日期': 120,
  '患者出生时间': 130,
  '患者性别': 100,
  "怀孕状态": 110,
  "种族": 100,
  "患者体重": 90,
  '患者年龄': 110,
});
/** 获取预览的5条数据 */
const getDicomMetaData = (taskGuid) => {
  folderFileTableInfo.value.loading = true;
  getDicomMeta(taskGuid).then((res: any) => {
    folderFileTableInfo.value.loading = false;
    if (res?.code == proxy.$passCode) {
      dicomMetaData.value = res.data || {};
      folderFileTableInfo.value.fields = [{ label: "序号", type: "index", width: TableColumnWidth.INDEX, align: "center" }].concat(dicomMetaData.value?.column?.map(f => {
        return {
          label: f, field: f, width: metaDataWidthsJson.value[f] || 120
        }
      }));
      let column = dicomMetaData.value?.column || [];
      folderFileTableInfo.value.data = dicomMetaData.value.datas?.map(d => {
        let json = {};
        column.forEach((c, index) => {
          json[c] = d[index];
        })
        return json;
      })
    } else {
      res?.msg && proxy.$ElMessage.error(res.msg);
    }
  })
}

const dicomStatisticsData: any = ref({});

const getFolderResultPromise: any = ref(null);

/** 获取解析文件结果数据 */
const getDicomStatisticsData = (taskGuid, isRefresh = false) => {
  getFolderResultPromise.value = getDicomStatistics(taskGuid).then((res: any) => {
    getFolderResultPromise.value = null;
    if (res?.code == proxy.$passCode) {
      if (isRefresh) {
        proxy.$ElMessage.success('刷新成功');
      }
      dicomStatisticsData.value = res.data || {};
    } else {
      res?.msg && proxy.$ElMessage.error(res.msg);
    }
  })
  return getFolderResultPromise.value;
}

/** 将时间转换为时分秒 */
const transferTime = (time) => {
  if (time == null) {
    return '--';
  }
  
  // 4. 将毫秒转换为小时、分钟和秒
  const totalSeconds = Math.floor(time / 1000);
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;

  // 5. 格式化输出
  const parts: any[] = [];

  if (hours > 0) {
    parts.push(`${hours}小时`);
  }

  if (minutes > 0 || hours > 0) { // 如果有小时,即使分钟为0也显示0分钟
    parts.push(`${minutes}分钟`);
  }

  parts.push(`${seconds}秒`);

  return parts.join('');
}

/**
 * 计算两个时间之间的耗时
 * @param {string} parsingTime - 开始时间(ISO 8601格式)
 * @param {string} parsingCompletedTime - 结束时间(ISO 8601格式)
 * @returns {string} - 格式化的耗时字符串,如 "2小时30分钟"
 */
const calculateElapsedTime = (parsingTime, parsingCompletedTime) => {
  // 1. 将时间字符串转换为Date对象
  const startTime = new Date(parsingTime);
  const endTime = new Date(parsingCompletedTime);

  // 2. 计算时间差(毫秒)
  const timeDiff = endTime - startTime;

  // 3. 检查时间是否有效
  if (isNaN(timeDiff)) {
    // return "时间格式错误";
    return '--';
  }

  if (timeDiff < 0) {
    //return "结束时间早于开始时间";
    return '--';
  }

 return transferTime(timeDiff);
}

/** 第二步的配置组件引用。 */
const anonTaskStepTwoRef = ref();

/** 步骤条对应的不同步骤下一步,上一步的处理函数。 */
const changeStepHandlers = {
  'lastStep': (val) => {
    step.value = val - 1;
    stepsInfo.value.step = val - 1;
  },
  '2': () => {
    let val = 2;
    formRef.value?.ruleFormRef?.validate((valid) => {
      if (valid) {
        if (formRef.value?.formInline?.dataSource == 2 && !sampleTableFields.value?.length) {
          proxy.$ElMessage.error('上传文件的字段不能为空');
          return;
        }
        dataSimpleFormRef.value?.ruleFormRef?.validate((valid) => {
          if (valid) {
            // 第一步到第二步时,如果字段列表中与字段脱敏规则中的字段不匹配,应清空。
            step.value = val - 1;
            stepsInfo.value.step = val - 1;
            anonTaskStepTwoRef.value?.updateNextStepRules();
          }
        });
      }
    });
  },
  '3': async () => {
    let val = 3;
    let exec = (saveParams) => {
      if (saveParams.coverageArea?.length) {
        saveParams.coverageArea = [saveParams.coverageArea];
      } else {
        saveParams.coverageArea = [];
      }
      if (saveParams.file?.length) {
        saveParams.filePath = {
          name: saveParams.file[0].name,
          url: saveParams.file[0].url
        }
        delete saveParams.file;
        saveParams.dataSourceGuid = null;
        saveParams.tableName = null;
      } else {
        if (saveParams.dataSource == 3 && clickSelectNode.value.path) {
          saveParams.filePath = {
            url: clickSelectNode.value.path
          };
        } else {
          saveParams.filePath = null;
        }
      }
      let simpleFormInline = dataSimpleFormRef.value.formInline;
      if (simpleFormInline.enableSamplingRate == 'Y') {
        saveParams.samplingRate = simpleFormInline.samplingRate && parseInt(simpleFormInline.samplingRate);
      } else {
        saveParams.samplingRate = null;
      }
      if (taskGuid.value) {
        saveParams.guid = taskGuid.value;
      }
      if (isEqual(saveParams, oldAnonTaskValueInfo.value)) {
        isExecEnd.value = false;
        step.value = val - 1;
        stepsInfo.value.step = val - 1;
        if (!analysisResultInfo.value?.status) {
          processStepThreeResultView();
        } else {
          isExecEnd.value = analysisResultInfo.value?.status == 'E' || analysisResultInfo.value?.status == 'Y';
        }
        return;
      }
      if (!taskGuid.value) { //保存
        fullscreenLoading.value = true;
        saveAnonTask(saveParams).then((res: any) => {
          fullscreenLoading.value = false;
          if (res.code == proxy.$passCode) {
            taskGuid.value = res.data?.taskGuid;
            isExecEnd.value = false;
            taskExecGuid.value = res.data?.lastExecGuid;
            oldAnonTaskValueInfo.value = saveParams;
            oldAnonTaskValueInfo.value.guid = taskGuid.value;
            step.value = val - 1;
            stepsInfo.value.step = val - 1;
            analysisResultInfo.value = {};
            if (refreshTimer.value) {
              clearInterval(refreshTimer.value);
              refreshTimer.value = null;
            }
            processStepThreeResultView();
            anonymizationStore.setIsAnonPageRefresh(true);
          } else {
            ElMessage.error(res.msg);
          }
        });
      } else { //更新
        fullscreenLoading.value = true;
        updateAnonTask(saveParams).then((res: any) => {
          fullscreenLoading.value = false;
          if (res.code == proxy.$passCode) {
            isExecEnd.value = false;
            taskExecGuid.value = res.data;
            step.value = val - 1;
            stepsInfo.value.step = val - 1;
            analysisResultInfo.value = {};
            if (refreshTimer.value) {
              clearInterval(refreshTimer.value);
              refreshTimer.value = null;
            }
            processStepThreeResultView();
            oldAnonTaskValueInfo.value = saveParams;
            anonymizationStore.setIsAnonPageRefresh(true);
          } else {
            ElMessage.error(res.msg);
          }
        })
      }
    }
    let saveParams: any = { ...formRef.value.formInline };
    if (saveParams.handleType == '01') {
      // 保存并提交 TODO。需要加个 记录旧值的,用来判断新值和旧值,是否发生变化,若变化则需要调用保存接口之后,再进行下一步。
      let configInfo = await anonTaskStepTwoRef.value?.getStepTwoConfigInfo();
      if (!configInfo) {
        return;
      }
      let privacy = configInfo.anonPrivacyMode; //值是克隆过的,可以删除
      delete privacy.isKaNumber;
      delete privacy.isRiskThreshold;
      delete privacy.isTcField;
      delete privacy.isLdField;
      // 为空时为了跟原始值保持一致
      privacy.kaNumber = (privacy.kaNumber && parseInt(privacy.kaNumber)) ?? null;
      privacy.riskThreshold = (privacy.riskThreshold && parseFloat(privacy.riskThreshold)) ?? null;
      privacy.tcFieldName = privacy.tcFieldName ?? null;
      privacy.tcThreshold = (privacy.tcThreshold && parseFloat(privacy.tcThreshold)) ?? null;
      privacy.ldFieldName = privacy.ldFieldName ?? null;
      privacy.ldNumber = (privacy.ldNumber && parseInt(privacy.ldNumber)) ?? null;
      Object.assign(saveParams, configInfo);
      exec(saveParams);
    } else {
      formRef.value?.ruleFormRef?.validate((valid, errorItem) => {
        if (valid) {
          let dataSource = formRef.value?.formInline?.dataSource;
          if (dataSource == 2 && !sampleTableFields.value?.length) {
            proxy.$ElMessage.error('上传文件的字段不能为空');
            return;
          }
          if (dataSource != 3) {
            dataSimpleFormRef.value?.ruleFormRef?.validate((valid) => {
              if (valid) {
                //         Object.assign(saveParams, { riskThreshold: '0.05' });
                exec(saveParams);
              }
            });
          } else {
            if (!clickSelectNode.value.path) {
              proxy.$ElMessage.error('请先上传文件');
              return;
            }
            exec(saveParams);
          }
        } else {
          var obj = Object.keys(errorItem);
          formRef.value.ruleFormRef?.scrollToField(obj[0])
        }
      })
    }
  },
  '4': () => {
    let val = 4;
     //下一步之后,设置执行结束, 查看结果。
    step.value = val - 1;
    stepsInfo.value.step = val - 1;
  }
}

const promise: any = ref(null);
const exportResult = () => {
  promise.value = exportAnonExecData({
    taskGuid: route.query.guid,
    execGuid: route.query.execGuid
  }).then((res: any) => {
    promise.value = null;
    if (res && !res.msg) {
      download(res, (route.query.taskName || oldAnonTaskValueInfo.value.taskName) + '_匿名化数据.xlsx', 'excel')
    } else {
      res?.msg && ElMessage.error(res?.msg);
    }
  }).catch(() => {
    promise.value = null;
  })
}

/** 获取字段类型的数据字典 */
const fieldTypeList: any = ref([]);

/** 编辑时获取的匿名化任务的详情信息 */
const detailInfo: any = ref({});

/** 记录原始的值信息,防止上一步之后未修改数据时不调用接口 */
const oldAnonTaskValueInfo: any = ref({});

onBeforeMount(() => {
  if (taskGuid.value) {
    fullscreenLoading.value = true;
    getAnonTaskDetail(taskGuid.value).then(async (res: any) => {
      if (res?.code == proxy.$passCode) {
        detailInfo.value = res.data || {};
        taskExecGuid.value = detailInfo.value.lastExecGuid;
        if (detailInfo.value.handleType == '01') {
          oldAnonTaskValueInfo.value = {
            guid: detailInfo.value.guid,
            taskName: detailInfo.value.taskName,
            dataSource: detailInfo.value.dataSource,
            handleType: detailInfo.value.handleType,
            coverageArea: detailInfo.value.coverageArea || [],
            qualifiedIdentifier: detailInfo.value.qualifiedIdentifier,
            samplingRate: detailInfo.value.samplingRate,
            dataSharingTypeCode: detailInfo.value.dataSharingTypeCode,
            anonTaskRules: cloneDeep(detailInfo.value.anonTaskRules),
            anonPrivacyMode: {
              kaNumber: detailInfo.value.anonPrivacyMode?.kaNumber,
              ldFieldName: detailInfo.value.anonPrivacyMode?.ldFieldName,
              ldNumber: detailInfo.value.anonPrivacyMode?.ldNumber,
              riskThreshold: detailInfo.value.anonPrivacyMode?.riskThreshold,
              tcFieldName: detailInfo.value.anonPrivacyMode?.tcFieldName,
              tcThreshold: detailInfo.value.anonPrivacyMode?.tcThreshold,
            }
          }
        } else {
          oldAnonTaskValueInfo.value = {
            guid: detailInfo.value.guid,
            taskName: detailInfo.value.taskName,
            dataSource: detailInfo.value.dataSource,
            handleType: detailInfo.value.handleType,
            coverageArea: detailInfo.value.coverageArea || [],
        //    qualifiedIdentifier: detailInfo.value.qualifiedIdentifier,
            samplingRate: detailInfo.value.samplingRate,
            dataSharingTypeCode: detailInfo.value.dataSharingTypeCode,
          }
        }
        if (detailInfo.value.dataSource == 1) {
          oldAnonTaskValueInfo.value.dataSourceGuid = detailInfo.value.dataSourceGuid;
          oldAnonTaskValueInfo.value.tableName = detailInfo.value.tableName;
        } else {
          oldAnonTaskValueInfo.value.filePath = detailInfo.value.filePath && cloneDeep(detailInfo.value.filePath);
        }
        detailInfo.value.dataSource == 3 && (clickSelectNode.value.path = oldAnonTaskValueInfo.value.filePath?.url);
        setDataSelectFormItems(Object.assign(detailInfo.value, { file: detailInfo.value.filePath ? [detailInfo.value.filePath] : [] }), true);
        if (detailInfo.value.samplingRate != null) {
          dataSimpleFormItems.value[0].default = 'Y';
          dataSimpleFormItems.value[1].visible = true;
          dataSimpleFormItems.value[1].default = detailInfo.value.samplingRate;
        } else {
          dataSimpleFormItems.value[0].default = 'N';
          dataSimpleFormItems.value[1].visible = false;
        }
        let dataSource = detailInfo.value.dataSource;
        dataSelectInfoItems.value[5].visible = dataSource == 1;
        dataSelectInfoItems.value[6].visible = dataSource == 1;
        dataSelectInfoItems.value[8].visible = dataSource == 2;
        try {
          // 文件解析
          if (dataSource == 2) {
            let url = detailInfo.value.filePath?.url;
            sampleTableDataLoading.value = true;
            const refSignInfo: any = await getDownFileSignByUrl(parseAndDecodeUrl(url).fileName);
            if (!refSignInfo?.data) {
              fullscreenLoading.value = false;
              refSignInfo?.msg && ElMessage.error(refSignInfo?.msg);
              return;
            }
            const fileRes: any = await obsDownloadRequest(refSignInfo?.data);
            sampleTableDataLoading.value = false;
            if (fileRes && !fileRes.msg) {
              parseFileData(fileRes);
            } else {
              fileRes?.msg && ElMessage.error(fileRes?.msg);
            }
            // 会出现从文件切换到数据库时没有数据库列表的问题。
            const res: any = await getDatabase({ connectStatus: 1 });
            if (res?.code == proxy.$passCode) {
              dataSourceList.value = res.data || [];
              let item = dataSelectInfoItems.value.find(item => item.field == 'dataSourceGuid');
              item && (item.options = dataSourceList.value);
            } else {
              proxy.$ElMessage.error(res.msg);
            }
          } else if (dataSource == 1) {
            const res: any = await getDatabase({ connectStatus: 1 });
            if (res?.code == proxy.$passCode) {
              dataSourceList.value = res.data || [];
              let item = dataSelectInfoItems.value.find(item => item.field == 'dataSourceGuid');
              item && (item.options = dataSourceList.value);
            } else {
              proxy.$ElMessage.error(res.msg);
            }
            currDatasourceSelect.value = dataSourceList.value.find(d => d.guid == detailInfo.value.dataSourceGuid);
            const tableRes: any = await getDsTableByDs({
              pageSize: -1,
              pageIndex: 1,
              dataSourceGuid: detailInfo.value.dataSourceGuid,
              database: currDatasourceSelect.value.databaseNameEn,
              databaseType: currDatasourceSelect.value.databaseType,
              tableName: '',
              hadFlag: false
            });
            if (tableRes?.code == proxy.$passCode) {
              dsTableList.value = tableRes.data?.records || [];
              let item = dataSelectInfoItems.value.find(item => item.field == 'tableName');
              item && (item.options = dsTableList.value);
            } else {
              proxy.$ElMessage.error(tableRes.msg);
            }
            getDsTableFieldColumn({
              pageSize: 50,
              pageIndex: 1,
              dataSourceGuid: currDatasourceSelect.value.guid,
              database: currDatasourceSelect.value.databaseNameEn,
              databaseType: currDatasourceSelect.value.databaseType,
              tableName: detailInfo.value.tableName,
            }).then((res: any) => {
              if (res.code == proxy.$passCode) {
                sampleTableFields.value = res.data?.map(d => {
                  d.fieldDataType = d.dataType;
                  d.enName = d.columnName;
                  d.chName = d.columnZhName;
                  return d;
                }) || [];
                /** 判断有抽样数据,需要查询接口 */
                getSampleDataByDsTable();
              } else {
                ElMessage.error(res.msg);
              }
            });
          } else if (dataSource == 3) {
            processFolderRefresh();
          }
          fullscreenLoading.value = false;
        } catch (error) {
          fullscreenLoading.value = false;
        }
      } else {
        fullscreenLoading.value = false;
        proxy.$ElMessage.error(res.msg);
      }
    });
  } else {
    getDatabase({ connectStatus: 1 }).then((res: any) => {
      if (res.code == proxy.$passCode) {
        dataSourceList.value = res.data || [];
        let item = dataSelectInfoItems.value.find(item => item.field == 'dataSourceGuid');
        item && (item.options = dataSourceList.value);
      } else {
        proxy.$ElMessage.error(res.msg);
      }
    })
  }
  getParamsList({
    dictType: "数据共享类型",
  }).then((res: any) => {
    if (res?.code == proxy.$passCode) {
      dataSharingTypeList.value = res.data || [];
      let item = dataSelectInfoItems.value.find(item => item.field == 'dataSharingTypeCode');
      item && (item.options = dataSharingTypeList.value);
    } else {
      proxy.$ElMessage.error(res.msg);
    }
  });
  getParamsList({
    dictType: "数据匿名化处理类型",
  }).then((res: any) => {
    if (res?.code == proxy.$passCode) {
      handleTypeList.value = res.data || [];
      let item = dataSelectInfoItems.value.find(item => item.field == 'handleType');
      item && (item.options = handleTypeList.value);
    } else {
      proxy.$ElMessage.error(res.msg);
    }
  });
  getParamsList({
    dictType: "字段类型",
  }).then((res: any) => {
    if (res?.code == proxy.$passCode) {
      fieldTypeList.value = res.data || [];
    } else {
      proxy.$ElMessage.error(res.msg);
    }
  });
  getParentAreaPromise.value = getAreaData({ parentId: null }).then((res: any) => {
    if (res?.code == proxy.$passCode) {
      parentAreaData.value = res.data ?? [];
      return parentAreaData.value;
    }
  })
})

const handleResize = () => {
  containerWidth.value = containerRef.value?.offsetWidth || 0;
}

onMounted(() => {
  nextTick(() => {
    containerWidth.value = containerRef.value?.offsetWidth || 0;
  })
  window.addEventListener('resize', handleResize);
})

const cancelTask = () => {
  proxy.$openMessageBox("当前页面尚未保存,确定放弃修改吗?", () => {
    userStore.setTabbar(userStore.tabbar.filter((tab: any) => tab.fullPath !== fullPath));
    router.push({
      name: 'anonResultProcessManage'
    });
  }, () => {
    proxy.$ElMessage.info("已取消");
  });
}

/** 完成任务关闭 */
const closeTask = () => {
  userStore.setTabbar(userStore.tabbar.filter((tab: any) => tab.fullPath !== fullPath));
  router.push({
    name: 'anonResultProcessManage'
  });
}

const refreshTimer = ref()

/** 执行结果信息 */
const analysisResultInfo: any = ref({});

const getResultPromise: any = ref(null);

/** 第三步处理,定时刷新查看结果 */
const processStepThreeResultView = (isRefresh = false) => {
  // 组件已卸载时不再执行
  if (!containerRef.value) {
    return;
  }
  let process = (isRefresh) => {
    getResultPromise.value = getAnonAnalyzeResult1(taskExecGuid.value).then((res: any) => {
      getResultPromise.value = null;
      if (res?.code == proxy.$passCode) {
        analysisResultInfo.value = res.data || {};
        if (analysisResultInfo.value.status == 'R') { //正在运行中
          if (isRefresh) {
            proxy.$ElMessage.success('刷新成功,正在执行中...');
          }
          //添加定时器。
          if (refreshTimer.value) {
            return;
          }
          refreshTimer.value = setInterval(async () => {
            process(false);
          }, 20000);
        } else if (analysisResultInfo.value.status == 'Y') {
          //去获取结果。
          isExecEnd.value = true;
          refreshTimer.value && clearInterval(refreshTimer.value);
          refreshTimer.value = null;
          analysisResultTableFields.value = res.data?.column || [];
          pageInfo.value.curr = 1;
          getAnalysisResultPageData(true);
        } else if (analysisResultInfo.value.status == 'E') {
          isExecEnd.value = true
          refreshTimer.value && clearInterval(refreshTimer.value);
          refreshTimer.value = null;
        }
      } else {
        proxy.$ElMessage.error(res.msg);
      }
    });
  }
  process(isRefresh);
}

/** 随时点击刷新查看结果。 */
const refreshQueryData = () => {
  if (getResultPromise.value) {
    return;
  }
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
  }
  processStepThreeResultView(true);
}

/** ------------------------- 匿名化分析结果页面数据展示 ---------------- */
const pageInfo: any = ref({
  ...commonPageConfig,
})

const pageChange = (info) => {
  pageInfo.value.curr = Number(info.curr);
  pageInfo.value.limit = Number(info.limit);
  getAnalysisResultPageData();
}

/** 每列字段对应的列宽计算结果。 */
const originResultTableFieldColumn = ref({});

/** 结果分析中的字段表格数据 */
const resultData: any = ref([]);

/** 不分页的全部数据 */
const fullResultData: any = ref([]);

/** 结果分析中的字段信息 */
const analysisResultTableFields: any = ref([]);

const analysisResultLoading = ref(false);

watch(
  resultData,
  (val: any[], oldVal) => {
    if (!analysisResultTableFields.value?.length) {
      originResultTableFieldColumn.value = {};
      return;
    }
    originResultTableFieldColumn.value = {};
    analysisResultTableFields.value.forEach((field, index) => {
      originResultTableFieldColumn.value[field.enName] = calcTableColumnWidth(
        val?.slice(0, 20) || [],
        field.enName,
        field.chName,
        24
      );
    });
  },
  {
    deep: true,
  }
);

const getAnalysisResultPageData = (isFull = false) => {
  analysisResultLoading.value = true;
  getAnonAnalyzePageData({
    pageIndex: pageInfo.value.curr,
    pageSize: isFull ? -1 : pageInfo.value.limit,
    taskExecGuid: taskExecGuid.value,
  }).then((res: any) => {
    analysisResultLoading.value = false;
    if (res?.code == proxy.$passCode) {
      if (isFull) {
        fullResultData.value = [];
        res.data?.records?.forEach(d => {
          let obj = {};
          analysisResultTableFields.value.forEach(t => {
            obj[t.enName] = d.fieldValue?.[t.enName];
          });
          obj['equivalenceClassNum'] = changeNum(d.equivalenceClassNum || 0, 0);
          obj['reIdentifyRisk'] = changeNum(d.reIdentifyRisk || 0, 2);
          obj['isGtThreshold'] = d.isGtThreshold;
          fullResultData.value.push(obj);
        });
        resultData.value = fullResultData.value.slice(0, pageInfo.value.limit);
        pageInfo.value.rows = fullResultData.value.length;
      } else {
        resultData.value = [];
        res.data?.records?.forEach(d => {
          let obj = {};
          analysisResultTableFields.value.forEach(t => {
            obj[t.enName] = d.fieldValue?.[t.enName];
          });
          obj['equivalenceClassNum'] = changeNum(d.equivalenceClassNum || 0, 0);
          obj['reIdentifyRisk'] = changeNum(d.reIdentifyRisk || 0, 2);
          obj['isGtThreshold'] = d.isGtThreshold;
          resultData.value.push(obj);
        });
        pageInfo.value.rows = res.data?.totalRows ?? 0;
      }
    } else {
      proxy.$ElMessage.error(res.msg);
    }
  })
}

const downPromise: any = ref()

const isWordStyle = ref(false);
/** 下载评估报告 */
const transfer = () => {
  isWordStyle.value = true;
}

const domClone: any = ref(null);

const resultReportRef = ref();

const convertHtml2Img = (dom, domClone) => {
  const element = <HTMLElement>dom.querySelector('.kpi-content')
  if (!element) {
    return Promise.resolve();
  }
  return html2canvas(element, {
    allowTaint: true,
    useCORS: true,
    scale: 2,
  }).then((canvas: any) => {
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
    element.parentNode && ((<HTMLElement>element.parentNode).scrollTop = 0);
    let url = canvas.toDataURL('image/jpeg');
    let img = document.createElement('img');
    if (url) {
      // img.src = url.split(',')[1];
      img.src = url;
      img.width = 620;
      img.height = 265;
      img.crossOrigin = 'Anonymous';
    }
    const copyElement = <HTMLElement>domClone.querySelector('.kpi-content')
    copyElement.parentNode?.replaceChild(img, copyElement);
  })
}

const loadingText = ref('');

const downloadLoading = ref(false);

const getHTML = (reportResultContent) => {
  let html = reportResultContent;
  html = html.replace(/"/g, "'");
  return html;
};

const downloadWord = () => {
  if (downPromise.value) {
    return;
  }
  let dom = domClone.value || (domClone.value = document.createElement('div'));
  let report = resultReportRef.value?.report;
  dom.innerHTML = report?.innerHTML;
  loadingText.value = '报告正在下载中,请勿关闭浏览器...';
  downloadLoading.value = true;
  downPromise.value = convertHtml2Img(report, dom).then(() => {
    htmlToWord({ html: encodeURIComponent(`<div>${getHTML(dom.innerHTML)}</div>`) }).then((res: any) => {
      downPromise.value = null
      loadingText.value = '';
      downloadLoading.value = false;
      if (res && !res.msg) {
        download(res, (route.query.taskName || oldAnonTaskValueInfo.value.taskName) + '_匿名化评估报告.docx', 'word')
      } else {
        res?.msg && ElMessage.error(res?.msg);
      }
    })
  }).catch(() => {
    downPromise.value = null;
  });
}

onUnmounted(() => {
  refreshTimer.value && clearInterval(refreshTimer.value);
  refreshTimer.value = null;
  if (folderRefreshTimer.value) {
    clearInterval(folderRefreshTimer.value);
    folderRefreshTimer.value = null;
  }
    
  // 清理未完成的Promise引用
  if (getResultPromise.value) {
    getResultPromise.value = null;
  }
  
  if (promise.value) {
    promise.value = null;
  }
  
  if (downPromise.value) {
    downPromise.value = null;
  }
  
  // 清理其他可能的异步操作引用
  if (getParentAreaPromise.value) {
    getParentAreaPromise.value = null;
  }

  if (domClone.value) {
    domClone.value = null;
  }

  window.removeEventListener('resize', handleResize);
  
})

</script>

<style lang="scss" scoped>
.top_tool_wrap {
  width: 100%;
  height: 72px;
  margin: 8px 0 0px;
  display: flex;
  justify-content: center;
  align-items: center;

  :deep(.el-steps) {
    width: 60%;
  }
}

.bottom_tool_wrap {
  height: 40px;
  padding: 0 16px;
  border-top: 1px solid #d9d9d9;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content_main {
  height: calc(100% - 40px);
  padding: 0 16px;
  overflow: hidden auto;
}

.operator_panel_wrap {
  padding-bottom: 12px;
}

.wait-result-div {
  height: 250px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .loading-img {
    width: 40px;
    height: 40px;
    margin-bottom: 18px;
  }

  .desc {
    color: #999;
    margin-bottom: 18px;
    margin-left: 26px;
  }

  :deep(.el-icon.failed) {
    color: #E63E33;
    width: 32px;
    height: 32px;
    margin-bottom: 8px;

    svg {
      width: 32px;
      height: 32px;
    }
  }

  .error-desc {
    color: #E63E33;
    font-size: 14px;
    line-height: 21px;
    margin-bottom: 8px;
    font-weight: 600;
  }
}

.analysis-result-main {
  min-height: 250px;

  .value-desc {
    font-size: 14px;
    color: #212121;
    line-height: 21px;
  }

  .result-title {
    font-size: 16px;
    color: #212121;
    line-height: 24px;
    font-weight: 600;
    margin-bottom: 6px;
  }

  .result-title-h1 {
    color: #212121;
    font-weight: 600;
    font-size: 24px;
    text-align: center;
    line-height: 36px;
    margin-top: 12px;
  }

  .result-title-desc {
    color: #666;
    font-size: 14px;
    line-height: 21px;
    margin-top: 12px;
  }

  .kpi-content {
    display: flex;
    flex-direction: row;
    column-gap: 12px;
    row-gap: 12px;
    flex-wrap: wrap;
    margin-bottom: 20px;
  }

  .border-content {
    height: 76px;
    display: flex;
    flex-direction: column;
    align-items: left;
    padding-left: 16px;
    justify-content: center;
    border: 1px solid #d9d9d9;
    width: calc(20% - 8px);
    min-width: 228px;
    border-radius: 2px;
    padding-left: 16px;

    .number {
      font-weight: 700;
      font-size: 20px;
      color: #212121;
      line-height: 30px;
      margin-top: 2px;

      &.score-color {
        color: #FF5F1F;
      }
    }

    .text {
      font-size: 14px;
      line-height: 21px;
      color: #666666;
      display: flex;

      .el-icon {
        color: #b2b2b2;
      }
    }
  }

  .result-table-desc {
    font-size: 14px;
    color: #999999;
    line-height: 21px;
  }

  .row-two-main {
    margin-top: 18px;
    display: flex;

    .table-one {
      width: 586px;

      &.border {
        border: 1px solid #d9d9d9;
        padding: 14px 18px 18px;
      }
    }

    .table-two {
      margin-left: 20px;
      width: calc(100% - 606px);

      &.border {
        border: 1px solid #d9d9d9;
        padding: 14px 18px 18px;
      }
    }
  }
}

.step-result {
  :deep(.v-content-wrap) {
    height: 100%;

    .el-card__body {
      height: calc(100% - 50px) !important;

      .card-body-content {
        height: 100%;
      }
    }

    .table_tool_wrap {
      padding: 0px;
    }
  }

}

:deep(.custom-form) {
  align-items: flex-start;

  .wid60.el-form-item {
    width: calc(66.66% - 12px);
  }
}

:deep(.fixwidth-form) {
  width: 500px;

  .autoWidth.el-form-item {
    width: 80px;
  }
}

.table-v2-main {
  width: 100%;
  height: 240px;
  margin-top: 2px;

  .main-placeholder {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    .empty-text {
      font-size: 14px;
      color: #b2b2b2;
    }
  }
}

:deep(.el-table-v2) {

  .el-table-v2__main {
    border: 1px solid #d9d9d9;
    background: #fff;
  }

  .el-table-v2__body tr.hover-row.el-table-v2__row--striped.current-row>td.el-table-v2__cell {
    background-color: var(--el-table-row-hover-bg-color);
  }

  .el-table-v2__body tr.current-row>td.el-table-v2__cell {
    background-color: var(--el-table-current-row-bg-color);
  }

  .el-table-v2__header {
    width: 100% !important;
  }

  .el-table-v2__header-cell,
  .el-table-v2__row-cell {
    border-right: 1px #d9d9d9 solid;
  }

  .el-table-v2__header-cell-text {
    color: #000;
    font-weight: normal;
  }

  .el-table-v2__empty {
    display: none !important;
  }

  .el-table-v2__header-row {
    border-bottom: 1px solid #d9d9d9;
  }
}

.empty-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 316px;
  width: 100%;
  flex-direction: column;

  .empty-text {
    font-size: 14px;
    color: #b2b2b2;
  }
}

:deep(.el-form) {
  .checkbox-cascader {
    display: flex;

    .el-cascader {
      margin-left: 8px;
    }
  }

  .checkbox-right {
    width: calc(100% - 50px);

    &.el-form-item {
      margin-bottom: 0px;
      margin-right: 0px;
      width: 100%;
    }
  }
}

:deep(.cell-tooltip-bg) {
  background-color: #fff1d4 !important;
}

:deep(.anlysis-content-wrap) {
  .card-title {
    justify-content: space-between;
  }
}

.folder-main {
  height: 170px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;

  .folder-title {
    font-size: 14px;
    color: #212121;
    font-weight: 600;
    margin-bottom: 16px;
    text-align: center;
    line-height: 21px;
    display: flex;
    justify-content: center;
  }

  :deep(.el-icon) {
    margin-right: 8px;
    width: 20px;
    height: 20px;

    &.fail {
      color: #E63E33;
    }

    &.success {
      color: #4FA55D;
    }

    svg {
      width: 100%;
      height: 100%;
    }
  }

  .folder-progress {
    width: 420px;

    .cnt {
      font-size: 14px;
      color: #212121;
      line-height: 21px;
      margin-top: 8px;
    }

    .desc {
      font-size: 14px;
      color: #999999;
      line-height: 21px;
      margin-top: 8px;
    }

    .el-button {
      margin-top: 12px;
    }
  }
}

.folder-main-content {
  height: 450px;
  padding: 8px 16px;

  :deep(.tree_panel) {
    height: 100%;

    .el-tree {
      overflow-y: auto;
    }
  }
}

.folder-foot {
  padding: 0px 16px 8px;
  line-height: 21px;
}

.preview-title {
  margin-bottom: 8px;
  font-size: 14px;
  color: #212121;
  line-height: 21px;
  font-weight: 600;
}

.folder-bottom {
  width: 100%;
  padding: 8px 0px 0px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>