index.vue 35 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
<!--
 * @Date: 2022-09-19 14:11:06
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-08-12 18:08:16
 * @FilePath: /jgdl/src/pages/collectionSettings/index.vue
 * @Description: 收款设置
-->
<template>
  <view class="collection-settings">

    <!-- 设置列表 -->
    <view class="settings-list">
      <!-- 收款账号 -->
      <view class="setting-item" @click="openAccountModal">
        <view class="setting-left">
          <text class="setting-label">收款账号</text>
        </view>
        <view class="setting-right">
          <text class="setting-status"
            :class="{ 'status-set': accountInfo.bankName && accountInfo.bankAccount && accountInfo.bankImg }">
            {{ accountInfo.bankName && accountInfo.bankAccount && accountInfo.bankImg ? '已设置' : '未设置' }}
          </text>
          <!-- <text class="arrow">></text> -->
          <RectRight color="#999" size="10" />
        </view>
      </view>

      <!-- 身份信息 -->
      <view class="setting-item" @click="openIdentityModal">
        <view class="setting-left">
          <text class="setting-label">身份信息</text>
        </view>
        <view class="setting-right">
          <text class="setting-status"
            :class="{ 'status-set': identityInfo.userName && identityInfo.idCard && identityInfo.idcard_1_img && identityInfo.idcard_2_img && identityInfo.idcard_effect_begin && identityInfo.idcard_effect_end && (identityInfo.idcard_province && identityInfo.idcard_city && identityInfo.idcard_district && identityInfo.idcard_address) }">
            {{ identityInfo.userName && identityInfo.idCard && identityInfo.idcard_1_img && identityInfo.idcard_2_img &&
              identityInfo.idcard_effect_begin && identityInfo.idcard_effect_end && (identityInfo.idcard_province && identityInfo.idcard_city && identityInfo.idcard_district && identityInfo.idcard_address) ? '已设置' :
            '未设置' }}
          </text>
          <!-- <text class="arrow">></text> -->
          <RectRight color="#999" size="10" />
        </view>
      </view>
    </view>

    <!-- 收款账号弹窗 -->
    <nut-popup v-model:visible="showAccountModal" position="bottom" :style="{ width: '100%', height: '85%' }"
      :close-on-click-overlay="false" closeable close-icon-position="top-right" @close="closeAccountModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">收款账号设置</text>
        </view>

        <view class="form-content">
          <view class="form-item">
            <text class="form-label"><text class="required-mark">*</text>银行名称</text>
            <view class="bank-selector" @click="showBankPicker">
              <text class="bank-text" :class="{ 'bank-selected': tempAccountInfo.bankName }">
                {{ getBankNameById(tempAccountInfo.bankName) || '请选择银行' }}
              </text>
              <!-- <text class="arrow-down">></text> -->
              <RectRight color="#999" size="10" />
            </view>
          </view>

          <view class="form-item">
            <text class="form-label"><text class="required-mark">*</text>银行账号</text>
            <input v-model="tempAccountInfo.bankAccount" placeholder="请输入银行账号"
              class="form-input custom-input native-input" :cursor-spacing="50" @blur="validateBankAccount" />
            <text v-if="bankAccountError" class="error-text">{{ bankAccountError }}</text>
          </view>

          <!-- 银行卡正面照片上传 -->
          <view class="form-item">
            <text class="form-label"><text class="required-mark">*</text>银行卡正面照</text>
            <view class="bank-img-container">
              <view v-if="tempAccountInfo.bankImg" class="bank-img-preview">
                <image :src="tempAccountInfo.bankImg" class="bank-img-image" mode="aspectFill" @tap="previewBankImg" />
                <view class="bank-img-actions">
                  <text class="change-img-btn" @tap="changeBankImg">重新上传</text>
                  <text class="delete-img-btn" @tap="deleteBankImg">删除</text>
                </view>
              </view>
              <view v-else class="bank-img-upload" @tap="changeBankImg">
                <text class="upload-icon">+</text>
                <text class="upload-text">上传银行卡正面照</text>
              </view>
            </view>
          </view>
        </view>

        <view class="modal-footer">
          <nut-button type="default" @click="closeAccountModal" class="footer-btn footer-btn-cancel">
            关闭
          </nut-button>
          <nut-button type="primary" @click="saveAccountInfo" color="#ffa500"
            :disabled="!tempAccountInfo.bankName || !tempAccountInfo.bankAccount || !tempAccountInfo.bankImg"
            class="footer-btn footer-btn-save">
            保存
          </nut-button>
        </view>
      </view>
    </nut-popup>

    <!-- 银行选择器弹窗 -->
    <nut-popup v-model:visible="showBankModal" position="bottom">
      <nut-picker v-model="bankPickerValue" :columns="bankOptions" title="选择银行" @confirm="onBankConfirm"
        @cancel="showBankModal = false"></nut-picker>
    </nut-popup>

    <!-- 身份信息弹窗 -->
    <nut-popup v-model:visible="showIdentityModal" position="bottom" :style="{ width: '100%', height: '100%' }"
      :close-on-click-overlay="false" closeable close-icon-position="top-right" @close="closeIdentityModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">身份信息设置</text>
        </view>

        <view class="form-content">
          <view class="form-item">
            <text class="form-label"><text class="required-mark">*</text>用户名称</text>
            <input v-model="tempIdentityInfo.userName" placeholder="请输入真实姓名" class="form-input native-input" />
          </view>

          <view class="form-item">
            <text class="form-label"><text class="required-mark">*</text>身份证号码</text>
            <input v-model="tempIdentityInfo.idCard" placeholder="请输入身份证号码" class="form-input native-input"
              maxlength="18" @blur="handleIdCardBlur" :cursor-spacing="50" />
            <text v-if="idCardError" class="error-text">{{ idCardError }}</text>
          </view>

          <!-- 身份证人像面照片上传 -->
          <view class="form-item">
            <text class="form-label"><text class="required-mark">*</text>身份证人像面</text>
            <view class="idcard-img-container">
              <view v-if="tempIdentityInfo.idcard_1_img" class="idcard-img-preview">
                <image :src="tempIdentityInfo.idcard_1_img" class="idcard-img-image" mode="aspectFill"
                  @tap="previewIdcard1Img" />
                <view class="idcard-img-actions">
                  <text class="change-img-btn" @tap="changeIdcard1Img">重新上传</text>
                  <text class="delete-img-btn" @tap="deleteIdcard1Img">删除</text>
                </view>
              </view>
              <view v-else class="idcard-img-upload" @tap="changeIdcard1Img">
                <text class="upload-icon">+</text>
                <text class="upload-text">上传身份证人像面</text>
              </view>
            </view>
          </view>

          <!-- 身份证国徽面照片上传 -->
          <view class="form-item">
            <text class="form-label"><text class="required-mark">*</text>身份证国徽面</text>
            <view class="idcard-img-container">
              <view v-if="tempIdentityInfo.idcard_2_img" class="idcard-img-preview">
                <image :src="tempIdentityInfo.idcard_2_img" class="idcard-img-image" mode="aspectFill"
                  @tap="previewIdcard2Img" />
                <view class="idcard-img-actions">
                  <text class="change-img-btn" @tap="changeIdcard2Img">重新上传</text>
                  <text class="delete-img-btn" @tap="deleteIdcard2Img">删除</text>
                </view>
              </view>
              <view v-else class="idcard-img-upload" @tap="changeIdcard2Img">
                <text class="upload-icon">+</text>
                <text class="upload-text">上传身份证国徽面</text>
              </view>
            </view>
          </view>

          <!-- 证件有效期开始日期 -->
          <view class="form-item">
            <text class="form-label"><text class="required-mark">*</text>证件有效期开始</text>
            <view class="date-selector" @click="showIdcardBeginDatePicker">
              <text class="date-text" :class="{ 'date-selected': tempIdentityInfo.idcard_effect_begin }">
                {{ tempIdentityInfo.idcard_effect_begin || '请选择开始日期' }}
              </text>
              <!-- <text class="arrow-down">></text> -->
              <RectRight color="#999" size="10" />
            </view>
          </view>

          <!-- 证件有效期结束日期 -->
          <view class="form-item">
            <text class="form-label"><text class="required-mark">*</text>证件有效期结束</text>
            <view class="date-selector" @click="showIdcardEndDatePicker">
              <text class="date-text" :class="{ 'date-selected': tempIdentityInfo.idcard_effect_end }">
                {{ tempIdentityInfo.idcard_effect_end || '请选择结束日期' }}
              </text>
              <!-- <text class="arrow-down">></text> -->
              <RectRight color="#999" size="10" />
            </view>
          </view>

          <!-- 身份证地址 -->
          <view class="form-item">
            <text class="form-label"><text class="required-mark">*</text>身份证地址</text>
            <!-- 地址选择器触发器 -->
            <view
              class="address-selector"
              @click="showAddressSelector = true"
            >
              <text class="address-text" :class="{ 'address-selected': addressData.full_address }">
                {{ addressData.full_address || '请选择省市县并填写详细地址' }}
              </text>
              <RectRight color="#999" size="10" />
            </view>
          </view>
        </view>

        <view class="modal-footer">
          <nut-button type="default" @click="closeIdentityModal" class="footer-btn footer-btn-cancel">
            关闭
          </nut-button>
          <nut-button type="primary" @click="saveIdentityInfo" color="#ffa500"
            :disabled="!tempIdentityInfo.userName || !tempIdentityInfo.idCard || !tempIdentityInfo.idcard_1_img || !tempIdentityInfo.idcard_2_img || !tempIdentityInfo.idcard_effect_begin || !tempIdentityInfo.idcard_effect_end || !tempIdentityInfo.idcard_province || !tempIdentityInfo.idcard_city || !tempIdentityInfo.idcard_district || !tempIdentityInfo.idcard_address || !!idCardError"
            class="footer-btn footer-btn-save">
            保存
          </nut-button>
        </view>
      </view>
    </nut-popup>

    <!-- 身份证有效期开始日期选择器 -->
    <nut-popup v-model:visible="showIdcardBeginDate" position="bottom" :style="{ height: '50%' }">
      <nut-date-picker v-model="idcardBeginDate" type="date" title="选择证件有效期开始日期" :max-date="maxYearDate"
        :min-date="minYearDate" @confirm="onIdcardBeginDateConfirm" @cancel="showIdcardBeginDate = false" />
    </nut-popup>

    <!-- 证件有效期结束类型选择器弹窗 -->
    <nut-popup v-model:visible="showEndDateTypeModal" position="bottom">
      <nut-picker v-model="endDateTypePickerValue" :columns="endDateTypeOptions" title="选择证件有效期类型"
        @confirm="onEndDateTypeConfirm" @cancel="showEndDateTypeModal = false"></nut-picker>
    </nut-popup>

    <!-- 身份证有效期结束日期选择器 -->
    <nut-popup v-model:visible="showIdcardEndDate" position="bottom" :style="{ height: '50%' }">
      <nut-date-picker v-model="idcardEndDate" type="date" title="选择证件有效期结束日期" :max-date="maxYearDate"
        :min-date="minYearDate" @confirm="onIdcardEndDateConfirm" @cancel="showIdcardEndDate = false" />
    </nut-popup>

    <!-- 固定返回按钮 - 只有当参数target=sell时才显示 -->
    <view v-if="showBackButton" class="fixed-back-btn" @click="goBack">
      <text class="back-text">返回</text>
    </view>

    <!-- 地址选择器组件 -->
    <AddressSelector
      v-model:visible="showAddressSelector"
      v-model="addressData"
      @change="onAddressChange"
      placeholder="请选择省市县并填写详细地址"
    />

  </view>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import Taro from "@tarojs/taro";
import "./index.less";

import { RectRight } from '@nutui/icons-vue-taro'

// 导入接口
import { updateProfileAPI, getProfileAPI } from '@/api/index'
import { getBanksAPI } from '@/api/other'
import BASE_URL from '@/utils/config'

// 导入用户状态管理
import { useUserStore } from '@/stores/user'

// 导入地址选择组件
import AddressSelector from '@/components/AddressSelector.vue'

// 获取页面参数
const instance = Taro.getCurrentInstance()
const { target } = instance.router?.params || {}

// 用户状态管理
const userStore = useUserStore()

/**
 * 判断是否显示返回按钮
 * 只有当参数target=sell时才显示
 */
const showBackButton = computed(() => {
  return target === 'sell'
})

/**
 * 收款账号信息
 */
const accountInfo = ref({
  bankName: '',
  bankAccount: '',
  bankImg: ''
});

/**
 * 身份信息
 */
const identityInfo = ref({
  userName: '',
  idCard: '',
  idcard_1_img: '',
  idcard_2_img: '',
  idcard_effect_begin: '',
  idcard_effect_end: '',
  idcard_address: ''
});

/**
 * 临时收款账号信息(用于弹窗编辑)
 */
const tempAccountInfo = ref({
  bankName: '',
  bankAccount: '',
  bankImg: ''
});

/**
 * 临时身份信息(用于弹窗编辑)
 */
const tempIdentityInfo = ref({
  userName: '',
  idCard: '',
  idcard_1_img: '',
  idcard_2_img: '',
  idcard_effect_begin: '',
  idcard_effect_end: '',
  // 身份证地址相关字段(显示用中文名称)
  province: '',
  city: '',
  county: '',
  // 身份证地址相关字段(提交用真实字段名)
  idcard_province: '',
  idcard_city: '',
  idcard_district: '',
  idcard_address: ''
});

/**
 * 弹窗显示状态
 */
const showAccountModal = ref(false);
const showIdentityModal = ref(false);
const showBankModal = ref(false);
const showIdcardBeginDate = ref(false);
const showIdcardEndDate = ref(false);
const showEndDateTypeModal = ref(false);
const showAddressSelector = ref(false);

/**
 * 身份证号码错误信息
 */
const idCardError = ref('');

/**
 * 银行账号错误信息
 */
const bankAccountError = ref('');

/**
 * 日期选择器相关状态
 */
const idcardBeginDate = ref(new Date());
const idcardEndDate = ref(new Date());

/**
 * 日期选择器的最大日期(当前年份后80年)
 */
const currentYear = new Date().getFullYear();
const maxYearDate = ref(new Date(currentYear + 80, 11, 31)); // 80年后的12月31日

/**
 * 日期选择器的最小日期(当前年份前80年)
 */
const minYearDate = ref(new Date(currentYear - 80, 0, 1)); // 80年前的1月1日

// 银行选择器当前选中的值
const bankPickerValue = ref([]);

// 证件有效期结束类型选择器当前选中的值
const endDateTypePickerValue = ref([]);

/**
 * 证件有效期结束类型选项
 */
const endDateTypeOptions = ref([
  {
    text: '长期',
    value: 'long_term'
  },
  {
    text: '选择日期',
    value: 'select_date'
  }
]);

/**
 * 银行列表数据(从接口获取)
 */
const bankOptions = ref([]);

/**
 * 获取银行列表
 */
const getBanksList = async () => {
  try {
    const result = await getBanksAPI();
    if (result.code && result.data) {
      // 适配数据格式:将 {id, name} 转换为 {text: name, value: id}
      bankOptions.value = result.data.map(bank => ({
        text: bank.name,
        value: bank.id
      }));
    }
  } catch (error) {
    console.error('获取银行列表失败:', error);
  }
};

/**
 * 获取用户信息
 */
const getUserInfo = async () => {
  try {
    const result = await getProfileAPI();
    if (result.code && result.data) {
      const userInfo = result.data;

      // 设置收款账号信息
      if (userInfo.bank_id && userInfo.bank_no) {
        accountInfo.value = {
          bankName: userInfo.bank_id, // 存储银行ID
          bankAccount: userInfo.bank_no, // 存储银行账号
          bankImg: userInfo.bank_img || '' // 存储银行卡图片
        };
      }

      // 设置身份信息
      if (userInfo.name && userInfo.idcard) {
        identityInfo.value = {
          userName: userInfo.name,
          idCard: userInfo.idcard,
          idcard_1_img: userInfo.idcard_1_img || '',
          idcard_2_img: userInfo.idcard_2_img || '',
          idcard_effect_begin: userInfo.idcard_effect_begin || '',
          idcard_effect_end: userInfo.idcard_effect_end || '',
          // 地址字段(用于显示的中文名称)
          province: userInfo.province_name || '',
          city: userInfo.city_name || '',
          county: userInfo.county_name || userInfo.district_name || '',
          // 身份证地址字段(真实字段名)
          idcard_province: userInfo.idcard_province || '',
          idcard_city: userInfo.idcard_city || '',
          idcard_district: userInfo.idcard_district || '',
          idcard_address: userInfo.idcard_address || ''
        };

        // 同时更新地址选择器的数据,包含code值用于还原选中状态
        if (userInfo.idcard_province && userInfo.idcard_city && userInfo.idcard_district) {
          addressData.value = {
            province: userInfo.province_name || '',
            city: userInfo.city_name || '',
            county: userInfo.county_name || userInfo.district_name || '',
            province_code: userInfo.idcard_province,
            city_code: userInfo.idcard_city,
            county_code: userInfo.idcard_district,
            detail_address: userInfo.idcard_address || '',
            idcard_address: userInfo.idcard_address || '',
            full_address: `${userInfo.province_name || ''}${userInfo.city_name || ''}${userInfo.county_name || userInfo.district_name || ''} ${userInfo.idcard_address || ''}`.trim()
          };
        }
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

/**
 * 页面加载时获取数据
 */
onMounted(() => {
  getBanksList();
  getUserInfo();
});

/**
 * 身份证号码校验
 * @param {string} idCard - 身份证号码
 * @returns {boolean} - 是否有效
 */
const validateIdCard = (idCard) => {
  if (!idCard) {
    return { valid: false, error: '请输入身份证号码' };
  }

  // 身份证号码正则表达式
  const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;

  if (!idCardRegex.test(idCard)) {
    return { valid: false, error: '身份证号码格式不正确' };
  }

  // 校验码验证
  const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

  let sum = 0;
  for (let i = 0; i < 17; i++) {
    sum += parseInt(idCard[i]) * weights[i];
  }

  const checkCode = checkCodes[sum % 11];
  const lastChar = idCard[17].toUpperCase();

  if (checkCode !== lastChar) {
    return { valid: false, error: '身份证号码校验失败' };
  }

  return { valid: true, error: '' };
};

/**
 * 处理身份证号码失焦事件
 */
const handleIdCardBlur = () => {
  const idCard = tempIdentityInfo.value.idCard;
  if (idCard) {
    const result = validateIdCard(idCard);
    idCardError.value = result.error;
  } else {
    idCardError.value = '';
  }
};

/**
 * 银行账号校验
 * @param {string} bankAccount - 银行账号
 * @returns {object} - 校验结果
 */
const validateBankAccountNumber = (bankAccount) => {
  if (!bankAccount) {
    return { valid: false, error: '请输入银行账号' };
  }

  // 检查是否都是数字
  const numberRegex = /^\d+$/;
  if (!numberRegex.test(bankAccount)) {
    return { valid: false, error: '银行账号只能包含数字' };
  }

  return { valid: true, error: '' };
};

/**
  * 处理银行账号失焦事件
  */
const validateBankAccount = () => {
  const bankAccount = tempAccountInfo.value.bankAccount;
  if (bankAccount) {
    const result = validateBankAccountNumber(String(bankAccount));
    bankAccountError.value = result.error;
  } else {
    bankAccountError.value = '';
  }
};

/**
 * 根据银行ID获取银行名称
 * @param {string} bankId - 银行ID
 * @returns {string} - 银行名称
 */
const getBankNameById = (bankId) => {
  if (!bankId || !bankOptions.value.length) return '';
  const bank = bankOptions.value.find(item => item.value === bankId);
  return bank ? bank.text : bankId;
};

/**
 * 显示银行选择弹窗
 */
const showBankPicker = () => {
  // 设置当前选中的值
  if (tempAccountInfo.value.bankName) {
    bankPickerValue.value = [tempAccountInfo.value.bankName];
  } else if (bankOptions.value.length > 0) {
    bankPickerValue.value = [bankOptions.value[0].value];
  }
  showBankModal.value = true;
};



/**
 * 银行选择确认回调
 */
const onBankConfirm = ({ selectedValue }) => {
  tempAccountInfo.value.bankName = selectedValue[0];
  showBankModal.value = false;
};

/**
 * 打开收款账号弹窗
 */
const openAccountModal = () => {
  tempAccountInfo.value = { ...accountInfo.value };
  bankAccountError.value = '';
  showAccountModal.value = true;
};

/**
 * 关闭收款账号弹窗
 */
const closeAccountModal = () => {
  showAccountModal.value = false;
  tempAccountInfo.value = { bankName: '', bankAccount: '', bankImg: '' };
  bankAccountError.value = '';
};

/**
 * 保存收款账号信息
 */
const saveAccountInfo = async () => {
  if (!tempAccountInfo.value.bankName || !tempAccountInfo.value.bankAccount) {
    Taro.showToast({
      title: '请填写完整信息',
      icon: 'none'
    });
    return;
  }

  try {
    // 调用API保存收款账号信息
    const result = await updateProfileAPI({
      bank_id: tempAccountInfo.value.bankName, // 发送银行ID
      bank_no: String(tempAccountInfo.value.bankAccount), // 转换为字符串传给接口
      bank_img: tempAccountInfo.value.bankImg // 发送银行卡图片
    });

    if (result.code) {
      accountInfo.value = { ...tempAccountInfo.value };

      // 更新全局用户状态
      userStore.updateUserInfo({
        bank_id: tempAccountInfo.value.bankName, // 存储银行ID
        bank_no: tempAccountInfo.value.bankAccount, // 保持数字类型存储到全局状态
        bank_img: tempAccountInfo.value.bankImg // 存储银行卡图片
      });

      closeAccountModal();

      Taro.showToast({
        title: '保存成功',
        icon: 'success'
      });
    }
  } catch (error) {
    console.error('保存收款账号失败:', error);
    Taro.showToast({
      title: '保存失败,请重试',
      icon: 'none'
    });
  }
};

/**
 * 打开身份信息弹窗
 */
const openIdentityModal = () => {
  tempIdentityInfo.value = { ...identityInfo.value };
  idCardError.value = '';
  // 初始化地址选择器数据
  initAddressData();
  showIdentityModal.value = true;
};

/**
 * 初始化地址选择器数据
 */
const initAddressData = () => {
  addressData.value = {
    province: tempIdentityInfo.value.province || '',
    city: tempIdentityInfo.value.city || '',
    county: tempIdentityInfo.value.county || '',
    province_code: tempIdentityInfo.value.idcard_province || '',
    city_code: tempIdentityInfo.value.idcard_city || '',
    county_code: tempIdentityInfo.value.idcard_district || '',
    detail_address: tempIdentityInfo.value.idcard_address || '',
    full_address: (tempIdentityInfo.value.province + tempIdentityInfo.value.city + tempIdentityInfo.value.county + tempIdentityInfo.value.idcard_address) || ''
  }
};

/**
 * 关闭身份信息弹窗
 */
const closeIdentityModal = () => {
  showIdentityModal.value = false;
  tempIdentityInfo.value = {
    userName: '',
    idCard: '',
    idcard_1_img: '',
    idcard_2_img: '',
    idcard_effect_begin: '',
    idcard_effect_end: '',
    province: '',
    city: '',
    county: '',
    idcard_province: '',
    idcard_city: '',
    idcard_district: '',
    idcard_address: ''
  };
  idCardError.value = '';
};

/**
 * 上传银行卡正面照
 */
const changeBankImg = () => {
  Taro.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: function (res) {
      const tempFilePath = res.tempFilePaths[0]
      uploadBankImage(tempFilePath)
    },
    fail: function () {
      Taro.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

/**
 * 上传银行卡图片到服务器
 * @param {String} filePath - 图片文件路径
 */
const uploadBankImage = (filePath) => {
  // 显示上传中提示
  Taro.showLoading({
    title: '上传中',
    mask: true
  })

  // 上传图片
  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) {
            tempAccountInfo.value.bankImg = upload_data.data.src;
            Taro.showToast({
              title: '上传成功',
              icon: 'success'
            })
          } else {
            Taro.showToast({
              icon: 'error',
              title: '服务器错误,稍后重试!',
              mask: true
            })
          }
        },
      });
    },
    fail: function (res) {
      Taro.hideLoading({
        success: () => {
          Taro.showToast({
            icon: 'error',
            title: '上传失败,稍后重试!',
            mask: true
          })
        },
      });
    }
  })
}

/**
 * 预览银行卡图片
 */
const previewBankImg = () => {
  if (tempAccountInfo.value.bankImg) {
    Taro.previewImage({
      urls: [tempAccountInfo.value.bankImg],
      current: tempAccountInfo.value.bankImg
    })
  }
}

/**
 * 删除银行卡图片
 */
const deleteBankImg = () => {
  Taro.showModal({
    title: '确认删除',
    content: '确定要删除银行卡照片吗?',
    success: function (res) {
      if (res.confirm) {
        tempAccountInfo.value.bankImg = ''
        Taro.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

/**
 * 选择身份证人像面照片
 */
const changeIdcard1Img = () => {
  Taro.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: function (res) {
      const tempFilePath = res.tempFilePaths[0]
      uploadIdcardImage(tempFilePath, 'idcard_1_img')
    },
    fail: function () {
      Taro.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

/**
 * 选择身份证国徽面照片
 */
const changeIdcard2Img = () => {
  Taro.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: function (res) {
      const tempFilePath = res.tempFilePaths[0]
      uploadIdcardImage(tempFilePath, 'idcard_2_img')
    },
    fail: function () {
      Taro.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

/**
 * 上传身份证图片到服务器
 * @param {String} filePath - 图片文件路径
 * @param {String} fieldName - 字段名称 (idcard_1_img 或 idcard_2_img)
 */
const uploadIdcardImage = (filePath, fieldName) => {
  // 显示上传中提示
  Taro.showLoading({
    title: '上传中',
    mask: true
  })

  // 上传图片
  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) {
            tempIdentityInfo.value[fieldName] = upload_data.data.src;
            Taro.showToast({
              title: '上传成功',
              icon: 'success'
            })
          } else {
            Taro.showToast({
              icon: 'error',
              title: '服务器错误,稍后重试!',
              mask: true
            })
          }
        },
      });
    },
    fail: function (res) {
      Taro.hideLoading({
        success: () => {
          Taro.showToast({
            icon: 'error',
            title: '上传失败,稍后重试!',
            mask: true
          })
        },
      });
    }
  })
}

/**
 * 预览身份证人像面图片
 */
const previewIdcard1Img = () => {
  if (tempIdentityInfo.value.idcard_1_img) {
    Taro.previewImage({
      urls: [tempIdentityInfo.value.idcard_1_img],
      current: tempIdentityInfo.value.idcard_1_img
    })
  }
}

/**
 * 预览身份证国徽面图片
 */
const previewIdcard2Img = () => {
  if (tempIdentityInfo.value.idcard_2_img) {
    Taro.previewImage({
      urls: [tempIdentityInfo.value.idcard_2_img],
      current: tempIdentityInfo.value.idcard_2_img
    })
  }
}

/**
 * 删除身份证人像面图片
 */
const deleteIdcard1Img = () => {
  Taro.showModal({
    title: '确认删除',
    content: '确定要删除身份证人像面照片吗?',
    success: function (res) {
      if (res.confirm) {
        tempIdentityInfo.value.idcard_1_img = ''
        Taro.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

/**
 * 删除身份证国徽面图片
 */
const deleteIdcard2Img = () => {
  Taro.showModal({
    title: '确认删除',
    content: '确定要删除身份证国徽面照片吗?',
    success: function (res) {
      if (res.confirm) {
        tempIdentityInfo.value.idcard_2_img = ''
        Taro.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

/**
 * 显示身份证有效期开始日期选择器
 */
const showIdcardBeginDatePicker = () => {
  showIdcardBeginDate.value = true
}

/**
 * 显示身份证有效期结束日期选择器
 */
const showIdcardEndDatePicker = () => {
  // 设置默认选中第一个选项
  if (endDateTypeOptions.value.length > 0) {
    endDateTypePickerValue.value = [endDateTypeOptions.value[0].value];
  }
  showEndDateTypeModal.value = true
}

/**
 * 确认选择身份证有效期开始日期
 * @param {Object} param - 日期选择器返回的参数
 */
const onIdcardBeginDateConfirm = (param) => {
  const { selectedValue } = param
  const year = selectedValue[0]
  const month = selectedValue[1].toString().padStart(2, '0')
  const day = selectedValue[2].toString().padStart(2, '0')
  tempIdentityInfo.value.idcard_effect_begin = `${year}-${month}-${day}`
  showIdcardBeginDate.value = false
}

/**
 * 证件有效期结束类型选择确认回调
 * @param {Object} param - 选择器返回的参数
 */
const onEndDateTypeConfirm = ({ selectedValue }) => {
  const selectedType = selectedValue[0];

  if (selectedType === 'long_term') {
    // 选择长期,直接设置为"长期"
    tempIdentityInfo.value.idcard_effect_end = '长期';
    showEndDateTypeModal.value = false;
  } else if (selectedType === 'select_date') {
    // 选择日期,打开日期选择器
    showEndDateTypeModal.value = false;
    showIdcardEndDate.value = true;
  }
};

/**
 * 确认选择身份证有效期结束日期
 * @param {Object} param - 日期选择器返回的参数
 */
const onIdcardEndDateConfirm = (param) => {
  const { selectedValue } = param
  const year = selectedValue[0]
  const month = selectedValue[1].toString().padStart(2, '0')
  const day = selectedValue[2].toString().padStart(2, '0')
  tempIdentityInfo.value.idcard_effect_end = `${year}-${month}-${day}`
  showIdcardEndDate.value = false
}

/**
 * 保存身份信息
 */
const saveIdentityInfo = async () => {
  if (!tempIdentityInfo.value.userName || !tempIdentityInfo.value.idCard) {
    Taro.showToast({
      title: '请填写完整信息',
      icon: 'none'
    });
    return;
  }

  const validation = validateIdCard(tempIdentityInfo.value.idCard);
  if (!validation.valid) {
    Taro.showToast({
      title: validation.error,
      icon: 'none'
    });
    return;
  }

  try {
    // 调用API保存身份信息
    const result = await updateProfileAPI({
      name: tempIdentityInfo.value.userName,
      idcard: tempIdentityInfo.value.idCard,
      idcard_1_img: tempIdentityInfo.value.idcard_1_img,
      idcard_2_img: tempIdentityInfo.value.idcard_2_img,
      idcard_effect_begin: tempIdentityInfo.value.idcard_effect_begin,
      idcard_effect_end: tempIdentityInfo.value.idcard_effect_end,
      // 使用真实的身份证地址字段名
      idcard_province: tempIdentityInfo.value.idcard_province,
      idcard_city: tempIdentityInfo.value.idcard_city,
      idcard_district: tempIdentityInfo.value.idcard_district,
      idcard_address: tempIdentityInfo.value.idcard_address
    });

    if (result.code) {
      identityInfo.value = { ...tempIdentityInfo.value };

      // 更新全局用户状态
      userStore.updateUserInfo({
        name: tempIdentityInfo.value.userName,
        idcard: tempIdentityInfo.value.idCard,
        idcard_1_img: tempIdentityInfo.value.idcard_1_img,
        idcard_2_img: tempIdentityInfo.value.idcard_2_img,
        idcard_effect_begin: tempIdentityInfo.value.idcard_effect_begin,
        idcard_effect_end: tempIdentityInfo.value.idcard_effect_end,
        // 身份证地址字段
        idcard_province: tempIdentityInfo.value.idcard_province,
        idcard_city: tempIdentityInfo.value.idcard_city,
        idcard_district: tempIdentityInfo.value.idcard_district,
        idcard_address: tempIdentityInfo.value.idcard_address
      });

      closeIdentityModal();

      Taro.showToast({
        title: '保存成功',
        icon: 'success'
      });
    } else {
      Taro.showToast({
        title: result.message || '保存失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('保存身份信息失败:', error);
    Taro.showToast({
      title: '保存失败,请重试',
      icon: 'none'
    });
  }
};

/**
 * 返回上一页
 */
const goBack = () => {
  Taro.redirectTo({
    url: '/pages/sell/index'
  });
};

// 地址选择相关状态
const addressData = ref({
  province: '',
  city: '',
  county: '',
  province_code: '',
  city_code: '',
  county_code: '',
  detail_address: '',
  idcard_address: '',
  full_address: ''
})

/**
 * 地址变化处理回调
 * @param {Object} address - 地址数据对象
 */
const onAddressChange = (address) => {
  // 更新临时身份信息中的地址字段(中文名称,用于显示)
  tempIdentityInfo.value.province = address.province
  tempIdentityInfo.value.city = address.city
  tempIdentityInfo.value.county = address.county

  // 更新身份证地址字段(真实字段名,用于提交)
  tempIdentityInfo.value.idcard_province = address.province_code || address.province
  tempIdentityInfo.value.idcard_city = address.city_code || address.city
  tempIdentityInfo.value.idcard_district = address.county_code || address.county
  tempIdentityInfo.value.idcard_address = address.detail_address
}
</script>

<script>
export default {
  name: "collectionSettings",
};
</script>