OrderMonitoring.vue 39.8 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
<template>
  <div class="space-y-6">
    <!-- 页面标题和操作区 -->
    <div class="flex items-center justify-between">
      <h3 class="text-neutral-900 text-[20px] font-bold">登记订单管理</h3>
      <div class="flex">
        <el-button class="h-10 px-4" @click="handleExport">
          <Download class="h-4 w-4 mr-1" />
          导出数据
        </el-button>
        <el-button 
          type="primary"
          :disabled="selectedOrderIds.length === 0"
          class="h-10 pr-4 pl-0"
          @click="handleBatchReview"
        >
          <Check class="h-4 w-4 mr-1" />
          批量审核{{ selectedOrderIds.length > 0 ? ` (${selectedOrderIds.length})` : '' }}
        </el-button>
        <el-button 
          type="primary"
          class="h-10 pr-4 pl-0"
          @click="handleBatchModify"
        >
          <Edit3 class="h-4 w-4 mr-1" />
          批量修改
        </el-button>
      </div>
    </div>

    <!-- 筛选和搜索区域 -->
    <el-card>
      <div class="flex items-center gap-2 w-full p-6">
      <!-- 搜索框 -->
      <div class="relative" style="width: 200px;">
        <Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-neutral-500 z-10" />
        <el-input
          v-model="customerPhone"
          placeholder="客户号码"
          class="search-input text-ellipsis-input"
          clearable
        />
      </div>

      <div class="relative" style="width: 200px;">
        <Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-neutral-500 z-10" />
        <el-input
          v-model="chinaPersonPhone"
          placeholder="登记人手机号"
          class="search-input text-ellipsis-input"
          clearable
        />
      </div>

      <!-- 查询时间 -->
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        class="flex-1"
        placeholder="查询时间"
      />

      <!-- 全部业务状态 -->
      <el-select v-model="businessStatusFilter" placeholder="全部业务状态" class="flex-1 bg-gray-100">
        <el-option label="全部业务状态" value="" />
        <el-option label="待办理" value="-1" />
        <el-option label="办理成功" value="1" />
        <el-option label="已关闭" value="0" />
      </el-select>

      <!-- 全部审核状态 -->
      <el-select v-model="reviewStatusFilter" placeholder="全部审核状态" class="flex-1 bg-gray-100">
        <el-option label="全部审核状态" value="" />
        <el-option label="待审核" value="0" />
        <el-option label="审核通过" value="1" />
        <el-option label="审核驳回" value="2" />
      </el-select>

      <!-- 全部业务 -->
      <el-select v-model="businessNameFilter" placeholder="全部业务" class="flex-1 bg-gray-100">
        <el-option label="全部业务" value="" />
        <el-option 
          v-for="businessName in uniqueBusinessNames" 
          :key="businessName.jobId"
          :label="businessName.jobName" 
          :value="businessName.jobId" 
        />
      </el-select>

        <!-- 查询和重置按钮 -->
        <el-button type="primary" @click="handleSearch" class="h-10 px-4 shrink-0">
          查询
        </el-button>
        <el-button @click="handleReset" class="h-10 pr-4 pl-0 shrink-0">
          重置
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格区 -->
    <el-card>
      <div class="table-container">
        <el-table
          :data="paginatedOrders"
          class="order-table"
          stripe
          border
          @selection-change="handleSelectionChange"
        >
          <!-- 选择列 -->
          <el-table-column type="selection" width="50" :selectable="isRowSelectable" />
          
          <!-- 订单ID -->
          <el-table-column prop="id" label="订单ID" width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <span class="font-mono text-[14px]">{{ row.id }}</span>
            </template>
          </el-table-column>
          
          <!-- 能人 -->
          <el-table-column prop="chinaPersonName" label="能人" width="70" />
          
          <!-- 能人手机号 -->
          <el-table-column prop="chinaPersonPhone" label="能人手机号" width="130" show-overflow-tooltip>
            <template #default="{ row }">
              <span class="font-mono">{{ row.chinaPersonPhone }}</span>
            </template>
          </el-table-column>
          
          <!-- 客户号码 -->
          <el-table-column prop="customerPhone" label="客户号码" width="130" show-overflow-tooltip>
            <template #default="{ row }">
              <span class="font-mono">{{ row.customerPhone }}</span>
            </template>
          </el-table-column>
          
          <!-- 业务名称 -->
          <el-table-column prop="jobName" label="业务名称" min-width="100" />
          
          <!-- 登记时间 -->
          <el-table-column prop="createTime" label="登记时间" min-width="140" show-overflow-tooltip>
            <template #default="{ row }">
              <span class="font-mono">{{ $utils.detailTime(row.createTime) }}</span>
            </template>
          </el-table-column>
          
          <!-- 预计酬金 -->
          <el-table-column prop="preMoney" label="预计酬金" width="90" align="right">
            <template #default="{ row }">
              <span v-if="row.preMoney" class="font-mono">¥{{ row.preMoney }}</span>
              <span v-else class="text-neutral-400">--</span>
            </template>
          </el-table-column>
          
          <!-- 实际酬金 -->
          <el-table-column prop="realMoney" label="实际酬金" width="90" align="right">
            <template #default="{ row }">
              <span v-if="row.realMoney" class="font-mono">¥{{ row.realMoney }}</span>
              <span v-else class="text-neutral-400">--</span>
            </template>
          </el-table-column>
          
          <!-- CRM订单编号 -->
          <el-table-column prop="crmOrderId" label="CRM订单编号" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.crmOrderId" class="font-mono text-[14px]">{{ row.crmOrderId }}</span>
              <span v-else class="text-neutral-400">--</span>
            </template>
          </el-table-column>
          
          <!-- 业务状态 -->
          <el-table-column prop="status" label="业务状态" width="90" fixed="right">
            <template #default="{ row }">
              <span 
                :class="getBusinessStatusClass(row.status)"
                class="px-2 py-1 rounded text-xs font-medium"
              >
                {{ getBusinessStatusName(row.status) }}
              </span>
            </template>
          </el-table-column>
          
          <!-- 审核状态 -->
          <el-table-column prop="auditStatus" label="审核状态" width="90" fixed="right">
            <template #default="{ row }">
              <span 
                v-if="row.auditStatus"
                :class="getReviewStatusClass(row.auditStatus)"
                class="px-2 py-1 rounded text-xs font-medium"
              >
                {{ getReviewStatusName(row.auditStatus) }}
              </span>
              <span v-else class="text-neutral-400">-</span>
            </template>
          </el-table-column>
          
          <!-- 操作 -->
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <div class="flex gap-1">
                <el-button 
                  type="primary" 
                  link 
                  size="small"
                  @click="handleViewDetail(row)"
                >
                  详情
                </el-button>
                <el-button 
                  v-if="row.auditStatus === 0"
                  type="primary" 
                  link 
                  size="small"
                  @click="handleApprove(row)"
                >
                  审核
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="flex justify-between items-center mt-4 py-3 px-6">
        <div class="text-sm text-neutral-600">
           {{ totalElements }} 条数据,当前第 {{ currentPage }}/{{ totalPages }} 
          <span v-if="selectedOrderIds.length > 0" class="ml-2">
            ,已选择 {{ selectedOrderIds.length }} 
          </span>
        </div>
        <div class="flex items-center gap-4">
          <div class="flex items-center gap-2">
            <span class="text-sm text-neutral-600" style="width: 60px;">每页条数</span>
            <el-select v-model="pageSize" class="w-[180px]" style="width: 90px;" size="small" @change="handlePageSizeChange">
              <el-option label="10 条/页" :value="10" />
              <el-option label="20 条/页" :value="20" />
              <el-option label="50 条/页" :value="50" />
              <el-option label="100 条/页" :value="100" />
            </el-select>
          </div>
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="totalElements"
            layout="prev, pager, next"
            small
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog v-model="isReviewDialogOpen" title="订单审核" width="600px" class="single-review-dialog">
      <div class="space-y-4">
        <div class="grid grid-cols-2 gap-6">
          <!-- 左列 -->
          <div class="space-y-4">
            <div class="flex items-center">
              <label class="text-sm text-neutral-500 shrink-0">订单ID</label>
              <p class="text-sm text-neutral-900 font-mono" style="margin-left: 16px;">{{ reviewingOrder.id }}</p>
            </div>
            <div class="flex items-center">
              <label class="text-sm text-neutral-500 shrink-0">能人</label>
              <p class="text-sm text-neutral-900" style="margin-left: 16px;">{{ reviewingOrder.chinaPersonName }}</p>
            </div>
            <div class="flex items-center">
              <label class="text-sm text-neutral-500 shrink-0">CRM订单编号</label>
              <p class="text-sm text-neutral-900 font-mono" style="margin-left: 16px;">{{ reviewingOrder.crmOrderId || '-' }}</p>
            </div>
            <div class="flex items-center">
              <label class="text-sm text-neutral-500 shrink-0">实际酬金</label>
              <p class="text-sm font-mono text-green-600" style="margin-left: 16px;">¥{{ reviewingOrder.realMoney?.toFixed(2) || '--' }}</p>
            </div>
          </div>
          
          <!-- 右列 -->
          <div class="space-y-4">
            <div class="flex items-center">
              <label class="text-sm text-neutral-500 shrink-0">业务名称</label>
              <p class="text-sm text-neutral-900" style="margin-left: 16px;">{{ reviewingOrder.jobName }}</p>
            </div>
            <div class="flex items-center">
              <label class="text-sm text-neutral-500 shrink-0">客户号码</label>
              <p class="text-sm text-neutral-900 font-mono" style="margin-left: 16px;">{{ reviewingOrder.customerPhone }}</p>
            </div>
            <div class="flex items-center">
              <label class="text-sm text-neutral-500 shrink-0">预计酬金</label>
              <p class="text-sm font-mono text-blue-600" style="margin-left: 16px;">¥{{ reviewingOrder.preMoney?.toFixed(2) || '--' }}</p>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="flex justify-end gap-3">
          <el-button 
            type="danger"
            plain
            @click="handleReject"
          >
            <X class="h-4 w-4 mr-1" />
            驳回
          </el-button>
          <el-button 
            type="primary" 
            @click="handleConfirmApprove"
            class="bg-brand-primary"
          >
            <Check class="h-4 w-4 mr-1" />
            通过
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量审核对话框 -->
    <el-dialog v-model="isBatchReviewDialogOpen" title="批量审核订单" width="600px" class="batch-review-dialog">
      <div class="space-y-4">
        
        <div class="bg-blue-50 p-4 rounded-lg">
          <p class="text-sm text-neutral-600 mb-2">待审核订单列表({{ batchReviewOrders.length }}</p>
          <div class="max-h-60 overflow-y-auto space-y-2">
            <div 
              v-for="order in batchReviewOrders" 
              :key="order.id"
              class="bg-white p-3 rounded border border-blue-100"
            >
              <div class="flex items-center justify-between">
                <div class="flex-1">
                  <p class="text-sm font-medium text-neutral-900">订单ID: {{ order.id }}</p>
                  <p class="text-xs text-neutral-600 mt-1">
                    业务类型:{{ order.jobName }} | 
                    预计酬金:¥{{ order.preMoney?.toFixed(2)||'--' }}
                    <span v-if="order.realMoney">
                      | 实际酬金:¥{{ order.realMoney.toFixed(2) }}
                    </span>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 驳回原因输入框 -->
        <div v-if="showBatchRejectReason" class="space-y-2">
          <label class="text-neutral-700 text-sm">驳回原因 <span class="text-error">*</span></label>
          <el-input
            v-model="batchRejectReason"
            type="textarea"
            :rows="4"
            placeholder="请输入驳回原因"
            maxlength="200"
            show-word-limit
          />
        </div>
      </div>
      <template #footer>
        <div class="flex justify-end gap-3">
          <el-button 
            type="danger"
            plain
            @click="showBatchRejectReason = true"
            v-if="!showBatchRejectReason"
          >
            <X class="h-4 w-4 mr-1" />
            审核驳回
          </el-button>
          <el-button 
            type="danger"
            plain
            @click="handleConfirmBatchReject"
            v-if="showBatchRejectReason"
          >
            <X class="h-4 w-4 mr-1" />
            确认驳回
          </el-button>
          <el-button type="primary" @click="handleConfirmBatchApprove">
            <Check class="h-4 w-4 mr-1" />
            审核通过
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量修改对话框 -->
    <el-dialog v-model="isBatchModifyDialogOpen" title="批量修改酬金" width="720px" class="batch-modify-dialog">
      <div class="space-y-6">
        <!-- 第一步:下载模板 -->
        <div class="bg-gray-50 border border-gray-200 rounded-lg p-6">
          <div class="text-lg font-medium text-gray-900 mb-2">第一步:下载模板</div>
          <div class="text-sm text-gray-600 mb-4">
            请先下载模板文件,按照模板格式填写数据。
          </div>
          <el-button type="primary" size="large" @click="downloadBatchTemplate">
            <Download class="h-4 w-4 mr-2" />
            下载模板
          </el-button>
        </div>

        <!-- 第二步:上传文件 -->
        <div class="bg-gray-50 border border-gray-200 rounded-lg p-6">
          <div class="mb-4">
            <div class="text-lg font-medium text-gray-900 mb-2">第二步:上传文件</div>
            <div class="text-sm text-gray-600">
              上传填好的文件,系统将自动解析并验证数据。支持 xls/xlsx 格式,单次最多100条。
            </div>
          </div>
          <div class="space-y-4">
            <el-upload
              class="w-full"
              :show-file-list="false"
              accept=".xls,.xlsx"
              :auto-upload="false"
              :on-change="handleBatchFileChange"
            >
              <el-button type="primary" size="large">
                <Upload class="h-4 w-4 mr-2" />
                选择文件
              </el-button>
            </el-upload>
            
            <!-- 文件信息显示 -->
            <div v-if="batchFileName" class="bg-blue-50 border border-blue-200 rounded-lg p-4">
              <div class="flex items-center justify-between">
                <div class="text-sm text-[#3b82f6] font-mono">{{ batchFileName }}</div>
                <el-button 
                  size="small" 
                  text 
                  class="text-gray-600 hover:text-gray-800"
                  @click="clearSelectedFile"
                >
                  重新选择
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <div v-if="batchParseDone" class="space-y-3">
          <div class="text-sm">
            解析结果:
            <span class="text-green-600 font-medium">有效 {{ batchValidRows.length }}</span>
            <span class="mx-2 text-neutral-400">|</span>
            <span class="text-red-600 font-medium">无效 {{ batchInvalidRows.length }}</span>
          </div>

          <el-table :data="batchPreviewRows" height="260" border stripe>
            <el-table-column prop="id" label="订单ID" min-width="160" />
            <el-table-column prop="currentReward" label="当前酬金" width="100" align="right">
              <template #default="{ row }">
                <span class="font-mono">¥{{ '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="realMoney" label="新酬金" width="100" align="right">
              <template #default="{ row }">
                <span class="font-mono">¥{{ Number(row.realMoney).toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="校验" width="80">
              <template #default="{ row }">
                <el-tag v-if="!row.memo" type="success" size="small">有效</el-tag>
                <el-tag v-else type="danger" size="small">无效</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="memo" label="错误信息" min-width="180" show-overflow-tooltip />
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="closeBatchDialog">取消</el-button>
        <el-button
          type="primary"
          :disabled="!batchParseDone || batchInvalidRows.length>0"
          @click="openVerifyDialog"
        >
          提交审核
        </el-button>
      </template>
    </el-dialog>

    <!-- 审核驳回对话框 -->
    <el-dialog 
      v-model="isRejectDialogOpen" 
      title="审核驳回" 
      width="500px"
      class="reject-dialog"
    >
      <div>
        <el-form>
          <el-form-item label="驳回原因" required>
            <el-input
              v-model="rejectReason"
              type="textarea"
              :rows="4"
              placeholder="请输入驳回原因"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button 
            @click="isRejectDialogOpen = false"
            class="border-neutral-300"
          >
            取消
          </el-button>
          <el-button 
            type="primary"
            @click="handleConfirmReject"
            class="bg-brand-primary"
          >
            确认驳回
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 验证码对话框 -->
    <el-dialog v-model="isVerifyDialogOpen" title="安全验证" width="420px" class="verify-dialog">
      <div class="space-y-3">
        <p class="text-sm text-neutral-600">请输入6位验证码以确认批量修改。</p>
        <el-input
          v-model="verifyCode"
          maxlength="6"
          placeholder="输入验证码(演示用:123456"
          class="w-full"
        />
      </div>
      <template #footer>
        <el-button @click="isVerifyDialogOpen = false">取消</el-button>
        <el-button type="primary" :disabled="verifyCode.length !== 6" @click="applyBatchModify">
          验证并执行
        </el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch , getCurrentInstance} from 'vue'
import { ElMessage } from 'element-plus'
import { Download, Check, Edit3, Search, Upload, X } from 'lucide-vue-next'

const { $api,$utils } = getCurrentInstance()!.appContext.config.globalProperties

// Props
interface Props {
  orders?: any[]
  onViewOrderDetail?: (order: any) => void
  onUpdateOrder?: (updates: any) => void
}

const props = withDefaults(defineProps<Props>(), {
  orders: () => []
})

// Emits
const emit = defineEmits(['view-order-detail', 'update-order', 'orders-update'])

// 响应式数据
const customerPhone = ref('')
const chinaPersonPhone = ref('')
const dateRange = ref<[string, string] | null>(null)
const businessStatusFilter = ref('')
const reviewStatusFilter = ref('')
const businessNameFilter = ref('')
const selectedOrderIds = ref<string[]>([])
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框状态
const isReviewDialogOpen = ref(false)
const reviewingOrder = ref<any>(null)
const isBatchReviewDialogOpen = ref(false)
const batchReviewOrders = ref<any[]>([])
const batchRejectReason = ref('')
const showBatchRejectReason = ref(false)
const isRejectDialogOpen = ref(false)
const rejectReason = ref('')

// 批量修改状态
const isBatchModifyDialogOpen = ref(false)
const currentBatchStep = ref(0)
const batchFileName = ref('')
const batchParseDone = ref(false)
const batchPreviewRows = ref<any[]>([])
const batchValidRows = ref<any[]>([])
const batchInvalidRows = ref<any[]>([])
const isVerifyDialogOpen = ref(false)
const verifyCode = ref('')

// 订单数据
const orders = ref<any[]>([])

// 类型定义
type BusinessStatus = '待办理' | '办理成功' | '已关闭' | '-1' | '0' | '1'
type ReviewStatus = '待审核' | '审核通过' | '审核驳回' | '0' | '1' | '2'

interface OperationLog {
  id: string
  time: string
  operator: string
  action: string
  details: string
}

interface Order {
  id: string
  registerPersonPhone: string
  registerPersonName: string
  customerPhone: string
  businessName: string
  registerTime: string
  businessStatus: BusinessStatus
  reviewStatus?: ReviewStatus
  estimatedReward: number
  actualReward?: number
  crmOrderNumber?: string
  completeTime?: string
  paymentTime?: string
  rejectReason?: string
  closeReason?: string
  remarks?: string
  processRemark?: string
  operationLogs?: OperationLog[]
}

// 计算属性
const uniqueBusinessNames = ref<any[]>([])
const totalPages = ref('')
const totalElements = ref('')
const paginatedOrders = ref<any[]>([])

// 状态样式映射 - 使用浅色背景样式
const getBusinessStatusClass = (status: BusinessStatus) => {
  const statusMap: Record<string, string> = {
    '-1': 'bg-blue-100 text-blue-800',
    '1': 'bg-green-100 text-green-800',
    '0': 'bg-gray-100 text-gray-800',
    '待办理': 'bg-blue-100 text-blue-800',
    '办理成功': 'bg-green-100 text-green-800',
    '已关闭': 'bg-gray-100 text-gray-800'
  }
  return statusMap[status] || 'bg-gray-100 text-gray-800'
}
const getBusinessStatusName = (status: BusinessStatus) => {
  const statusMap: Record<string, string> = {
    '-1': '待办理',
    '1': '办理成功',
    '0': '已关闭',
    '待办理': '待办理',
    '办理成功': '办理成功',
    '已关闭': '已关闭'
  }
  return statusMap[status] || ''
}

const getReviewStatusClass = (status: ReviewStatus) => {
  const statusMap: Record<string, string> = {
    '0': 'bg-purple-100 text-purple-800',
    '1': 'bg-green-100 text-green-800',
    '2': 'bg-orange-100 text-orange-800',
    '待审核': 'bg-purple-100 text-purple-800',
    '审核通过': 'bg-green-100 text-green-800',
    '审核驳回': 'bg-orange-100 text-orange-800'
  }
  return statusMap[status] || 'bg-gray-100 text-gray-800'
}
const getReviewStatusName = (status: ReviewStatus) => {
  const statusMap: Record<string, string> = {
    '0': '待审核',
    '1': '审核通过',
    '2': '审核驳回',
    '待审核': '待审核',
    '审核通过': '审核通过',
    '审核驳回': '审核驳回'
  }
  return statusMap[status] || '--'
}

// 判断行是否可选择(只有待审核的订单才能被选择)
const isRowSelectable = (row: any) => {
  return row.auditStatus === 0
}

// 事件处理
const handleSearch = () => {
  currentPage.value = 1
  // 清空选中状态,防止按钮禁用问题
  selectedOrderIds.value = []

  queryOrder()
}

const handleReset = () => {
  customerPhone.value = ''
  chinaPersonPhone.value = ''
  dateRange.value = null
  businessStatusFilter.value = ''
  reviewStatusFilter.value = ''
  businessNameFilter.value = ''
  currentPage.value = 1
  ElMessage.success('已重置筛选条件')
}

const handleSelectionChange = (selection: any[]) => {
  selectedOrderIds.value = selection.map(item => item.id)
}

const handleExport = async () => {

  let start = ''
  let end = ''
  if(dateRange.value){
    start = new Date(dateRange.value[0]).getTime()+''
    end = (new Date(dateRange.value[1]).getTime()+24*60*60*1000-1)+''
  }

  const res = await $api.exportOrderList({
    customerPhone: customerPhone.value,
    chinaPersonPhone: chinaPersonPhone.value,
    startTime: start,
    endTime: end,
    status: businessStatusFilter.value,
    auditStatus: reviewStatusFilter.value,
    jobId: businessNameFilter.value,
    page: currentPage.value,
    pageSize: pageSize.value
  })

  if(res.type == 'blob') {
    let fileJson = {
      content: res.value,
      fileType: 'xlsx',
      fileName: '登记订单数据'
    }
    $utils.exportExcel(fileJson)
  } else {
    let errorText
    try {
      errorText = res.value.msg
    } catch(e) {
      errorText = '网络异常,请稍后重试'
    }
    ElMessage.error(errorText)
  }
}

const handleBatchReview = () => {
  if (selectedOrderIds.value.length === 0) {
    ElMessage.error('请选择要审核的订单')
    return
  }

  // 确保只对待审核的订单进行批量审核
  const pendingOrders = paginatedOrders.value.filter(order => 
    selectedOrderIds.value.includes(order.id) && order.auditStatus === 0
  )
  if (pendingOrders.length === 0) {
    ElMessage.error('所选订单中没有待审核的订单')
    return
  }
  // 设置批量审核的订单列表并打开对话框
  batchReviewOrders.value = pendingOrders
  isBatchReviewDialogOpen.value = true
}

const handleBatchModify = () => {
  resetBatchState()
  isBatchModifyDialogOpen.value = true
}

const handleViewDetail = (order: any) => {
  let param = {...order}

  param.status += ''
  param.auditStatus += ''

  emit('view-order-detail', param)
}

const handleApprove = (order: any) => {
  reviewingOrder.value = order
  isReviewDialogOpen.value = true
}

const handleConfirmApprove = async () => {
  if (reviewingOrder.value) {
    const order = paginatedOrders.value.find(o => o.id === reviewingOrder.value.id)
    if (order) {
     try {
        const response = await $api.audioOrderList({
          list:[{
            id: order.id,
            auditStatus: '1'
          }]
        })
        
        if (response.c === 0) {
          ElMessage.success(`订单 ${reviewingOrder.value.id} 审核通过`)
          isReviewDialogOpen.value = false
          setTimeout(()=>{
            reviewingOrder.value = null
          },0)

          queryOrder()
        } else {
          ElMessage.error(response.m)
        }
      } catch (error) {
        
      }
    }
  }
}

const handleReject = () => {
  if (!reviewingOrder.value) return
  isRejectDialogOpen.value = true
}

const handleConfirmReject = async() => {
  if (!rejectReason.value.trim()) {
    ElMessage.error('请填写驳回原因')
    return
  }
  
  if (reviewingOrder.value) {
    const order = paginatedOrders.value.find(o => o.id === reviewingOrder.value.id)
    if (order) {
      try {
        const response = await $api.audioOrderList({
          list:[{
            id: order.id,
            auditStatus: '2',
            auditMemo: rejectReason.value
          }]
        })
        
        if (response.c === 0) {
          ElMessage.success(`订单 ${reviewingOrder.value.id} 已驳回`)
          isReviewDialogOpen.value = false
          isRejectDialogOpen.value = false
          setTimeout(()=>{
            reviewingOrder.value = null
            rejectReason.value = ''
          },0)

          queryOrder()
        } else {
          ElMessage.error(response.m)
        }
      } catch (error) {
        
      }
    }
  }
}

const handleConfirmBatchReject = async () => {
  if (batchReviewOrders.value.length === 0) {
    ElMessage.error('没有待审核的订单')
    return
  }

  let list: any[] = []
  batchReviewOrders.value.forEach(order => {
    list.push({
      id: order.id,
      auditStatus: '2',
      auditMemo: batchRejectReason.value
    })
  })

  const response = await $api.audioOrderList({
    list: list
  })
  
  if (response.c === 0) {
    ElMessage.success(`成功批量驳回 ${batchReviewOrders.value.length} 个订单`)

    isBatchReviewDialogOpen.value = false
    showBatchRejectReason.value = false
    setTimeout(() => {
      selectedOrderIds.value = []
      batchReviewOrders.value = []
      batchRejectReason.value = ''
    }, 0);

    queryOrder()
  } else {
    ElMessage.error(response.m)
  }
}

const handleConfirmBatchApprove = async () => {
  if (batchReviewOrders.value.length === 0) {
    ElMessage.error('没有待审核的订单')
    return
  }
  
  let list: any[] = []
  batchReviewOrders.value.forEach(order => {
    list.push({
      id: order.id,
      auditStatus: '1'
    })
  })

  const response = await $api.audioOrderList({
    list: list
  })
  
  if (response.c === 0) {
    ElMessage.success(`成功批量审核通过 ${batchReviewOrders.value.length} 个订单`)

    isBatchReviewDialogOpen.value = false
    setTimeout(() => {
      selectedOrderIds.value = []
      batchReviewOrders.value = []
    }, 0);

    queryOrder()
  } else {
    ElMessage.error(response.m)
  }
}

const handlePageSizeChange = () => {
  currentPage.value = 1

  queryOrder()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page

  queryOrder()
}

// 批量修改:模板下载
const downloadBatchTemplate = () => {
  try {
    // 创建下载链接
    const link = document.createElement('a')
    // 使用相对路径,确保本地和线上都能正常访问
    link.href = './static/file/order_tem.xlsx'
    link.download = '批量修改酬金模板.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('模板下载失败,请稍后重试')
  }
}

// 批量修改:重置状态
const resetBatchState = () => {
  currentBatchStep.value = 0
  batchFileName.value = ''
  batchParseDone.value = false
  batchPreviewRows.value = []
  batchValidRows.value = []
  batchInvalidRows.value = []
  verifyCode.value = ''
}

// 清除选中的文件
const clearSelectedFile = () => {
  batchFileName.value = ''
  batchParseDone.value = false
  batchPreviewRows.value = []
  batchValidRows.value = []
  batchInvalidRows.value = []
}

// CSV 简单解析
const parseCsv = (text: string): string[][] => {
  // 简易 CSV:按行分割,再按逗号分割,不处理引号嵌套的复杂情况
  return text
    .split(/\r?\n/)
    .map(line => line.trim())
    .filter(line => line.length > 0)
    .map(line => line.split(',').map(col => col.trim()))
}

// 校验并映射为预览行
const buildPreviewRows = (list:any[]) => {
  const preview: any[] = []
  const valid: any[] = []
  const invalid: any[] = []

  list.forEach(item=>{
    preview.push(item)

    if(item.memo){
      invalid.push(item)
    }else{
      valid.push(item)
    }
  })

  return { preview, valid, invalid }
}

// 上传变更
const handleBatchFileChange = async (file: any) => {
  if (!file?.raw) return
  const raw: File = file.raw

  // 验证文件大小(2MB)
  const maxSize = 2 * 1024 * 1024
  if (raw.size > maxSize) {
    ElMessage.error('文件大小超过2MB限制,请压缩后重新上传')
    return
  }

  // 验证文件格式
  const fileName = raw.name.toLowerCase()
  if (!fileName.endsWith('.csv') && !fileName.endsWith('.xlsx')) {
    ElMessage.error('目前仅支持 csv和xlsx 格式的文件')
    return
  }

  batchFileName.value = raw.name

  try {
      const fd = new FormData()
      fd.append('file', raw)

      const response = await $api.updateOrderListMoney(fd)
      if(response.c === 0){
        const { preview, valid, invalid } = buildPreviewRows(response.d.list)

        batchPreviewRows.value = preview
        batchValidRows.value = valid
        batchInvalidRows.value = invalid
        batchParseDone.value = true
        if (valid.length === 0) {
          ElMessage.warning('未检测到有效记录,请检查文件内容')
        }

      }else{
        ElMessage.error(response.m)
      }
  } catch (error) {
    ElMessage.error('读取文件失败,请重试')
  }

}

const closeBatchDialog = () => {
  isBatchModifyDialogOpen.value = false
}

const openVerifyDialog = async () => {
  const response = await $api.updateOrderMoney({
    list: batchPreviewRows.value
  })

  if(response.c === 0){
    ElMessage.success(`成功修改 ${batchPreviewRows.value.length} 个订单`)

    isVerifyDialogOpen.value = false
    isBatchModifyDialogOpen.value = false
    setTimeout(()=>{
      resetBatchState()
    },0)
    queryOrder()
  }else{
    ElMessage.error(response.m)
  }
}

// 执行变更(演示校验码:123456)
const applyBatchModify = () => {
  if (verifyCode.value !== '123456') {
    ElMessage.error('验证码错误')
    return
  }
  const updates = batchValidRows.value
  if (updates.length === 0) {
    ElMessage.error('没有可执行的修改')
    return
  }
  // 应用到本地订单列表
  const newOrders = orders.value.map(o => {
    const u = updates.find(x => x.orderId === o.id)
    if (!u) return o
    return {
      ...o,
      actualReward: Number(u.newReward)
    }
  })
  orders.value = newOrders
  emit('orders-update', newOrders)

  ElMessage.success(`成功修改 ${updates.length} 个订单`)
  isVerifyDialogOpen.value = false
  isBatchModifyDialogOpen.value = false
  resetBatchState()
}

// 初始化数据
onMounted(() => {
  queryOrder()
  queryRule()
})
const queryRule = async ()=>{
  try {
    const response = await $api.queryAllRewardList({})
    
    if (response.c === 0 && response.d) {
      uniqueBusinessNames.value = response.d
    } else {
      
    }
  } catch (error) {
    
  }
}
const queryOrder = async ()=>{
  try {

    let start = ''
    let end = ''
    if(dateRange.value){
      start = new Date(dateRange.value[0]).getTime()+''
      end = (new Date(dateRange.value[1]).getTime()+24*60*60*1000-1)+''
    }

    const response = await $api.queryOrderList({
      customerPhone: customerPhone.value,
      chinaPersonPhone: chinaPersonPhone.value,
      startTime: start,
      endTime: end,
      status: businessStatusFilter.value,
      auditStatus: reviewStatusFilter.value,
      jobId: businessNameFilter.value,
      page: currentPage.value,
      pageSize: pageSize.value
    })

    if(response.c === 0){
      paginatedOrders.value = response.d.content

      totalElements.value = response.d.totalElements
      totalPages.value = response.d.totalPages
    }else{
      ElMessage.error(response.m)
    }
  } catch (error) {
    
  }
}

// 监听props变化
watch(() => props.orders, (newOrders) => {
  if (newOrders.length > 0) {
    orders.value = newOrders
  }
}, { deep: true })
</script>

<style scoped>

/* 搜索框样式 */
:deep(.search-input .el-input__wrapper) {
  background-color: #f3f3f5;
  border: none;
  padding-left: 36px;
  box-shadow: none;
  height: 40px;
}

:deep(.search-input .el-input__inner) {
  background-color: transparent;
}

/* 表格容器样式 */
.table-container {
  padding: 24px;
}

/* 轮廓与圆角已在全局 main.css 统一控制,这里不再重复设置,避免视觉上变粗 */

/* 表头样式 - 灰色背景 */
:deep(.order-table .el-table__header-wrapper) {
  background-color: #f3f4f6;
}

:deep(.order-table .el-table__header) {
  background-color: #f3f4f6;
}

/* 表头底色已在全局设置,这里仅保留需要的细化样式 */

/* 表格行样式 */
:deep(.order-table .el-table__row:hover) {
  background-color: #f8fafc;
}

/* 单元格边线已在全局统一(仅底部分隔,无纵向分割线) */

/* 表格头部圆角 */
:deep(.order-table .el-table__header tr th:first-child) {
  border-top-left-radius: 8px;
}

:deep(.order-table .el-table__header tr th:last-child) {
  border-top-right-radius: 8px;
}

/* 斑马纹样式优化 */
:deep(.order-table .el-table__row.el-table__row--striped) {
  background-color: #fafafa;
}

:deep(.order-table .el-table__row.el-table__row--striped:hover) {
  background-color: #f8fafc;
}

/* 表格选择框(含表头全选)可见性与主题色 */
:deep(.order-table .el-table__header .el-checkbox .el-checkbox__inner),
:deep(.order-table .el-table__body .el-checkbox .el-checkbox__inner) {
  background-color: #ffffff !important;
  border-color: #9ca3af !important; /* 中性灰,保证在灰色表头上可见 */
}

:deep(.order-table .el-checkbox .el-checkbox__inner:hover) {
  border-color: #3b82f6 !important;
}

:deep(.order-table .el-checkbox.is-checked .el-checkbox__inner),
:deep(.order-table .el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #3b82f6 !important; /* 主题蓝 */
  border-color: #3b82f6 !important;
}

:deep(.order-table .el-checkbox.is-checked .el-checkbox__inner::after) {
  border-color: #ffffff !important; /* 对勾为白色,更清晰 */
}

/* 固定列样式 */
:deep(.order-table .el-table__fixed-right) {
  box-shadow: -8px 0 16px 0px rgba(0, 0, 0, 0.12);
}

:deep(.order-table .el-table__fixed-right .el-table__cell) {
  background-color: white;
}

:deep(.order-table .el-table__fixed-right .el-table th.el-table__cell) {
  background-color: #f3f4f6 !important;
}

/* 操作列按钮样式 - 确保纯文字链接效果,无背景色 */
:deep(.el-button.el-button--primary.is-link) {
  background-color: transparent !important;
  background: transparent !important;
  background-image: none !important;
  border: none !important;
  padding: 4px 8px !important;
  box-shadow: none !important;
}

:deep(.el-button.el-button--primary.is-link:hover) {
  background-color: transparent !important;
  background: transparent !important;
  background-image: none !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.el-button.el-button--primary.is-link:focus) {
  background-color: transparent !important;
  background: transparent !important;
  background-image: none !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.el-button.el-button--primary.is-link:active) {
  background-color: transparent !important;
  background: transparent !important;
  background-image: none !important;
  border: none !important;
  box-shadow: none !important;
}

/* 固定列样式优化 */
:deep(.el-table__fixed-right) {
  box-shadow: -8px 0 16px 0px rgba(0, 0, 0, 0.12), -4px 0 6px -2px rgba(0, 0, 0, 0.08) !important;
}

:deep(.el-table__fixed-right .el-table__cell) {
  background-color: white !important;
}

:deep(.el-table__fixed-right .el-table th.el-table__cell) {
  background-color: #f3f4f6 !important;
}

/* 日期范围选择器高度调整 */
:deep(.el-date-editor--daterange.el-input__wrapper) {
  height: 40px !important;
  min-height: 40px !important;
}

:deep(.el-date-editor--daterange .el-range-input) {
  height: 38px !important;
  line-height: 38px !important;
}
</style>