index.vue 44.5 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
<template>
    <view class="sell-page">
        <!-- 顶部导航 -->
        <!-- <nut-config-provider :theme-vars="themeVars">
            <nut-sticky top="0">
                <nut-navbar v-if="!isAuthMode && !isMyCarMode" left-show @on-click-back="goBack">
                    <template #content>
                        <view class="content">
                            <text class="title" style="font-size: 33rpx; font-weight: 500;">{{ isEditMode ? '编辑车源' : '发布车源' }}</text>
                        </view>
                    </template>
                    <template #left-show>
                        <RectLeft color="white" />
                    </template>
                </nut-navbar>
            </nut-sticky>
        </nut-config-provider> -->

        <!-- 表单内容 -->
        <view class="form-container">
            <!-- 车辆照片上传 -->
            <view class="form-section">
                <text class="section-title">添加车辆照片</text>
                <view class="upload-grid">
                    <!-- 正面照 -->
                    <view class="upload-item">
                        <!-- 上传按钮 -->
                        <view v-if="!uploadedImages.front" class="upload-button" @click="triggerUpload('front')">
                            <Plus class="upload-icon" />
                        </view>
                        <!-- 图片预览 -->
                        <view v-else class="image-preview" @click="previewImage(uploadedImages.front)">
                            <image :src="uploadedImages.front" class="preview-image" mode="aspectFill" />
                            <view class="delete-btn" @click.stop="deleteImage('front')">
                                <Close class="delete-icon" />
                            </view>
                        </view>
                        <text class="upload-label">正面照</text>
                    </view>

                    <!-- 左侧照 -->
                    <view class="upload-item">
                        <!-- 上传按钮 -->
                        <view v-if="!uploadedImages.left" class="upload-button" @click="triggerUpload('left')">
                            <Plus class="upload-icon" />
                        </view>
                        <!-- 图片预览 -->
                        <view v-else class="image-preview" @click="previewImage(uploadedImages.left)">
                            <image :src="uploadedImages.left" class="preview-image" mode="aspectFill" />
                            <view class="delete-btn" @click.stop="deleteImage('left')">
                                <Close class="delete-icon" />
                            </view>
                        </view>
                        <text class="upload-label">左侧照</text>
                    </view>

                    <!-- 右侧照 -->
                    <view class="upload-item">
                        <!-- 上传按钮 -->
                        <view v-if="!uploadedImages.right" class="upload-button" @click="triggerUpload('right')">
                            <Plus class="upload-icon" />
                        </view>
                        <!-- 图片预览 -->
                        <view v-else class="image-preview" @click="previewImage(uploadedImages.right)">
                            <image :src="uploadedImages.right" class="preview-image" mode="aspectFill" />
                            <view class="delete-btn" @click.stop="deleteImage('right')">
                                <Close class="delete-icon" />
                            </view>
                        </view>
                        <text class="upload-label">右侧照</text>
                    </view>

                    <!-- 其他 -->
                    <view class="upload-item">
                        <!-- 上传按钮 -->
                        <view v-if="!uploadedImages.other" class="upload-button" @click="triggerUpload('other')">
                            <Plus class="upload-icon" />
                        </view>
                        <!-- 图片预览 -->
                        <view v-else class="image-preview" @click="previewImage(uploadedImages.other)">
                            <image :src="uploadedImages.other" class="preview-image" mode="aspectFill" />
                            <view class="delete-btn" @click.stop="deleteImage('other')">
                                <Close class="delete-icon" />
                            </view>
                        </view>
                        <text class="upload-label">其他</text>
                    </view>
                </view>

                <!-- 图片预览组件 -->
                <nut-image-preview v-model:show="previewVisible" :images="previewImages" :init-no="previewIndex" @close="closePreview" />
            </view>

            <!-- 所在学校 -->
            <view class="form-section">
                <view class="form-item" @click="showSchoolPicker">
                    <view class="form-item-left">
                        <Location class="form-icon" />
                        <text class="form-label">所在学校</text>
                    </view>
                    <view class="form-item-right">
                        <text class="form-value" :class="{ 'form-value-selected': formData.school_name, 'form-value-placeholder': !formData.school_name }">{{ formData.school_name || '请选择' }}</text>
                        <Right class="arrow-icon" />
                    </view>
                </view>
            </view>

            <!-- 车辆详情表单 -->
            <nut-form ref="formRef" :model-value="formData">
                <view class="form-section">
                    <!--<!~~ 车型品牌 ~~>
                    <nut-form-item label-position="top" label="车型品牌" prop="brand" required
                        :rules="[{ required: true, message: '请选择车型品牌' }]">
                        <view class="form-item-content" @click="showBrandPicker">
                            <text class="form-value">{{ formData.brand || '请选择' }}</text>
                            <Right class="arrow-icon" />
                        </view>
                    </nut-form-item>

                    <!~~ 车辆型号 ~~>
                    <nut-form-item label-position="top" label="车辆型号" prop="model">
                        <view class="form-item-content" @click="showModelPicker">
                            <text class="form-value">{{ formData.model || '请选择' }}</text>
                            <Right class="arrow-icon" />
                        </view>
                    </nut-form-item>-->

                    <!-- 品牌型号选择(新版) -->
                    <nut-form-item label-position="top" label="品牌型号选择" prop="brandModel">
                        <view class="form-item-content" :class="{ 'form-item-disabled': isVerified }" @click="showBrandModelPicker">
                            <text class="form-value" :class="{ 'form-value-selected': formData.brand && formData.model, 'form-value-placeholder': !(formData.brand && formData.model), 'form-value-disabled': isVerified }">
                                {{ formData.brand && formData.model ? `${formData.brand} ${formData.model}` : '请选择品牌型号' }}
                            </text>
                            <Right class="arrow-icon" :class="{ 'arrow-icon-disabled': isVerified }" />
                        </view>
                    </nut-form-item>

                    <!-- 车辆出厂年份 -->
                    <nut-form-item label-position="top" label="车辆出厂年份" prop="manufacture_year">
                        <view class="form-item-content" @click="showYearPicker">
                            <text class="form-value" :class="{ 'form-value-selected': formData.manufacture_year, 'form-value-placeholder': !formData.manufacture_year }">{{ formData.manufacture_year || '请选择' }}</text>
                            <Right class="arrow-icon" />
                        </view>
                    </nut-form-item>

                    <!-- 新旧程度 -->
                    <nut-form-item label-position="top" label="新旧程度" prop="new_level">
                        <view class="form-item-content" @click="showConditionPicker">
                            <text class="form-value" :class="{ 'form-value-selected': formData.new_level, 'form-value-placeholder': !formData.new_level }">{{ formData.new_level || '请选择' }}</text>
                            <Right class="arrow-icon" />
                        </view>
                    </nut-form-item>

                    <!-- 行驶里程 -->
                    <nut-form-item label="行驶里程" prop="total_mileage_km" required
                        :rules="[{ required: true, message: '请输入行驶里程' }]">
                        <nut-input v-model="formData.total_mileage_km" placeholder="请输入" type="number" input-align="right" @input="validateMileageInput">
                            <template #right>
                                <text class="unit">公里</text>
                            </template>
                        </nut-input>
                    </nut-form-item>

                    <nut-config-provider :theme-vars="themeVars">
                    <!-- 续航里程 -->
                    <nut-form-item label="续航里程" prop="range_km">
                        <nut-input v-model="formData.range_km" placeholder="请输入" type="number" input-align="right" :disabled="isVerified" @click="validateRangeInput" @input="validateNumberInput($event, 'range_km', false)">
                            <template #right>
                                <text class="unit">公里</text>
                            </template>
                        </nut-input>
                    </nut-form-item>

                    <!-- 最高时速 -->
                    <nut-form-item label="最高时速" prop="max_speed_kmh">
                        <nut-input v-model="formData.max_speed_kmh" placeholder="请输入" type="number"
                            input-align="right" :disabled="isVerified" @click="validateMaxSpeedInput" @input="validateNumberInput($event, 'max_speed_kmh', false)">
                            <template #right>
                                <text class="unit">km/h</text>
                            </template>
                        </nut-input>
                    </nut-form-item>
                    </nut-config-provider>

                    <!-- 电池容量 -->
                    <nut-form-item label="电池容量" prop="battery_capacity_ah">
                        <nut-input v-model="formData.battery_capacity_ah" placeholder="请输入" type="number" input-align="right" @input="validateBatteryCapacityInput">
                            <template #right>
                                <text class="unit">Ah</text>
                            </template>
                        </nut-input>
                    </nut-form-item>

                    <!-- 电池损耗度 -->
                    <!-- <nut-form-item label-position="top" label="电池损耗度" prop="batteryWear">
                        <view class="form-item-content" @click="showBatteryWearPicker">
                            <text class="form-value">{{ formData.batteryWear || '请选择' }}</text>
                            <Right class="arrow-icon" />
                        </view>
                    </nut-form-item> -->

                    <!-- 刹车磨损度 -->
                    <nut-form-item label-position="top" label="刹车磨损度" prop="brake_wear_level">
                        <view class="form-item-content" @click="showBrakeWearPicker">
                            <text class="form-value" :class="{ 'form-value-selected': formData.brake_wear_level, 'form-value-placeholder': !formData.brake_wear_level }">{{ formData.brake_wear_level || '请选择' }}</text>
                            <Right class="arrow-icon" />
                        </view>
                    </nut-form-item>

                    <!-- 轮胎磨损度 -->
                    <nut-form-item label-position="top" label="轮胎磨损度" prop="tire_wear_level">
                        <view class="form-item-content" @click="showTireWearPicker">
                            <text class="form-value" :class="{ 'form-value-selected': formData.tire_wear_level, 'form-value-placeholder': !formData.tire_wear_level }">{{ formData.tire_wear_level || '请选择' }}</text>
                            <Right class="arrow-icon" />
                        </view>
                    </nut-form-item>
                </view>
            </nut-form>

            <!-- 价格信息 -->
            <view class="form-section">
                <view class="form-item">
                    <view class="form-item-left">
                        <Location class="form-icon" />
                        <text class="form-label">出让价格</text>
                    </view>
                    <view class="form-item-right">
                        <text class="price-symbol">¥</text>
                        <input v-model="formData.price" placeholder="请输入" type="digit" class="price-input" @input="validatePriceInput" />
                    </view>
                </view>

                <view class="form-item">
                    <view class="form-item-left">
                        <Location class="form-icon" />
                        <text class="form-label">市场价</text>
                    </view>
                    <view class="form-item-right">
                        <text class="market-price-symbol">¥</text>
                        <input v-model="formData.market_price" placeholder="请输入" type="digit"
                            class="market-price-input" @input="validateMarketPriceInput" />
                    </view>
                </view>
            </view>

            <!-- 车辆描述 -->
            <view class="form-section">
                <nut-textarea v-model="formData.note" placeholder="请描述车辆详情,如使用感受、车况特点等" :cursorSpacing="100" />
            </view>
        </view>

        <!-- 底部按钮 -->
        <view class="bottom-actions">
            <nut-button v-if="!isAuthMode" color="#fb923c" size="large" block @click="onPublish">
                {{ isEditMode ? '保存修改' : '确认发布' }}
            </nut-button>
            <nut-button v-else color="#fb923c" size="large" block @click="onPublish">
                确认发布
            </nut-button>
        </view>

        <!-- 选择器弹窗 -->
        <!-- 学校选择器 -->
        <nut-popup v-model:visible="schoolPickerVisible" position="bottom">
            <nut-picker v-model="schoolValue" :columns="schoolOptions" title="选择学校" @confirm="onSchoolConfirm"
                @cancel="schoolPickerVisible = false" />
        </nut-popup>

        <!-- TODO: 如果车型品牌选择其他,车辆型号选择其他型号,允许用户自己填写自定义的内容, 需要等待真实数据后再考虑  -->

        <!-- 品牌选择 -->
        <nut-popup v-model:visible="brandPickerVisible" position="bottom">
            <nut-picker v-model="brandValue" :columns="brandOptions" title="选择车型品牌" @confirm="onBrandConfirm"
                @cancel="brandPickerVisible = false" />
        </nut-popup>

        <!-- 型号选择 -->
        <nut-popup v-model:visible="modelPickerVisible" position="bottom">
            <nut-picker v-model="modelValue" :columns="modelOptions" title="选择车辆型号" @confirm="onModelConfirm"
                @cancel="modelPickerVisible = false" />
        </nut-popup>

        <!-- 品牌型号选择器组件 -->
        <BrandModelPicker ref="brandModelPickerRef" :brand-options="brandOptions" @confirm="onBrandModelConfirm" @cancel="onBrandModelCancel" />

        <!-- 年份选择 -->
        <nut-popup v-model:visible="yearPickerVisible" position="bottom">
            <nut-date-picker
                v-model="yearValue"
                title="选择出厂年份"
                type="year-month"
                :max-date="maxYearDate"
                @confirm="onYearConfirm"
                @cancel="yearPickerVisible = false"
            />
        </nut-popup>

        <!-- 新旧程度选择 -->
        <nut-popup v-model:visible="conditionPickerVisible" position="bottom">
            <nut-picker v-model="conditionValue" :columns="conditionOptions" title="选择新旧程度"
                @confirm="onConditionConfirm" @cancel="conditionPickerVisible = false" />
        </nut-popup>

        <!-- 电池损耗度选择 -->
        <!-- <nut-popup v-model:visible="batteryWearPickerVisible" position="bottom">
            <nut-picker v-model="batteryWearValue" :columns="wearLevelOptions" title="选择电池损耗度"
                @confirm="onBatteryWearConfirm" @cancel="batteryWearPickerVisible = false" />
        </nut-popup> -->

        <!-- 刹车磨损度选择 -->
        <nut-popup v-model:visible="brakeWearPickerVisible" position="bottom">
            <nut-picker v-model="brakeWearValue" :columns="wearLevelOptions" title="选择刹车磨损度"
                @confirm="onBrakeWearConfirm" @cancel="brakeWearPickerVisible = false" />
        </nut-popup>

        <!-- 轮胎磨损度选择 -->
        <nut-popup v-model:visible="tireWearPickerVisible" position="bottom">
            <nut-picker v-model="tireWearValue" :columns="wearLevelOptions" title="选择轮胎磨损度" @confirm="onTireWearConfirm"
                @cancel="tireWearPickerVisible = false" />
        </nut-popup>

        <!-- 收款说明弹框 -->
        <PaymentAgreementModal
            v-model="paymentAgreementVisible"
            @agree="handlePaymentAgreementAgree"
            @confirm="handlePaymentAgreementConfirm"
            @close="handlePaymentAgreementClose"
        />
    </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Plus, Right, Location, Close } from '@nutui/icons-vue-taro'
import Taro, { useDidShow } from '@tarojs/taro'
import BASE_URL from '@/utils/config';
import BrandModelPicker from '@/components/BrandModelPicker.vue'
import PaymentAgreementModal from '@/components/PaymentAgreementModal.vue'
import { checkPermission, PERMISSION_TYPES } from '@/utils/permission'
import './index.less'

// 导入接口
import { addVehicleAPI, editVehicleAPI, getVehicleDetailAPI } from '@/api/car';
import { getSchoolsAPI, getBrandsModelsAPI } from '@/api/other';


const themeVars = {
    inputDisabledColor: '#999'
}

/**
 * 返回上一页
 */
// eslint-disable-next-line no-unused-vars
const goBack = () => {
    Taro.navigateBack()
}

// 获取页面参数
const instance = Taro.getCurrentInstance()
const { id, mode, type, from } = instance.router?.params || {}
const isEditMode = ref(mode === 'edit' && id)
const isAuthMode = ref(type === 'auth' && id)
const isMyCarMode = ref(type === 'myCar' && id)
const carId = ref(id || '')

// 已上传图片的URL
const uploadedImages = reactive({
    front: '',
    left: '',
    right: '',
    other: ''
})

// 图片预览相关
const previewVisible = ref(false)
const previewImages = ref([])
const previewIndex = ref(0)

const closePreview = () => {
    previewVisible.value = false
}

// 表单数据
const formData = reactive({
    school_name: '',
    school_id: '',
    brand: '',
    model: '',
    brandModel: '', // 品牌型号组合字段,用于表单验证
    manufacture_year: '',
    new_level: '',
    total_mileage_km: '',
    range_km: '',
    max_speed_kmh: '',
    battery_capacity_ah: '',
    // batteryWear: '',
    brake_wear_level: '',
    tire_wear_level: '',
    price: '',
    market_price: '',
    note: '',
    // 车辆照片字段
    front_photo: '',
    left_photo: '',
    right_photo: '',
    other_photo: '',
    verification_status: '',
    status: '' // 车辆状态字段 (3=已上架, 5=已下架)
})

// 选择器显示状态
const schoolPickerVisible = ref(false)
const brandPickerVisible = ref(false)
const modelPickerVisible = ref(false)
const yearPickerVisible = ref(false)
const conditionPickerVisible = ref(false)
// const batteryWearPickerVisible = ref(false)
const brakeWearPickerVisible = ref(false)
const tireWearPickerVisible = ref(false)

// 收款说明弹框显示状态
const paymentAgreementVisible = ref(false)

// 新的品牌型号选择器状态
// 品牌型号选择器组件引用
const brandModelPickerRef = ref(null)

// 选择器值
const schoolValue = ref([])
const brandValue = ref([])
const modelValue = ref([])
const yearValue = ref(new Date())
const conditionValue = ref([])
// const batteryWearValue = ref([])
const brakeWearValue = ref([])
const tireWearValue = ref([])

// 年份选择器最大日期限制(当前年份的12月31日)
const maxYearDate = ref(new Date(new Date().getFullYear(), 11, 31))

// 计算属性:判断是否为已认证状态
const isVerified = computed(() => {
    return isEditMode.value && formData.verification_status === 5
})

/**
 * 显示已认证不能修改的提醒
 */
const showVerifiedTip = () => {
    Taro.showToast({
        title: '车辆已认证,该项不能修改',
        icon: 'none',
        duration: 2000
    })
}

// 选择器选项数据
const schoolOptions = ref([])
const brandOptions = ref([])
const modelOptions = ref([])



const conditionOptions = ref([
    { text: '9成新', value: '9成新' },
    { text: '8成新', value: '8成新' },
    { text: '7成新', value: '7成新' },
    { text: '6成新', value: '6成新' },
    { text: '5成新及以下', value: '5成新及以下' }
])

const wearLevelOptions = ref([
    { text: '全新', value: '全新' },
    { text: '轻微磨损', value: '轻微磨损' },
    { text: '中度磨损', value: '中度磨损' },
    { text: '重度磨损', value: '重度磨损' },
    { text: '需要更换', value: '需要更换' }
])

/**
 * 触发图片上传
 * @param {String} type - 图片类型 (front/left/right/other)
 */
const triggerUpload = (type) => {
    Taro.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
            const tempFilePath = res.tempFilePaths[0]
            uploadImage(tempFilePath, type)
        },
        fail: function () {
            Taro.showToast({
                title: '选择图片失败',
                icon: 'none'
            })
        }
    })
}

/**
 * 上传图片到服务器
 * @param {String} filePath - 图片文件路径
 * @param {String} type - 图片类型 (front/left/right/other)
 */
const uploadImage = (filePath, type) => {
    // 显示上传中提示
    Taro.showLoading({
        title: '上传中',
        mask: true
    })

    // 获取上传URL
    wx.uploadFile({
        url: BASE_URL + '/admin/?m=srv&a=upload',
        filePath,
        name: 'file',
        header: {
            'content-type': 'multipart/form-data',
        },
        success: function (res) {
            let upload_data = JSON.parse(res.data);
            Taro.hideLoading({
                success: () => {
                    if (res.statusCode === 200) {
                        uploadedImages[type] = upload_data.data.src;
                // 同时更新formData中对应的照片字段
                formData[`${type}_photo`] = upload_data.data.src;
                        Taro.showToast({
                            title: '上传成功',
                            icon: 'success'
                        })
                    } else {
                        Taro.showToast({
                            icon: 'error',
                            title: '服务器错误,稍后重试!',
                            mask: true
                        })
                    }
                }
            });
        },
        fail: function () {
            Taro.hideLoading({
                success: () => {
                    Taro.showToast({
                        icon: 'error',
                        title: '上传失败,稍后重试!',
                        mask: true
                    })
                }
            })
        }
    });
}

/**
 * 预览图片
 * @param {String} imageUrl - 图片URL
 */
const previewImage = (imageUrl) => {
    previewImages.value = [{ src: imageUrl }]
    previewIndex.value = 0
    previewVisible.value = true
}

/**
 * 删除图片
 * @param {String} type - 图片类型 (front/left/right/other)
 */
const deleteImage = (type) => {
    uploadedImages[type] = ''
    // 同时清空formData中对应的照片字段
    formData[`${type}_photo`] = ''
    Taro.showToast({
        title: '删除成功',
        icon: 'success'
    })
}

/**
 * 显示学校选择器
 */
const showSchoolPicker = () => {
    schoolPickerVisible.value = true
}

/**
 * 显示品牌选择器
 */
// const showBrandPicker = () => {
//     brandPickerVisible.value = true
// }

/**
 * 显示型号选择器
 */
// const showModelPicker = () => {
//     if (!formData.brand) {
//         Taro.showToast({
//             title: '请先选择品牌',
//             icon: 'none'
//         })
//         return
//     }
//     modelPickerVisible.value = true
// }

/**
 * 显示年份选择器
 */
const showYearPicker = () => {
    yearPickerVisible.value = true
}

/**
 * 显示新旧程度选择器
 */
const showConditionPicker = () => {
    conditionPickerVisible.value = true
}

/**
 * 显示电池损耗度选择器
 */
// const showBatteryWearPicker = () => {
//     batteryWearPickerVisible.value = true
// }

/**
 * 显示刹车磨损度选择器
 */
const showBrakeWearPicker = () => {
    brakeWearPickerVisible.value = true
}

/**
 * 显示轮胎磨损度选择器
 */
const showTireWearPicker = () => {
    tireWearPickerVisible.value = true
}

/**
 * 通用数字输入验证函数,限制范围在0-9999之间
 * @param {Object} event - 输入事件对象
 * @param {String} field - 字段名
 * @param {Boolean} allowDecimal - 是否允许小数,默认true
 */
const validateNumberInput = (event, field, allowDecimal = true) => {
    let value = event.detail.value

    // 只保留数字和小数点(如果允许),删除其他字符
    if (allowDecimal) {
        value = value.replace(/[^0-9.]/g, '')

        // 防止多个小数点,只保留第一个小数点
        const dotIndex = value.indexOf('.')
        if (dotIndex !== -1) {
            value = value.substring(0, dotIndex + 1) + value.substring(dotIndex + 1).replace(/\./g, '')
        }

        // 防止以小数点开头
        if (value.startsWith('.')) {
            value = '0' + value
        }
    } else {
        // 只允许整数
        value = value.replace(/[^0-9]/g, '')
    }

    // 限制范围在0-9999之间
    const numValue = parseFloat(value)
    if (numValue > 99999) {
        value = '99999'
    }

    // 使用 nextTick 确保视图更新
    Taro.nextTick(() => {
        formData[field] = value
    })
}

/**
 * 校验价格输入,只允许数字和小数点,范围0-99999
 * @param {Object} event - 输入事件对象
 */
const validatePriceInput = (event) => {
    validateNumberInput(event, 'price', true)
}

/**
 * 校验市场价格输入,只允许数字和小数点,范围0-99999
 * @param {Object} event - 输入事件对象
 */
const validateMarketPriceInput = (event) => {
    validateNumberInput(event, 'market_price', true)
}

/**
 * 校验行驶里程输入,只允许整数,范围0-99999
 * @param {Object} event - 输入事件对象
 */
const validateMileageInput = (event) => {
    validateNumberInput(event, 'total_mileage_km', false)
}

/**
 * 校验续航里程输入权限
 * @param {Object} event - 点击事件对象
 */
// eslint-disable-next-line no-unused-vars
const validateRangeInput = (event) => {
    if (isVerified.value) {
        showVerifiedTip()
        return
    }
}

/**
 * 校验最高时速输入权限
 * @param {Object} event - 点击事件对象
 */
// eslint-disable-next-line no-unused-vars
const validateMaxSpeedInput = (event) => {
    if (isVerified.value) {
        showVerifiedTip()
        return
    }
}

/**
 * 校验电池容量输入,允许小数,范围0-99999
 * @param {Object} event - 输入事件对象
 */
const validateBatteryCapacityInput = (event) => {
    validateNumberInput(event, 'battery_capacity_ah', true)
}

/**
 * 学校选择确认
 */
const onSchoolConfirm = ({ selectedValue, selectedOptions }) => {
    formData.school_id = selectedValue[0]
    formData.school_name = selectedOptions[0].text
    schoolPickerVisible.value = false
}

/**
 * 品牌选择确认
 */
const onBrandConfirm = ({ selectedValue }) => {
    formData.brand = selectedValue[0]
    formData.model = '' // 重置型号
    brandPickerVisible.value = false
}

/**
 * 型号选择确认
 */
const onModelConfirm = ({ selectedValue }) => {
    formData.model = selectedValue[0]
    modelPickerVisible.value = false
}

/**
 * 年份选择确认
 */
const onYearConfirm = ({ selectedValue }) => {
    formData.manufacture_year = `${selectedValue[0]}年`
    yearPickerVisible.value = false
}

/**
 * 新旧程度选择确认
 */
const onConditionConfirm = ({ selectedValue }) => {
    formData.new_level = selectedValue[0]
    conditionPickerVisible.value = false
}

/**
 * 电池损耗度选择确认
 */
// const onBatteryWearConfirm = ({ selectedValue }) => {
//     formData.batteryWear = selectedValue[0]
//     batteryWearPickerVisible.value = false
// }

/**
 * 刹车磨损度选择确认
 */
const onBrakeWearConfirm = ({ selectedValue }) => {
    formData.brake_wear_level = selectedValue[0]
    brakeWearPickerVisible.value = false
}

/**
 * 轮胎磨损度选择确认
 */
const onTireWearConfirm = ({ selectedValue }) => {
    formData.tire_wear_level = selectedValue[0]
    tireWearPickerVisible.value = false
}

/**
 * 显示品牌型号选择器
 */
const showBrandModelPicker = () => {
    if (isVerified.value) {
        showVerifiedTip()
        return
    }
    brandModelPickerRef.value?.show()
}

/**
 * 品牌型号选择确认回调
 */
const onBrandModelConfirm = (result) => {
    formData.brand = result.brand
    formData.model = result.model
    // 设置组合字段用于表单验证
    formData.brandModel = `${result.brand} ${result.model}`

    // Taro.showToast({
    //     title: `已选择 ${result.brand} ${result.model}`,
    //     icon: 'success',
    //     duration: 2000
    // })
}

/**
 * 品牌型号选择取消回调
 */
const onBrandModelCancel = () => {
    // 可以在这里处理取消逻辑
}

/**
 * 将文字转换为对应的数字分数
 */
const convertTextToScore = (text, type) => {
    if (type === 'condition') {
        const conditionMap = {
            '9成新': 5,
            '8成新': 4,
            '7成新': 3,
            '6成新': 2,
            '5成新及以下': 1
        }
        return conditionMap[text] || 0
    } else if (type === 'wear') {
        const wearMap = {
            '全新': 5,
            '轻微磨损': 4,
            '中度磨损': 3,
            '重度磨损': 2,
            '需要更换': 1
        }
        return wearMap[text] || 0
    }
    return 0
}

/**
 * 将数字分数转换为对应的文字
 */
const convertScoreToText = (score, type) => {
    if (type === 'condition') {
        const scoreMap = {
            5: '9成新',
            4: '8成新',
            3: '7成新',
            2: '6成新',
            1: '5成新及以下'
        }
        return scoreMap[score] || ''
    } else if (type === 'wear') {
        const scoreMap = {
            5: '全新',
            4: '轻微磨损',
            3: '中度磨损',
            2: '重度磨损',
            1: '需要更换'
        }
        return scoreMap[score] || ''
    }
    return ''
}

const createCar = async (data) => {
    // 新增车辆,且卖车时,op=review,表示只申请卖车审核
    const { code } = await addVehicleAPI({ ...data, op: 'review' })
    if (code) {
        Taro.hideLoading()
        // 发布成功,提示用户等待审核
        Taro.showModal({
            title: '提示',
            content: '发布成功,请等待审核',
            showCancel: false,
            confirmText: '知道了',
            success: (res) => {
                if (res.confirm) {
                    Taro.reLaunch({ url: '/pages/index/index' })
                }
            }
        })
    }
}

const updateCar = async (id, data) => {
    // 只编辑车辆时,op=edit,表示只编辑车辆信息
    // 编辑车辆,且申请卖车时,op=review,表示申请卖车审核
    const { code } = await editVehicleAPI({ id, ...data, op: isAuthMode.value ? 'review' : 'edit' })
    if (code) {
        Taro.hideLoading()
        Taro.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000,
            complete: () => {
                Taro.navigateBack()
            }
        })
    }
}

/**
 * 发布/保存车辆
 */
const onPublish = async () => {
    if (!validateForm()) return

    // 编辑模式下,如果车辆是上架状态,需要确认提示
    if (isEditMode.value && formData.status === 3) {
        Taro.showModal({
            title: '提示',
            content: '保存后, 车辆将下架,修改资料需等待审核后才能再上架,是否仍要提交修改?',
            confirmText: '确认保存',
            cancelText: '取消',
            success: (res) => {
                if (res.confirm) {
                    performSave()
                }
            }
        })
        return
    }

    // 直接保存
    performSave()
}

/**
 * 执行保存操作
 */
const performSave = async () => {
    const loadingTitle = isEditMode.value ? '保存中...' : '发布中...'
    Taro.showLoading({ title: loadingTitle })

    // 构建提交数据,将文字转换为数字
    const submitData = {
        ...formData,
        new_level: convertTextToScore(formData.new_level, 'condition'),
        brake_wear_level: convertTextToScore(formData.brake_wear_level, 'wear'),
        tire_wear_level: convertTextToScore(formData.tire_wear_level, 'wear')
    }

    if (isEditMode.value) {
        submitData.id = carId.value
    }

    // 在此处调用实际的API接口提交数据
    if (isEditMode.value) {
        await updateCar(carId.value, submitData)
    } else {
        await createCar(submitData)
    }
}

/**
 * 价格格式校验
 * @param {string} price 价格字符串
 * @returns {boolean} 是否为有效的价格格式
 */
const isValidPrice = (price) => {
    if (!price || price.toString().trim() === '') return false
    // 正则表达式:匹配数字和小数点,允许小数
    const priceRegex = /^\d+(\.\d+)?$/
    return priceRegex.test(price.toString().trim())
}

/**
 * 表单验证
 * @returns {boolean} 验证结果
 */
const validateForm = () => {
    // 检查是否至少上传了一张图片
    // const hasImages = formData.front_photo || formData.left_photo || formData.right_photo || formData.other_photo
    const hasImages = formData.front_photo
    if (!hasImages) {
        // Taro.showToast({ title: '请上传车辆图片', icon: 'none' })
        Taro.showToast({ title: '请上传车辆正面照', icon: 'none' })
        return false
    }

    // if (!formData.brand) {
    //     Taro.showToast({ title: '请选择车型品牌', icon: 'none' })
    //     return false
    // }

    // if (!formData.new_level) {
    //     Taro.showToast({ title: '请选择新旧程度', icon: 'none' })
    //     return false
    // }

    if (!formData.total_mileage_km || formData.total_mileage_km <= 0) {
        Taro.showToast({ title: '请输入正确的行驶里程', icon: 'none' })
        return false
    }

    // 校验出让价格(必填)
    if (!formData.price) {
        Taro.showToast({ title: '请输入出让价格', icon: 'none' })
        return false
    }

    if (!isValidPrice(formData.price)) {
        Taro.showToast({ title: '出让价格格式不正确,请输入有效数字', icon: 'none' })
        return false
    }

    // 校验市场价格(选填,但如果填写了必须格式正确)
    if (formData.market_price && !isValidPrice(formData.market_price)) {
        Taro.showToast({ title: '市场价格格式不正确,请输入有效数字', icon: 'none' })
        return false
    }

    return true
}

/**
 * 加载车辆数据(编辑模式)
 */
const loadCarData = async () => {
    if (!isEditMode.value || !carId.value) return

    try {
        Taro.showLoading({ title: '加载中...' })

        // 调用真实API获取车辆数据
        const { code, data } = await getVehicleDetailAPI({ id: carId.value })

        if (code) {
            // 响应数据
            const carData = data;

            // 填充表单数据,如果是数字则转换为文字
            Object.assign(formData, {
                school_id: carData.school_id,
                school_name: carData.school_name,
                brand: carData.brand,
                model: carData.model,
                manufacture_year: carData.manufacture_year,
                new_level: typeof carData.new_level === 'number' ? convertScoreToText(carData.new_level, 'condition') : carData.new_level,
                total_mileage_km: carData.total_mileage_km,
                range_km: carData.range_km,
                max_speed_kmh: carData.max_speed_kmh,
                battery_capacity_ah: carData.battery_capacity_ah,
                // batteryWear: carData.batteryWear,
                brake_wear_level: typeof carData.brake_wear_level === 'number' ? convertScoreToText(carData.brake_wear_level, 'wear') : carData.brake_wear_level,
                tire_wear_level: typeof carData.tire_wear_level === 'number' ? convertScoreToText(carData.tire_wear_level, 'wear') : carData.tire_wear_level,
                price: carData.price,
                market_price: carData.market_price,
                note: carData.note,
                verification_status: carData.verification_status,
                status: carData.status // 添加车辆状态字段
            })

            // 填充图片数据
            uploadedImages.front = carData.front_photo || ''
            uploadedImages.left = carData.left_photo || ''
            uploadedImages.right = carData.right_photo || ''
            uploadedImages.other = carData.other_photo || ''
            // 同时填充formData中的照片字段
            formData.front_photo = carData.front_photo || ''
            formData.left_photo = carData.left_photo || ''
            formData.right_photo = carData.right_photo || ''
            formData.other_photo = carData.other_photo || ''

            Taro.hideLoading()
        }
    } catch (error) {
        console.error('加载车辆数据失败:', error)
        Taro.hideLoading()
        Taro.showToast({
            title: '加载数据失败',
            icon: 'none'
        })
    }
}

/**
 * 加载学校列表
 */
const loadSchools = async () => {
    try {
        const { code, data } = await getSchoolsAPI()
        if (code && data) {
            schoolOptions.value = data.map(school => ({
                text: school.name,
                value: school.id
            }))
        }
    } catch (error) {
        console.error('加载学校列表失败:', error)
    }
}

/**
 * 加载品牌型号列表
 */
const loadBrandsModels = async () => {
    try {
        const { code, data } = await getBrandsModelsAPI()
        if (code && data) {
            // 转换品牌数据格式
            brandOptions.value = data.map(brand => ({
                text: brand.name,
                value: brand.id,
                models: brand.models || []
            }))
        }
    } catch (error) {
        console.error('加载品牌型号列表失败:', error)
    }
}

/**
 * 检查用户权限的通用函数
 */
const checkUserPermission = async () => {
    // 检查卖车权限
    const permissionResult = await checkPermission(PERMISSION_TYPES.SELL_CAR, {
        showToast: false,
        autoRedirect: false
    })

    // 如果没有权限,显示确认弹窗
    if (!permissionResult.hasPermission) {
        // 可以通过 permissionResult.missingFields 获取未通过校验的字段
        // 可以通过 permissionResult.validFields 获取已通过校验的字段
        Taro.showModal({
            title: '温馨提示',
            content: `您未填写${permissionResult.missingFields.includes('phone') ? '个人资料' : '收款信息'}, 将无法发布车辆`,
            cancelText: '关闭',
            confirmText: '立即设置',
            success: (res) => {
                if (res.confirm) {
                    if (permissionResult.missingFields.includes('phone')) {
                        // 用户信息未填写
                        Taro.redirectTo({
                            url: '/pages/register/index?target=sell'
                        })
                    } else if (permissionResult.missingFields.includes('name') || permissionResult.missingFields.includes('bank_id') || permissionResult.missingFields.includes('bank_no') || permissionResult.missingFields.includes('idcard') || permissionResult.missingFields.includes('bank_img') || permissionResult.missingFields.includes('idcard_1_img') || permissionResult.missingFields.includes('idcard_2_img') || permissionResult.missingFields.includes('idcard_effect_begin') || permissionResult.missingFields.includes('idcard_effect_end') || permissionResult.missingFields.includes('idcard_address')) {
                        // 收款信息未填写
                        Taro.redirectTo({
                            url: '/pages/collectionSettings/index?target=sell'
                        })
                    }
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
        return false
    }
    return true
}

// 页面加载时执行
onMounted(async () => {
    // 加载基础数据
    await Promise.all([
        loadSchools(),
        loadBrandsModels()
    ])

    if (isEditMode.value) {
        loadCarData()
    }

    // 默认权限检查逻辑
    const hasPermission = await checkUserPermission()
    if (hasPermission) {
        // 权限验证通过,显示收款说明弹框
        paymentAgreementVisible.value = true
    }

    // 动态修改标题
    // wx.setNavigationBarTitle({
    //     title: isEditMode.value ? '编辑车源' : '发布车源'
    // });
    // if (isAuthMode.value) {
    //     wx.setNavigationBarTitle({
    //         title: '发布车源'
    //     });
    // }
    if (isMyCarMode.value) {
        wx.setNavigationBarTitle({
            title: '编辑车源'
        });
    } else {
        wx.setNavigationBarTitle({
            title: '发布车源'
        });
    }
})

// 页面显示时执行(包括首次加载和从其他页面返回)
useDidShow(async () => {
    // 权限检查逻辑 - 仅在特殊情况下触发
    const pages = Taro.getCurrentPages()
    // const currentPage = pages[pages.length - 1]
    const prevPage = pages.length > 1 ? pages[pages.length - 2] : null

    let shouldCheckPermission = false

    // 第一个条件:如果当前页面没有上一页,判断参数有没有from=collectionSettings
    // if (!prevPage && from === 'collectionSettings') {
        // shouldCheckPermission = true
    // }
    // 如果当前页面有前一页,判断前一页是不是/pages/register/index返回过来的
    if (!prevPage && from === 'sell') {
        shouldCheckPermission = true
    }

    if (shouldCheckPermission) {
        const hasPermission = await checkUserPermission()
        if (hasPermission) {
            // 权限验证通过,显示收款说明弹框
            paymentAgreementVisible.value = true
        }
    }
})

/**
 * 处理收款说明弹框的同意操作
 */
const handlePaymentAgreementAgree = () => {
    // 用户同意收款协议,组件内部会处理关闭逻辑
    paymentAgreementVisible.value = false
    // 这里可以添加同意后的逻辑,比如更新用户状态等
    Taro.showToast({
        title: '已同意收款协议',
        icon: 'success'
    })
}

/**
 * 处理收款说明弹框的确认操作
 */
const handlePaymentAgreementConfirm = () => {
    // 用户确认收款说明,组件内部会处理关闭逻辑
    paymentAgreementVisible.value = false
    // 这里可以添加确认后的逻辑
    Taro.showToast({
        title: '已确认收款说明',
        icon: 'success'
    })
}

/**
 * 处理收款说明弹框的关闭操作
 */
const handlePaymentAgreementClose = () => {
    // 用户关闭收款说明弹框
    paymentAgreementVisible.value = false

    // 判断是否有上一页,如果有就返回上一页,没有则返回首页
    const pages = Taro.getCurrentPages()
    if (pages.length > 1) {
        // 有上一页,返回上一页
        Taro.navigateBack()
    } else {
        // 没有上一页,跳转到首页
        Taro.redirectTo({
            url: '/pages/index/index'
        })
    }
}
</script>