FeePlanList.vue 37.7 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
<template>
  <div>
    <a-card title="配送费配置" :bordered="false" class="list-table-card">
      <div class="list-toolbar">
        <div class="list-toolbar-left">
          <a-select
            v-if="isAdmin"
            v-model:value="selectedCityId"
            placeholder="选择租户"
            class="list-filter"
            @change="handleCityChange"
          >
            <a-select-option v-for="c in cityList" :key="c.id" :value="c.id">{{ c.name }}</a-select-option>
          </a-select>
          <div v-else class="managed-city-pill">当前租户:{{ currentCityName || `租户#${selectedCityId}` }}</div>
        </div>
        <div class="list-toolbar-right">
          <a-button type="primary" :disabled="!selectedCityId" @click="createPlan">新增方案</a-button>
        </div>
      </div>

      <div v-if="selectedCityId" class="plan-layout">
        <div class="plan-sidebar">
          <div class="plan-sidebar-header">
            <div>
              <div class="plan-sidebar-title">计价方案</div>
              <div class="plan-sidebar-subtitle">同一租户可维护多套外卖配送规则</div>
            </div>
          </div>
          <a-spin :spinning="planLoading">
            <div class="plan-list">
              <button
                v-for="item in planList"
                :key="item.id"
                type="button"
                class="plan-item"
                :class="{ active: item.id === selectedPlanId }"
                @click="selectPlan(item.id)"
              >
                <div class="plan-item-top">
                  <span class="plan-item-name">{{ item.name }}</span>
                  <a-tag v-if="item.isDefault === 1" color="green">默认</a-tag>
                </div>
                <div class="plan-item-bottom">
                  <span>{{ item.status === 1 ? '启用中' : '已停用' }}</span>
                  <span>排序 {{ item.listOrder ?? 0 }}</span>
                </div>
              </button>
              <a-empty v-if="!planList.length" description="暂无计价方案" />
            </div>
          </a-spin>
        </div>

        <div class="plan-content">
          <template v-if="currentPlan && config">
            <div class="plan-content-top">
              <div class="soft-note-card plan-note-card">
                <strong>当前配置说明</strong>
                <p>同一租户可维护多套配送费方案,并指定默认启用方案用于实时计价。</p>
              </div>

              <div class="plan-toolbar">
                <div class="plan-toolbar-meta">
                  <span class="plan-toolbar-eyebrow">当前编辑</span>
                  <strong>{{ currentPlan.name || '未命名方案' }}</strong>
                </div>
                <a-space wrap>
                  <a-button @click="copyPlan" :disabled="!selectedPlanId">复制当前方案</a-button>
                  <a-button @click="setDefaultPlan" :disabled="currentPlan.isDefault === 1 || currentPlan.status !== 1">设为默认</a-button>
                  <a-popconfirm title="确认删除当前方案?" @confirm="deletePlan">
                    <a-button danger :disabled="currentPlan.isDefault === 1">删除方案</a-button>
                  </a-popconfirm>
                </a-space>
                <div class="plan-toolbar-submit">
                  <span class="plan-toolbar-tip">支持先试算,再保存当前方案</span>
                  <a-space wrap>
                    <a-button @click="previewPlan" :loading="previewing">试算配送费</a-button>
                    <a-button type="primary" class="plan-save-button" @click="saveCurrentPlan" :loading="planSaving">保存当前方案</a-button>
                  </a-space>
                </div>
              </div>
            </div>

            <div class="plan-content-body">
              <div class="plan-section">
                <div class="plan-section-head">
                  <div class="plan-section-chip">基础</div>
                  <div class="soft-section-header">
                    <div class="soft-section-heading">
                      <h3 class="soft-section-title">方案基础信息</h3>
                      <p class="soft-section-subtitle">维护方案名称、状态和备注说明。</p>
                    </div>
                  </div>
                </div>

                <a-row :gutter="16">
                  <a-col :span="8">
                    <a-form-item label="方案名称">
                      <a-input v-model:value="currentPlan.name" placeholder="如:标准午高峰方案" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item label="状态">
                      <a-select v-model:value="currentPlan.status">
                        <a-select-option :value="1">启用</a-select-option>
                        <a-select-option :value="0">停用</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item label="排序">
                      <a-input-number v-model:value="currentPlan.listOrder" :min="0" style="width:100%" />
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-form-item label="备注">
                  <a-input v-model:value="currentPlan.remark" placeholder="可填写适用业务场景说明" />
                </a-form-item>
              </div>

              <a-card class="preview-card" :bordered="false">
                <template #title>草稿试算</template>
                <div class="soft-section-subtitle preview-subtitle">保存前可先按草稿参数试算配送费,确认距离、时段和附加项是否符合预期。</div>
                <a-row :gutter="12">
                  <a-col :span="6">
                    <a-form-item label="起点经度">
                      <a-input v-model:value="previewForm.startLng" placeholder="121.4737" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="6">
                    <a-form-item label="起点纬度">
                      <a-input v-model:value="previewForm.startLat" placeholder="31.2304" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="6">
                    <a-form-item label="终点经度">
                      <a-input v-model:value="previewForm.endLng" placeholder="121.4879" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="6">
                    <a-form-item label="终点纬度">
                      <a-input v-model:value="previewForm.endLat" placeholder="31.2492" />
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row :gutter="12">
                  <a-col :span="8">
                    <a-form-item label="重量(kg)">
                      <a-input-number v-model:value="previewForm.weight" :min="0" :step="0.1" style="width:100%" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item label="件数">
                      <a-input-number v-model:value="previewForm.pieces" :min="0" style="width:100%" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item label="服务时间戳(秒,可空)">
                      <a-input v-model:value="previewForm.serviceTime" placeholder="留空则按当前时间" />
                    </a-form-item>
                  </a-col>
                </a-row>
                <div v-if="previewResult" class="preview-result">
                  <a-tag color="processing">总配送费 {{ previewResult.totalFee ?? 0 }} 元</a-tag>
                  <a-tag>基础 {{ previewResult.moneyBasic ?? 0 }}</a-tag>
                  <a-tag>里程 {{ previewResult.moneyDistance ?? 0 }}</a-tag>
                  <a-tag>重量 {{ previewResult.moneyWeight ?? 0 }}</a-tag>
                  <a-tag>件数 {{ previewResult.moneyPiece ?? 0 }}</a-tag>
                  <a-tag>时段 {{ previewResult.moneyTime ?? 0 }}</a-tag>
                  <a-tag>预计送达 {{ previewResult.estimatedMinutes ?? 0 }} 分钟</a-tag>
                  <a-tag>里程 {{ previewResult.distance ?? 0 }} km</a-tag>
                  <a-tag v-if="previewResult.minFeeApplied === 1" color="gold">已触发保底 {{ previewResult.minFee ?? 0 }}</a-tag>
                  <a-tag v-if="previewResult.moneyTime > 0" color="purple">当前服务时间命中时段加价</a-tag>
                </div>
              </a-card>

              <a-form :model="config" layout="vertical">
                <div class="plan-section">
                  <div class="plan-section-head">
                    <div class="plan-section-chip">总览</div>
                    <div class="soft-section-header">
                      <div class="soft-section-heading">
                        <h3 class="soft-section-title">费用总览</h3>
                        <p class="soft-section-subtitle">基础费与保底费会参与最终总价计算。</p>
                      </div>
                    </div>
                  </div>
                  <a-row :gutter="16">
                    <a-col :span="12">
                      <a-form-item label="保底费用(元)">
                        <a-input-number v-model:value="config.type6.minFee" :min="0" :step="0.1" style="width:100%" />
                      </a-form-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-item label="基础费(元/单)">
                        <a-input-number v-model:value="config.type6.baseFee" :min="0" :step="0.1" style="width:100%" />
                      </a-form-item>
                    </a-col>
                  </a-row>
                </div>

                <div class="plan-section">
                  <div class="plan-section-head">
                    <div class="plan-section-chip">里程</div>
                    <div class="soft-section-header">
                      <div class="soft-section-heading">
                        <h3 class="soft-section-title">里程阶梯</h3>
                        <p class="soft-section-subtitle">先配置起步距离,再追加超出后的阶梯规则。</p>
                      </div>
                      <div class="soft-section-actions">
                        <a-button type="dashed" @click="addDistanceStep">新增阶梯段</a-button>
                      </div>
                    </div>
                  </div>
                  <a-row :gutter="16">
                    <a-col :span="12">
                      <a-form-item label="起步里程(km内)">
                        <a-input-number v-model:value="config.type6.distanceBasic" :min="0" :step="0.1" style="width:100%" />
                      </a-form-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-item label="起步费用(元)">
                        <a-input-number v-model:value="config.type6.distanceBasicMoney" :min="0" :step="0.1" style="width:100%" />
                      </a-form-item>
                    </a-col>
                  </a-row>
                  <div v-if="distanceSteps.length" class="soft-dashed-block">
                    <a-row v-for="(step, index) in distanceSteps" :key="index" :gutter="12" class="plan-dynamic-row">
                      <a-col :span="7">
                        <a-form-item :label="index === 0 ? '结束里程(km)' : ''">
                          <a-input-number v-model:value="step.endDistance" :min="0" :step="0.1" style="width:100%" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="7">
                        <a-form-item :label="index === 0 ? '每档里程(km)' : ''">
                          <a-input-number v-model:value="step.unitDistance" :min="0.1" :step="0.1" style="width:100%" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="7">
                        <a-form-item :label="index === 0 ? '每档加价(元)' : ''">
                          <a-input-number v-model:value="step.unitFee" :min="0" :step="0.1" style="width:100%" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="3">
                        <a-form-item :label="index === 0 ? '操作' : ''">
                          <a-button danger block @click="removeDistanceStep(index)">删除</a-button>
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </div>
                  <a-empty v-else description="暂无里程阶梯配置" />
                </div>

                <div class="plan-section">
                  <div class="plan-section-head">
                    <div class="plan-section-chip">重量</div>
                    <div class="soft-section-header">
                      <div class="soft-section-heading">
                        <h3 class="soft-section-title">重量计费</h3>
                        <p class="soft-section-subtitle">重量按首重和续重单价计算,可设置费用封顶。</p>
                      </div>
                    </div>
                  </div>
                  <a-row :gutter="16">
                    <a-col :span="12">
                      <a-form-item label="首重(kg)">
                        <a-input-number v-model:value="config.type6.weightFirst" :min="0" :step="0.1" style="width:100%" />
                      </a-form-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-item label="首重费用(元)">
                        <a-input-number v-model:value="config.type6.weightFirstFee" :min="0" :step="0.1" style="width:100%" />
                      </a-form-item>
                    </a-col>
                  </a-row>
                  <a-row :gutter="16">
                    <a-col :span="12">
                      <a-form-item label="续重单价(元/kg)">
                        <a-input-number v-model:value="config.type6.weightUnitFee" :min="0" :step="0.1" style="width:100%" />
                      </a-form-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-item label="封顶费用(元)">
                        <a-input-number v-model:value="config.type6.weightCapFee" :min="0" :step="0.1" style="width:100%" />
                      </a-form-item>
                    </a-col>
                  </a-row>
                </div>

                <div class="plan-section">
                  <div class="plan-section-head">
                    <div class="plan-section-chip">件数</div>
                    <div class="soft-section-header">
                      <div class="soft-section-heading">
                        <h3 class="soft-section-title">件数计费</h3>
                        <p class="soft-section-subtitle">适合按商品件数额外加价的场景。</p>
                      </div>
                      <div class="soft-section-actions">
                        <a-button type="dashed" @click="addPieceRule">新增件数区间</a-button>
                      </div>
                    </div>
                  </div>
                  <div v-if="pieceRules.length" class="soft-dashed-block">
                    <a-row v-for="(rule, index) in pieceRules" :key="index" :gutter="12" class="plan-dynamic-row">
                      <a-col :span="6">
                        <a-form-item :label="index === 0 ? '起始件数' : ''">
                          <a-input-number v-model:value="rule.startPiece" :min="0" style="width:100%" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="6">
                        <a-form-item :label="index === 0 ? '结束件数' : ''">
                          <a-input-number v-model:value="rule.endPiece" :min="0" style="width:100%" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item :label="index === 0 ? '费用(元)' : ''">
                          <a-input-number v-model:value="rule.fee" :min="0" :step="0.1" style="width:100%" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="4">
                        <a-form-item :label="index === 0 ? '操作' : ''">
                          <a-button danger block @click="removePieceRule(index)">删除</a-button>
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </div>
                  <a-empty v-else description="暂无件数区间配置" />
                </div>

                <div class="plan-section">
                  <div class="plan-section-head">
                    <div class="plan-section-chip">时段</div>
                    <div class="soft-section-header">
                      <div class="soft-section-heading">
                        <h3 class="soft-section-title">时段附加费</h3>
                        <p class="soft-section-subtitle">用于午晚高峰或夜间等时段加价。</p>
                      </div>
                      <div class="soft-section-actions">
                        <a-button type="dashed" @click="addTimePeriod">新增时段</a-button>
                      </div>
                    </div>
                  </div>
                  <div v-if="timePeriods.length" class="soft-dashed-block">
                    <a-row v-for="(period, index) in timePeriods" :key="index" :gutter="12" class="plan-dynamic-row">
                      <a-col :span="5">
                        <a-form-item :label="index === 0 ? '开始时间' : ''">
                          <a-input v-model:value="period.startText" placeholder="22:00" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="5">
                        <a-form-item :label="index === 0 ? '结束时间' : ''">
                          <a-input v-model:value="period.endText" placeholder="06:00" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="5">
                        <a-form-item :label="index === 0 ? '附加费(元)' : ''">
                          <a-input-number v-model:value="period.money" :min="0" :step="0.1" style="width:100%" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="5">
                        <a-form-item :label="index === 0 ? '状态' : ''">
                          <a-select v-model:value="period.isOpen">
                            <a-select-option :value="1">启用</a-select-option>
                            <a-select-option :value="0">关闭</a-select-option>
                          </a-select>
                        </a-form-item>
                      </a-col>
                      <a-col :span="4">
                        <a-form-item :label="index === 0 ? '操作' : ''">
                          <a-button danger block @click="removeTimePeriod(index)">删除</a-button>
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </div>
                  <a-empty v-else description="暂无时段附加费配置" />
                </div>

                <div class="plan-section plan-section-last">
                  <div class="plan-section-head">
                    <div class="plan-section-chip">展示</div>
                    <div class="soft-section-header">
                      <div class="soft-section-heading">
                        <h3 class="soft-section-title">预计送达与展示</h3>
                        <p class="soft-section-subtitle">控制预计送达时间和骑手可视距离。</p>
                      </div>
                    </div>
                  </div>
                  <a-row :gutter="16">
                    <a-col :span="12">
                      <a-form-item label="预计送达基础时间(分钟)">
                        <a-input-number v-model:value="config.distanceBasicTime" :min="0" style="width:100%" />
                      </a-form-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-item label="超出每km增加时间(分钟)">
                        <a-input-number v-model:value="config.distanceMoreTime" :min="0" style="width:100%" />
                      </a-form-item>
                    </a-col>
                  </a-row>
                  <a-form-item label="附近骑手显示范围(km)">
                    <a-input-number v-model:value="config.riderDistance" :min="0" :step="0.1" style="width:100%" />
                  </a-form-item>
                </div>
              </a-form>
            </div>
          </template>

          <div v-else class="plan-empty-state">
            <a-empty description="当前租户还没有配送费方案">
              <template #extra>
                <a-space>
                  <a-button type="primary" @click="initializeDefaultPlan" :loading="planSaving">初始化默认方案</a-button>
                  <a-button @click="createPlan" :loading="planSaving">新增空白方案</a-button>
                </a-space>
              </template>
            </a-empty>
          </div>
        </div>
      </div>

      <a-empty v-else description="请先选择租户" />
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { adminFeePlanApi } from '@/api'
import { useRoleSelectedCity } from '@/composables/useRoleSelectedCity'

type TimePeriodForm = {
  startText: string
  endText: string
  isOpen: number
  money: number | null
}

type DistanceStepForm = {
  endDistance: number | null
  unitDistance: number | null
  unitFee: number | null
}

type PieceRuleForm = {
  startPiece: number | null
  endPiece: number | null
  fee: number | null
}

const route = useRoute()
const {
  isAdmin,
  cityList,
  selectedCityId,
  currentCityName,
  loadCities,
} = useRoleSelectedCity()

const config = ref<any>(null)
const planList = ref<any[]>([])
const planLoading = ref(false)
const planSaving = ref(false)
const selectedPlanId = ref<number | null>(null)
const currentPlan = ref<any>(null)
const timePeriods = ref<TimePeriodForm[]>([])
const distanceSteps = ref<DistanceStepForm[]>([])
const pieceRules = ref<PieceRuleForm[]>([])
const previewing = ref(false)
const previewResult = ref<any>(null)
const previewForm = reactive({
  startLng: '',
  startLat: '',
  endLng: '',
  endLat: '',
  weight: 0,
  pieces: 1,
  serviceTime: '',
})

async function loadFeePlanCities() {
  const queryCityId = Number(route.query.cityId || 0) || undefined
  await loadCities(queryCityId)
  if (selectedCityId.value) {
    await loadPlanList(selectedCityId.value)
  }
}

async function handleCityChange() {
  previewResult.value = null
  await loadPlanList(selectedCityId.value)
}

async function loadPlanList(cityId?: number, preferPlanId?: number) {
  if (!cityId) return
  planLoading.value = true
  try {
    const res: any = await adminFeePlanApi.list(isAdmin.value ? cityId : undefined)
    planList.value = Array.isArray(res?.data) ? res.data : []
    const targetPlanId = preferPlanId || planList.value.find(item => item.isDefault === 1)?.id || planList.value[0]?.id
    if (targetPlanId) {
      await selectPlan(targetPlanId)
    } else {
      selectedPlanId.value = null
      currentPlan.value = null
      config.value = null
    }
  } finally {
    planLoading.value = false
  }
}

async function selectPlan(planId: number) {
  selectedPlanId.value = planId
  const res: any = await adminFeePlanApi.detail(planId, isAdmin.value ? selectedCityId.value : undefined)
  const detail = res?.data || {}
  currentPlan.value = {
    id: detail.id,
    name: detail.name || '',
    status: detail.status ?? 1,
    listOrder: detail.listOrder ?? 0,
    remark: detail.remark || '',
    isDefault: detail.isDefault ?? 0,
  }
  config.value = normalizeConfig(detail.config)
  distanceSteps.value = (config.value.type6.distanceSteps || []).map((step: any) => ({
    endDistance: step.endDistance ?? 0,
    unitDistance: step.unitDistance ?? 1,
    unitFee: step.unitFee ?? 0,
  }))
  pieceRules.value = (config.value.type6.pieceRules || []).map((rule: any) => ({
    startPiece: rule.startPiece ?? 0,
    endPiece: rule.endPiece ?? 0,
    fee: rule.fee ?? 0,
  }))
  timePeriods.value = (config.value.type6.times || []).map((period: any) => ({
    startText: minuteToText(period.start),
    endText: minuteToText(period.end),
    isOpen: period.isOpen === 0 ? 0 : 1,
    money: period.money ?? 0,
  }))
  previewResult.value = null
}

async function createPlan() {
  if (!selectedCityId.value) return
  planSaving.value = true
  try {
    const payload = {
      name: `方案${planList.value.length + 1}`,
      status: 1,
      listOrder: planList.value.length,
      remark: '',
      config: deepClone(config.value || normalizeConfig(null)),
    }
    const res: any = await adminFeePlanApi.create(payload, isAdmin.value ? selectedCityId.value : undefined)
    message.success('方案已创建')
    await loadPlanList(selectedCityId.value, res?.data)
  } catch (err: any) {
    message.error(err?.message || '方案创建失败')
  } finally {
    planSaving.value = false
  }
}

async function initializeDefaultPlan() {
  if (!selectedCityId.value) return
  planSaving.value = true
  try {
    const res: any = await adminFeePlanApi.initDefault(isAdmin.value ? selectedCityId.value : undefined)
    message.success('默认方案已初始化')
    await loadPlanList(selectedCityId.value, res?.data)
  } catch (err: any) {
    message.error(err?.message || '默认方案初始化失败')
  } finally {
    planSaving.value = false
  }
}

async function copyPlan() {
  if (!selectedPlanId.value || !selectedCityId.value) return
  const res: any = await adminFeePlanApi.copy(selectedPlanId.value, isAdmin.value ? selectedCityId.value : undefined)
  message.success('方案已复制')
  await loadPlanList(selectedCityId.value, res?.data)
}

async function deletePlan() {
  if (!selectedPlanId.value || !selectedCityId.value) return
  await adminFeePlanApi.del(selectedPlanId.value, isAdmin.value ? selectedCityId.value : undefined)
  message.success('方案已删除')
  await loadPlanList(selectedCityId.value)
}

async function setDefaultPlan() {
  if (!selectedPlanId.value || !selectedCityId.value) return
  if (currentPlan.value?.status !== 1) {
    message.error('请先启用当前方案,再设为默认')
    return
  }
  await adminFeePlanApi.setDefault(selectedPlanId.value, isAdmin.value ? selectedCityId.value : undefined)
  message.success('默认方案已更新')
  await loadPlanList(selectedCityId.value, selectedPlanId.value)
}

async function saveCurrentPlan() {
  if (!selectedPlanId.value || !currentPlan.value || !selectedCityId.value) return
  try {
    const payload = buildPlanPayload()
    planSaving.value = true
    await adminFeePlanApi.update(selectedPlanId.value, payload, isAdmin.value ? selectedCityId.value : undefined)
    message.success('方案保存成功')
    await loadPlanList(selectedCityId.value, selectedPlanId.value)
  } catch (err: any) {
    message.error(err?.message || '方案保存失败')
  } finally {
    planSaving.value = false
  }
}

async function previewPlan() {
  if (!selectedCityId.value) return
  try {
    const payload = buildPlanPayload()
    if (!previewForm.startLng || !previewForm.startLat || !previewForm.endLng || !previewForm.endLat) {
      message.error('请填写完整的试算经纬度')
      return
    }
    previewing.value = true
    const res: any = await adminFeePlanApi.preview({
      config: payload.config,
      calc: {
        startLng: previewForm.startLng,
        startLat: previewForm.startLat,
        endLng: previewForm.endLng,
        endLat: previewForm.endLat,
        weight: previewForm.weight ?? 0,
        pieces: previewForm.pieces ?? 0,
        serviceTime: previewForm.serviceTime ? Number(previewForm.serviceTime) : 0,
      },
    }, isAdmin.value ? selectedCityId.value : undefined)
    previewResult.value = res?.data || null
  } catch (err: any) {
    message.error(err?.message || '试算失败')
  } finally {
    previewing.value = false
  }
}

function buildPlanPayload() {
  if (!currentPlan.value) {
    throw new Error('请选择计价方案')
  }
  const planName = String(currentPlan.value.name || '').trim()
  if (!planName) {
    throw new Error('请填写方案名称')
  }
  const nextConfig = deepClone(config.value || normalizeConfig(null))
  nextConfig.type = [6]
  nextConfig.type6.baseSwitch = nextConfig.type6.baseFee > 0 ? 1 : 0
  nextConfig.type6.distanceSwitch = 1
  nextConfig.type6.weightSwitch =
    nextConfig.type6.weightFirst > 0 || nextConfig.type6.weightFirstFee > 0 || nextConfig.type6.weightUnitFee > 0 ? 1 : 0
  nextConfig.type6.pieceSwitch = pieceRules.value.length ? 1 : 0
  nextConfig.type6.distanceSteps = buildDistanceStepsPayload()
  nextConfig.type6.pieceRules = buildPieceRulesPayload()
  nextConfig.type6.times = buildTimesPayload()
  return {
    name: planName,
    status: currentPlan.value.status ?? 1,
    listOrder: currentPlan.value.listOrder ?? 0,
    remark: currentPlan.value.remark || '',
    config: nextConfig,
  }
}

function createDefaultType6() {
  return {
    minFee: 0,
    baseSwitch: 0,
    baseFee: 0,
    feeMode: 2,
    fixMoney: 0,
    distanceSwitch: 1,
    distanceBasic: 3,
    distanceBasicMoney: 4,
    distanceMoreMoney: 1.5,
    distanceType: 1,
    distanceSteps: [],
    weightSwitch: 1,
    weightFirst: 5,
    weightFirstFee: 0,
    weightUnitFee: 1,
    weightCapFee: 30,
    weightBasic: 0,
    weightBasicMoney: 0,
    weightMoreMoney: 0,
    weightType: 1,
    pieceSwitch: 0,
    pieceRules: [],
    times: [],
  }
}

function normalizeConfig(raw: any) {
  const next = raw || {}
  const type6 = { ...createDefaultType6(), ...(next.type6 || {}) }
  return {
    ...next,
    type: [6],
    type6: {
      ...type6,
      distanceSteps: Array.isArray(type6.distanceSteps) ? type6.distanceSteps : [],
      pieceRules: Array.isArray(type6.pieceRules) ? type6.pieceRules : [],
      times: Array.isArray(type6.times) ? type6.times : [],
    },
    distanceBasic: next.distanceBasic ?? 3,
    distanceBasicTime: next.distanceBasicTime ?? 30,
    distanceMoreTime: next.distanceMoreTime ?? 10,
    riderDistance: next.riderDistance ?? 3,
  }
}

function addTimePeriod() {
  timePeriods.value.push({ startText: '', endText: '', isOpen: 1, money: 0 })
}

function removeTimePeriod(index: number) {
  timePeriods.value.splice(index, 1)
}

function addDistanceStep() {
  distanceSteps.value.push({ endDistance: 0, unitDistance: 1, unitFee: 0 })
}

function removeDistanceStep(index: number) {
  distanceSteps.value.splice(index, 1)
}

function addPieceRule() {
  pieceRules.value.push({ startPiece: 0, endPiece: 0, fee: 0 })
}

function removePieceRule(index: number) {
  pieceRules.value.splice(index, 1)
}

function buildDistanceStepsPayload() {
  let prevEnd = config.value.type6.distanceBasic ?? 0
  return distanceSteps.value.map((step, index) => {
    const endDistance = step.endDistance ?? 0
    const unitDistance = step.unitDistance ?? 0
    const unitFee = step.unitFee ?? 0
    if (endDistance <= prevEnd) {
      throw new Error(`第${index + 1}条里程阶梯结束里程必须大于上一阶梯`)
    }
    if (unitDistance <= 0) {
      throw new Error(`第${index + 1}条里程阶梯每档里程必须大于0`)
    }
    prevEnd = endDistance
    return { endDistance, unitDistance, unitFee, listOrder: index }
  })
}

function buildPieceRulesPayload() {
  const payload = pieceRules.value
    .map((rule, index) => {
      const startPiece = rule.startPiece ?? 0
      const endPiece = rule.endPiece ?? 0
      if (startPiece > endPiece) {
        throw new Error(`第${index + 1}条件数区间起始值不能大于结束值`)
      }
      return { startPiece, endPiece, fee: rule.fee ?? 0, listOrder: index }
    })
    .sort((a, b) => a.startPiece - b.startPiece)

  for (let index = 1; index < payload.length; index += 1) {
    if (payload[index].startPiece <= payload[index - 1].endPiece) {
      throw new Error('件数区间不能重叠')
    }
  }
  return payload
}

function buildTimesPayload() {
  return timePeriods.value
    .map((period, index) => {
      const hasContent = period.startText || period.endText || period.money
      if (!hasContent) return null
      const start = textToMinute(period.startText, `第${index + 1}条时段开始时间格式错误`)
      const end = textToMinute(period.endText, `第${index + 1}条时段结束时间格式错误`)
      if (start === end) {
        throw new Error(`第${index + 1}条时段开始时间不能等于结束时间`)
      }
      return {
        start,
        end,
        isOpen: period.isOpen === 0 ? 0 : 1,
        money: period.money ?? 0,
      }
    })
    .filter(Boolean)
}

function textToMinute(text: string, errorMessage: string) {
  const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec((text || '').trim())
  if (!match) {
    throw new Error(errorMessage)
  }
  return Number(match[1]) * 60 + Number(match[2])
}

function minuteToText(value: number | null | undefined) {
  if (typeof value !== 'number' || Number.isNaN(value)) return ''
  const hour = Math.floor(value / 60)
  const minute = value % 60
  return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
}

function deepClone<T>(value: T): T {
  return JSON.parse(JSON.stringify(value))
}

onMounted(loadFeePlanCities)
</script>

<style scoped>
.plan-layout {
  display: grid;
  grid-template-columns: 280px minmax(0, 1fr);
  gap: 18px;
  min-height: 720px;
}

.plan-sidebar,
.plan-content {
  border-radius: 24px;
  border: 1px solid var(--line);
  background: var(--panel);
  padding: 18px;
}

.plan-content {
  display: flex;
  flex-direction: column;
  gap: 18px;
  min-width: 0;
}

.plan-content-top {
  position: sticky;
  top: 0;
  z-index: 2;
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding-bottom: 6px;
  background: var(--bg-color);
}

.plan-content-body {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.plan-sidebar-header,
.plan-toolbar,
.soft-section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.plan-sidebar-title,
.plan-item-name,
.soft-section-title {
  font-family: var(--font-display);
  color: var(--text-dark);
}

.plan-sidebar-title {
  font-size: 16px;
  font-weight: 700;
}

.plan-sidebar-subtitle,
.plan-item-bottom,
.soft-section-subtitle,
.plan-toolbar-eyebrow,
.plan-toolbar-tip,
.managed-city-pill {
  color: var(--text-soft);
  font-size: 12px;
}

.managed-city-pill {
  display: inline-flex;
  align-items: center;
  min-height: 36px;
  padding: 0 14px;
  border-radius: 999px;
  border: 1px solid var(--line);
  background: var(--panel-strong);
}

.plan-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 14px;
}

.plan-item {
  border: 1px solid var(--line);
  background: var(--panel-strong);
  border-radius: 18px;
  padding: 14px;
  text-align: left;
  cursor: pointer;
}

.plan-item.active {
  border-color: var(--brand);
  background: var(--panel-tint);
  box-shadow: var(--shadow-sm);
}

.plan-item-top,
.plan-item-bottom {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.plan-item-bottom {
  margin-top: 6px;
}

.plan-toolbar {
  flex-wrap: wrap;
  align-items: center;
  padding: 14px 16px;
  border: 1px solid var(--line);
  border-radius: 20px;
  background: var(--panel-strong);
  box-shadow: var(--shadow-sm);
}

.plan-toolbar-meta,
.plan-toolbar-submit {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.plan-toolbar-meta strong {
  color: var(--text-dark);
  font-size: 15px;
  line-height: 1.4;
}

.plan-toolbar-submit {
  margin-left: auto;
  align-items: flex-end;
}

.plan-save-button {
  min-width: 108px;
  height: 36px;
  padding-inline: 16px;
  border: none;
  border-radius: 12px;
  background: linear-gradient(135deg, #8c7cf0, #a98ff7 55%, #e5b5dc);
  box-shadow: var(--shadow-sm);
}

.plan-save-button:hover,
.plan-save-button:focus {
  background: linear-gradient(135deg, #8372ee, #a188f6 55%, #e2add7);
}

.plan-section {
  padding: 18px 20px 20px;
  border: 1px solid var(--line);
  border-radius: 22px;
  background: var(--panel-strong);
}

.plan-section-last {
  margin-bottom: 0;
}

.plan-section-head {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 16px;
}

.plan-section-chip {
  display: inline-flex;
  align-items: center;
  align-self: flex-start;
  min-height: 26px;
  padding: 0 12px;
  border-radius: 999px;
  background: var(--panel-strong);
  border: 1px solid var(--line-strong);
  color: var(--brand);
  font-size: 12px;
  font-weight: 700;
}

.soft-section-heading {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.soft-section-title {
  margin: 0;
  font-size: 18px;
  line-height: 1.35;
}

.soft-section-subtitle {
  margin: 0;
  line-height: 1.6;
}

.plan-dynamic-row {
  margin-bottom: 12px;
  align-items: flex-start;
}

.preview-card {
  border-radius: 16px;
  background: var(--panel-strong);
  border: 1px solid var(--line);
}

.preview-subtitle {
  margin-bottom: 14px;
}

.preview-result {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.plan-empty-state {
  min-height: 520px;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media (max-width: 960px) {
  .plan-layout {
    grid-template-columns: 1fr;
  }

  .plan-content-top {
    position: static;
    padding-bottom: 0;
    background: transparent;
  }

  .plan-toolbar,
  .soft-section-header,
  .plan-toolbar-submit {
    flex-direction: column;
    align-items: flex-start;
  }

  .plan-save-button {
    width: 100%;
  }
}
</style>