index.vue 53.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
<!--
 * @Date: 2022-07-18 10:22:22
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-11-26 19:52:55
 * @FilePath: /data-table/src/views/index.vue
 * @Description: 首页
-->
<template>
  <van-notice-bar v-if="formSetting.sjsj_is_count_down" left-icon="volume-o" :text="notice_text" scrollable
    mode="closeable" />
  <div v-if="!show_loading" class="table-box">
    <template v-if="PHeader.visible && (page_type === 'add' || model === 'preview')">
      <van-image v-if="PHeader.type === 'image' && PHeader.cover" width="100%" :src="PHeader.cover + '?imageView2/0/w/2000'" fit="cover" />
      <template v-if="PHeader.type === 'carousel'">
        <van-swipe class="my-swipe" lazy-render indicator-color="white">
          <van-swipe-item v-for="image in PHeader.cover" :key="index"><img :src="image"
              style="height: 12rem; width: 100%; object-fit: cover" /></van-swipe-item>
        </van-swipe>
      </template>
      <div v-if="PHeader.type === 'text'" class="PHeader-Text" v-html="PHeader.banner" />
    </template>
    <div v-if="PHeader.label" class="table-title" v-html="PHeader.label" />
    <!-- TAG:总分支持0分显示,避免因真假值判断被隐藏 -->
    <div
      v-if="PHeader.x_total_score !== undefined && PHeader.x_total_score !== null && PHeader.x_total_score !== ''"
      style="font-weight: bold; color: red; text-align: center; font-size: 0.9rem;"
    >总分: {{ PHeader.x_total_score }}</div>
    <div v-if="PHeader.flow_node_name" style="text-align: center;">({{ PHeader.flow_node_name }})</div>
    <div v-if="PHeader.description" class="table-desc" v-html="PHeader.description" />
    <van-config-provider :theme-vars="themeVars">
      <van-form ref="myForm" @submit="onSubmit" @failed="onFailed" :scroll-to-error="true">
        <van-cell-group :border="false">
          <component v-for="(item, index) in visible_form_data" :id="item.key" :ref="(el) => setRefMap(el, item)" :key="item.key"
            :is="item.component" :item="item" @active="onActive" @remove="onRemove" @blur="onBlur" />
        </van-cell-group>
        <pagination-field
          v-if="enable_pagination"
          :current="current_page_index"
          :total="filtered_pages.length"
          :is-last="current_page_index === filtered_pages.length - 1"
          :prev-label="page_nav.prev_text"
          :next-label="page_nav.next_text"
          :prev-btn-color="page_nav.prev_btn_color"
          :next-btn-color="page_nav.next_btn_color"
          :prev-text-color="page_nav.prev_text_color"
          :next-text-color="page_nav.next_text_color"
          :submit-button="PCommit"
          :prev-disabled="page_nav.prev_disabled"
          @prev="handlePrev"
          @next="handleNext"
          @submit="handleSubmit"
        />
        <!-- 非流程版表单 -->
        <div v-if="formData.length && PCommit.visible && !formSetting.is_flow && !enable_pagination" style="margin: 16px">
          <van-button round block type="primary" :color="PCommit.btn_color" native-type="submit" :disabled="submitStatus">
            <span :style="{ color: PCommit.text_color }">{{ PCommit.text ? PCommit.text : '提交' }}</span>
          </van-button>
        </div>
        <!-- 流程表单 -->
        <div v-if="formSetting.is_flow" style="margin: 16px; padding-top: 1rem;">
          <div v-if="formSetting.is_flow_content">
            <p style="margin-bottom: 1rem; font-size: 0.85rem; font-weight: bold;">审批意见</p>
            <div style="margin-bottom: 1rem; border: 1px solid #eee;">
              <van-field
                v-model="approval_note"
                rows="3"
                autosize
                label=""
                type="textarea"
                placeholder=""
              />
            </div>
          </div>
          <van-button round block type="primary" @click="approval_show=true" style="margin-bottom: 1rem;">
            流程操作
          </van-button>
        </div>
        <!-- 显示审批意见 -->
        <div v-if="page_type === 'info' && form_flow_process_list.length" style="margin: 16px;">
          <div>
            <p style="margin-bottom: 1rem; font-size: 0.85rem; font-weight: bold;">审批结果</p>
            <div style="margin-bottom: 1rem; border-left: 1px solid #eee; border-right: 1px solid #eee;">
              <van-collapse ref="collapseRef" v-model="active_flow_process">
                <van-collapse-item v-for="(item, index) in form_flow_process_list" :value="item.node_action_id === 'commit' ? '提交' : '驳回'" :name="item.created_time">
                  <template #title>
                    <div style="display: flex; align-items: center;">
                      <van-icon
                        :name="item.node_action_id === 'commit' ? 'passed' : 'close'"
                        :color="item.node_action_id === 'commit' ? '#05ae33' : 'red'" size="1rem"
                      />&nbsp;
                      <span v-if="item.node_action_id === 'commit'" class="van-ellipsis" style="color: #05ae33; width: 45vw; display: inline-block; line-height: 1rem;">
                        {{ item.node_name }}
                      </span>
                      <span v-else class="van-ellipsis" style="color: red; width: 45vw; display: inline-block; line-height: 1rem;">
                        {{ item.node_name }}
                      </span>
                    </div>
                  </template>
                  <div>
                    <!-- <van-row gutter="" align="center" style="margin-bottom: 0.25rem;">
                      <van-col span="8">审批操作</van-col>
                      <van-col span="16" style="text-align: right;">commit=提交,reject=驳回</van-col>
                    </van-row> -->
                    <van-row v-if="item.note" gutter="" align="center" style="margin-bottom: 0.25rem;">
                      <van-col span="8">审批意见</van-col>
                      <van-col span="16" style="text-align: right;">{{ item.note }}</van-col>
                    </van-row>
                    <van-row gutter="" align="center" style="margin-bottom: 0.25rem;">
                      <van-col span="8">节点名称</van-col>
                      <van-col span="16" style="text-align: right;">{{ item.node_name }}</van-col>
                    </van-row>
                    <van-row gutter="" align="center" style="margin-bottom: 0.25rem;">
                      <van-col span="8">审批人名称</van-col>
                      <van-col span="16" style="text-align: right;">{{ item.created_by_name }}</van-col>
                    </van-row>
                    <van-row gutter="" align="center" style="margin-bottom: 0.25rem;">
                      <van-col span="8">审批时间</van-col>
                      <van-col span="16" style="text-align: right;">{{ formatDate(item.created_time) }}</van-col>
                    </van-row>
                  </div>
                </van-collapse-item>
              </van-collapse>
            </div>
          </div>
        </div>
        <!-- <van-cell-group :border="false">
          <component
            v-for="(item, index) in mockData"
            :id="item.key"
            :ref="(el) => setRefMap(el, item)"
            :key="index"
            :is="item.component"
            :item="item"
            @active="onActive"
                />
        </van-cell-group>
        <div v-if="mockData.length && PCommit.visible" style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            {{ PCommit.text ? PCommit.text : '提交' }}
          </van-button>
        </div> -->
      </van-form>
      <!-- <van-floating-bubble
        axis="xy"
        icon="records-o"
        magnetic="x"
        @click="onClickFloatingBubble"
      /> -->
    </van-config-provider>
  </div>
  <div v-if="page_type === 'add'" style="text-align: center; color: #545454; font-size: 0.85rem; padding-bottom: 2rem">
    提交即授权该表单收集你的填写信息
  </div>
  <div>
    <!-- TODO: 签到二维码,待用 -->
    <!-- <van-image width="50" height="50" src="https://oa-dev.onwall.cn/admin/?a=get_qrcode&m=srv&key=123'"></van-image> -->
  </div>
  <van-overlay :show="show_qrcode">
    <div class="wrapper">
      <div class="block">
        <div style="text-align: center; margin-top: 0.5rem;">请先关注公众号</div>
        <van-image @touchstart="onTap" width="100%" fit="cover" :src="qr_url" />
        <div style="text-align: center; margin-bottom: 0.5rem; font-size: 0.85rem;">长按识别二维码</div>
      </div>
    </div>
  </van-overlay>
  <van-overlay :show="pwd_show">
    <div class="pwd-wrapper">
      <div class="block">
        <div style="text-align: center; margin-top: 0.5rem;">请输入密码填写表单</div>
        <van-config-provider :theme-vars="themeVars">
          <van-form>
            <van-field v-model="mmtx_password" type="password" autocomplete label="密码"
              style="border: 1px solid #dfdfdf; margin: 1rem 0; border-radius: 5px;" />
            <van-button @click="onSubmitPwd" type="primary" round block>验证并填写表单</van-button>
          </van-form>
        </van-config-provider>
      </div>
    </div>
  </van-overlay>
  <van-action-sheet
    v-model:show="approval_show"
    :actions="approval_actions"
    @select="onApprovalSelect"
    cancel-text="取消"
    close-on-click-action
    @cancel="onApprovalCancel"
  />

  <van-overlay :show="bind_tel_show" z-index="100">
    <div class="bind-tel-wrapper">
      <div class="block">
        <div style="text-align: center; padding: 1rem; padding-top: 0; font-weight: bold;">手机号绑定</div>
        <login-box ref="bindForm" @on-submit="onBindSubmit"></login-box>
        <div style="padding: 1rem; padding-bottom: 0;">
          <van-button round block type="primary" :color="styleColor.baseColor" @click="bindSubmit">
            绑&nbsp;定
          </van-button>
        </div>
      </div>
    </div>
  </van-overlay>

  <van-dialog v-model:show="show_reject" title="选择驳回节点" show-cancel-button :confirm-button-color="themeVars.buttonPrimaryBackground" @confirm="onConfirmDialog" @cancel="onCancelDialog">
    <div style="padding: 1rem 0;">
      <van-checkbox-group v-model="checked_reject" shape="square" :checked-color="themeVars.buttonPrimaryBackground">
        <van-checkbox v-for="(node, index) in reject_nodes" :key="index" :name="node.code" style="margin: 0 0 8px 20px;">{{ node.name }}</van-checkbox>
      </van-checkbox-group>
    </div>
  </van-dialog>

  <van-loading v-if="show_loading" size="24px" vertical style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 5rem;">加载中...</van-loading>
</template>

<script setup>
import "@vant/touch-emulator"; // PC上引入时使得表格组件按钮插件出问题,移动端使用没问题
import { createComponentType } from "@/hooks/useComponentType";
import { Cookies, $, _, axios, storeToRefs, mainStore, Toast, useTitle, } from "@/utils/generatePackage.js";
import { useRoute } from "vue-router";
import { queryFormAPI, postVerifyPasswordAPI, getVolunteerSourceLeaderAPI } from "@/api/form.js";
import { addFormDataAPI, queryFormDataAPI, modiFormDataAPI, flowFormDataAPI } from "@/api/data.js";
import { showSuccessToast, showFailToast, showConfirmDialog, showToast } from "vant";
import { resetDialogState } from "@/utils/dialogControl.js";
import { wxInfo, getUrlParams, formatDate, prettyLog } from "@/utils/tools";
import { styleColor } from "@/constant.js";
import { sharePage } from '@/composables/useShare.js'
import wx from 'weixin-js-sdk'
import LoginBox from '@/components/LoginBox/index.vue';
import PaginationField from '@/components/PaginationField/index.vue';
import { usePagination } from '@/composables/usePagination.js';

const $route = useRoute();
const $router = useRouter();

// 获取表单设置
const store = mainStore();
const { formSetting, formInfo, successInfo } = storeToRefs(store);

// // web端判断封面图片高度
// const is_pc = computed(() => wxInfo().isPC);
// const PHeaderHeight = computed(() => {
//   if (is_pc.value) {
//     return "35vh";
//   } else {
//     return "20vh";
//   }
// });

// TAG: 自定义主题颜色
const themeVars = {
  buttonPrimaryBackground: styleColor.baseColor,
  buttonPrimaryBorderColor: styleColor.baseColor,
  pickerConfirmActionColor: styleColor.baseColor,
};

const PHeader = ref({});
const PCommit = ref({});
// const PHeader_cover = ref("");
// const PHeader_title = ref("");
// const mockData = ref([]);
/**
 * 表单结构数据
 */
const formData = ref([]);

/**
 * 格式化表单数据
*/
const formatData = (data) => {
  const arr = [];
  data.forEach((field) => {
    const { interaction_type, data_type, field_id, field_name, ...component_props } = field;
    // 生成组件属性
    const temp = {
      key: field_name,
      value: component_props.default ? component_props.default : "",
      component_props,
    };
    arr.push(temp);
  });
  return arr;
};
/**
 * 表单提交数据
 */
const postData = ref({});
/**
 * 表单历史数据
 */
const historyData = ref({});

// 编辑模式不能提交操作
const model = $route.query.model;
// 权限控制, 页面参数判断页面功能
/**
 * add 新增页
 * info 详情页
 * edit 编辑页
 * flow 流程页
 */
const page_type = $route.query.page_type ? $route.query.page_type : 'add';
//
const data_id = $route.query.data_id ? $route.query.data_id : null;
// 模仿金数据的扩展参数
const x_field_1 = $route.query.x_field_1 ? $route.query.x_field_1 : null;
// 周期ID标识
const x_cycle = $route.query.x_cycle ? $route.query.x_cycle : null;
// iframe项目标识 - 现在是美乐爱觉使用
const x_project = $route.query.x_project ? $route.query.x_project : null;
// iframe传值openid
const iframe_openid = getUrlParams(location.href) ? getUrlParams(location.href).openid : '';
// 强制后台检查标识
const force_back = $route.query.force_back ? $route.query.force_back : '';
// 义工来源
const volunteer_source = $route.query.volunteer_source ? $route.query.volunteer_source : '';

const notice_text = ref(""); // 顶部提示文字
const show_qrcode = ref(false); // 显示二维码
const qr_url = ref(""); // qrcode
const pwd_show = ref(false);
const mmtx_password = ref('');
const form_name = ref(''); // 表单名称

// 提交表单密码
const onSubmitPwd = async () => {
  const { code } = await postVerifyPasswordAPI({ form_code: $route.query.code, mmtx_password: mmtx_password.value });
  if (code) {
    pwd_show.value = false;
  }
}

// 弹出流程审核操作
const approval_show = ref(false);
const approval_note = ref('');
const flow_node_action_id = ref('');
// 审批组件点击
const onClickFloatingBubble = () => {
  approval_show.value = true;
}
const myForm = ref(null);
const approval_actions = ref([]);
const show_reject = ref(false);
const checked_reject = ref([]);
const reject_nodes = ref([]);
const onApprovalSelect = (item) => {
  flow_node_action_id.value = item.id;
  if (page_type === 'add') { // 新增页面统一处理为提交
    myForm.value.submit();
  }
  if (page_type === 'flow') {
    // 驳回选择分支操作
    if (item.id === 'reject' && item?.parent_nodes?.length) { // 点击驳回按钮
      show_reject.value = true;
      reject_nodes.value = item.parent_nodes; // 驳回操作对应的上级节点
      return;
    }
    myForm.value.submit();
  }
};

const onApprovalCancel = () => {
  console.warn('取消');
}

// const handleApproval = (type) => {
//   console.warn(type);
//   console.warn(approval_note.value);
// }

const onConfirmDialog = () => { // 提交驳回节点操作
  // 提交驳回节点操作,需要驳回的节点需要传递到后台数据中
  myForm.value.submit();
}
const onCancelDialog = () => { // 取消驳回节点操作
  checked_reject.value = [];
}

// TODO: 等待调试发送短信接口
const bind_tel_show = ref(false);
const bindForm = ref(null);
const bindSubmit = () => {
  bindForm.value.submit();
}

const onBindSubmit = (values) => {
  axios.post('/srv/?a=b_login', {
    phone: values.phone,
    pin: values.code,
  })
    .then(res => {
      if (res.data.code === 1) {
        bind_tel_show.value = false;
        // 表单成功提交后续操作
        successHandle();
      } else {
        console.warn(res.data);
        Toast({
          message: res.data.msg,
          icon: 'close',
        });
      }
    })
    .catch(err => {
      console.error(err);
    })
};

const flow_node_code = $route.query.flow_node_code ? $route.query.flow_node_code :formSetting.value.flow_node_code; // flow_node_code 表示随机选择的流程节点的ID
const form_flow_process_list = ref([]);
const active_flow_process = ref([]);
const collapseRef = ref(null);

const show_loading = ref(false);

// 定时器ID,用于清理轮询
let subscribeCheckInterval = null;

onMounted(async () => {
  // 显示加载动画
  show_loading.value = true;
  // TAG: 全局背景色
  document
    .querySelector("body")
    .setAttribute("style", `background-color: ${styleColor.backgroundColor}`);
  // const { data, flow_process_list, code } = await queryFormAPI({ form_code: $route.query.code, page_type, data_id, flow_node_code, force_back, openid: iframe_openid, x_cycle, volunteer_source }); // flow_node_code 表示随机选择的流程节点的ID
  const { data, flow_process_list, code } = await queryFormAPI({ form_code: $route.query.code, ...$route.query }); // flow_node_code 表示随机选择的流程节点的ID
  const form_data = data;
  // 处理审批意见显示
  if (code) {
    setTimeout(() => {
      form_flow_process_list.value = flow_process_list; // 上中下游节点的审批意见
      if (flow_process_list?.length) {
        active_flow_process.value.push(flow_process_list[0]['created_time']);
        // nextTick(() => {
        //   // 全部展开
        //   collapseRef.value?.toggleAll(true);
        // })
      }
    }, 1000);
  }
  // 缓存表单信息
  store.changeFormInfo(data);
  // 表单网页标题
  useTitle(form_data.name);
  form_name.value = form_data.name;
  // 重构数据结构
  let page_header = {};
  let page_commit = {};
  let page_form = [];
  form_data.field_list.forEach((element) => {
    if (element.tag === "page_header") {
      // 页眉组件
      page_header = element;
    } else if (element.tag === "page_commit") {
      // 提交按钮
      page_commit = element;
    } else {
      page_form.push(element);
    }
  });
  /** 页眉属性
   * @param label 表单标题
   * @param banner_type 页眉类型:["文字", "单张图", "轮播图"] text=文字,image=单张图,carousel=轮播图
   * @param banner_url 页眉图片地址
   * @param description 描述内容
   * @param invisible 页眉展示
   */
  if (page_header) {
    PHeader.value = {
      label: page_header.label,
      description: page_header.description,
      type: page_header.banner_type,
      cover: page_header.banner_url,
      banner: page_header.banner,
      visible: !page_header.invisible,
      flow_node_name: formSetting.value.flow_node_name ? formSetting.value.flow_node_name : '', // 节点名称
    };
  }
  if (page_commit) {
    PCommit.value = {
      text: page_commit.text,
      visible: !page_commit.invisible,
      is_back: page_commit.is_back,
      back_title: page_commit.back_title,
      btn_color: page_commit.background_color,
      text_color: page_commit.color,
    };
  }

  // page_form.push({
  //   "tag": "divider",
  //   "name": "name_2",
  //   "index": 2,
  //   "label": "表格",
  //   "unique": false,
  //   "default": "",
  //   "disabled": false,
  //   "field_id": 799599,
  //   "readonly": false,
  //   "required": false,
  //   "data_type": "text",
  //   "field_name": "field_2",
  //   "placeholder": "请输入",
  //   "interaction_type": "h5edit"
  // })

  formData.value = formatData(page_form);
  // TAG: 构建分页组件
  if (page_type === 'add' || page_type === undefined || model === 'preview') {
    buildPages();
    enable_pagination.value = filtered_pages.value.length > 1;
  }
  /**** END ****/

  // TAG:获取原来表单数据
  if (data_id) { // 如果有data_id,则获取历史数据 否则获取表单默认值
    const history_data = await queryFormDataAPI({ form_code: $route.query.code, data_id, openid: iframe_openid, force_back, page_type });
    if (history_data.code) {
      // 结构优化一下
      let object = history_data.data;
      const isInfoPage = page_type === 'info';
      const objectMap = new Map(Object.entries(object)); // 将 object 转换为 Map,Object.entries() 方法用于返回一个给定对象自身可枚举属性的键值对数组,数组中的每个元素是一个包含键值对的数组,[ ["name", "Alice"], ["age", 30], ["city", "New York"] ]
      formData.value.forEach((item) => {
        if (objectMap.has(item.key)) {
          item.component_props.default = objectMap.get(item.key);
          // 设置读写权限 read_only read_write
          if (isInfoPage) {
            item.component_props.readonly = true;
            PCommit.value.visible = false; // 只读模式下,提交按钮隐藏
          }
          // 处理分页表单结果数据
          if (object.x_score_map) {
            // TAG:分数映射存在时才处理分页成绩(保留0分)
            const score_map = object.x_score_map;
            // 这里使用空值合并运算符,避免0分被当作假值
            item.component_props.x_score = (score_map[item.key] ?? '');
            PHeader.value.x_total_score = (score_map.x_total_score ?? '');
          } else {
            // TAG:分数映射不存在时清空分页成绩,避免残留展示
            item.component_props.x_score = undefined;
            PHeader.value.x_total_score = undefined;
          }
        }
      });
      historyData.value = history_data.data; // 历史表单字段数据
      // 显示加载动画
      show_loading.value = false;
    }
    if (!history_data) {
      PCommit.value.visible = false; // 查询数据错误,提交按钮隐藏
      // 显示加载动画
      show_loading.value = false;
    }
  } else {
    // 显示加载动画
    show_loading.value = false;
  }

  // TAG: 创建组件类型
  createComponentType(formData.value);

  const isJSON = (value) => {
    try {
      JSON.parse(value);
      return true;
    } catch (e) {
      return false;
    }
  }

  // TAG: 不同类型提交表单处理
  if (page_type === 'add' || page_type === undefined) { // 表单为新增状态, 检查是否有未完成的表单信息
    const existingCookie = Cookies.get($route.query.code);
    if (existingCookie) {
      // 如果Cookie存在,更新它
      let object = JSON.parse(existingCookie);
      // 默认值
      const objectMap = new Map(Object.entries(object)); // 将 object 转换为 Map,Object.entries() 方法用于返回一个给定对象自身可枚举属性的键值对数组,数组中的每个元素是一个包含键值对的数组,[ ["name", "Alice"], ["age", 30], ["city", "New York"] ]
      formData.value.forEach((item) => {
        if (objectMap.has(item.key)) {
          // 适配双重json字符串问题,比如地址
          const value = isJSON(objectMap.get((item.key))) ? JSON.parse(objectMap.get((item.key))) : objectMap.get((item.key));
          item.component_props.default = value;
        }
      });
    }
  }
  if (page_type === 'add' && !force_back) { // 表单为新增状态, 非后台打开状态
    // 过期时间显示
    notice_text.value = `表单报名将在 ${formSetting.value.sjsj_end_time} 后结束`;
    // 判断是否需要关注公众号, 弹出二维码识别
    if (formSetting.value.wxzq_must_follow && !formSetting.value.x_field_weixin_subscribe) {
      show_qrcode.value = true;
      qr_url.value = formSetting.value.wxzq_mp_qrcode;
      // 标记用户还未关注
      localStorage.setItem('weixin_subscribe', 0);
    }
    // 判断是否弹出密码输入框
    checkUserPassword();
    // 当数据量达到限额时,该表单将不能继续提交数据。
    if (formSetting.value.sjsj_max_count_error) {
      // 提交按钮禁用
      submitStatus.value = true;
    }
    // 设定填写次数
    if (formSetting.value.wxzq_scope && model !== 'preview') {
      if (formSetting.value.fill_error) {
        // 提交按钮禁用
        submitStatus.value = true;
      }
    }
  }
  // 启用分享功能,非预览模式
  if (formSetting.value.wxzq_is_share && model !== 'preview') {
    wx.ready(() => {
      /**
       * 微信分享卡片标题模式
       * form_name=使用表单名称作为分享标题,customize=自定义分享标题
       */
      const title = formSetting.value.wxzq_share_title_mode === 'form_name' ? form_name.value : formSetting.value.wxzq_share_custom_title;
      // 自定义分享内容
      sharePage({ title, desc: formSetting.value.wxzq_share_slogan, imgUrl: formSetting.value.wxzq_share_logo });
    });
  }

  setTimeout(() => {
    // 审核操作列表数据
    approval_actions.value = formSetting.value.flow_node_action_list?.map((item) => { return { name: item.btnText, id: item.id, parent_nodes: item.parent_nodes } });
  }, 1000);

  // 初始化完成后执行规则检查
  nextTick(() => {
    checkRules();
  });

  setTimeout(() => {
    const width = $('body').width();
    // 固定表单宽度
    $('.table-box').css('width', (width - 30) + 'px');
  }, 100);

  // TAG:表单样式统一修改
  // 详情页表单的border去掉
  if (page_type === 'info') {
    nextTick(() => {
      document.documentElement.style.setProperty('--border-style', '0');
    })
  }
  // iframe通信-读取联系人身份证信息
  window.addEventListener('message', (ev) => {
    let data = ev.data || null;
    if (data.length) {
      const objectMap = new Map(data?.map(item => [item.key, item.value]));
      formData.value.forEach((item) => {
        // 绑定别名字段
        if (objectMap.has(item.component_props.alias)) {
          if (item.component_props.tag === 'checkbox') { // 多选组件值需要转换为数组
            item.component_props.default = objectMap.get(item.component_props.alias).trim().split(' ');
          } else {
            item.component_props.default = objectMap.get(item.component_props.alias);
          }
        }
      });
    }
  }, false);
});

onUnmounted(() => {
  // 清理定时器
  if (subscribeCheckInterval) {
    clearInterval(subscribeCheckInterval);
    subscribeCheckInterval = null;
  }
});

// 自定义失焦操作
// const onBlur = async (item) => {
//   console.warn(item);
//   // const history_data = await queryFormDataAPI({ form_code: $route.query.code, data_id, openid: iframe_openid, force_back, page_type });
//   // if (history_data.code) {
//   //   // 结构优化一下
//   //   let object = history_data.data;
//   // 如果字段有数据了 object里面的字段需要删掉
//   // delete historyData.value[item.key];
//   //   const objectMap = new Map(Object.entries(object)); // 将 object 转换为 Map,Object.entries() 方法用于返回一个给定对象自身可枚举属性的键值对数组,数组中的每个元素是一个包含键值对的数组,[ ["name", "Alice"], ["age", 30], ["city", "New York"] ]
//   //   formData.value.forEach((item) => {
//   //     if (objectMap.has(item.key)) {
//   //       item.component_props.default = objectMap.get(item.key);
//   //     }
//   //   });
//   //   historyData.value = history_data.data; // 历史表单字段数据
//   // }
// }

// 打开轮询用户是否关注
const onTap = () => {
  if (localStorage.getItem('weixin_subscribe') === '0') {
    // 清理之前的定时器(如果存在)
    if (subscribeCheckInterval) {
      clearInterval(subscribeCheckInterval);
    }
    subscribeCheckInterval = setInterval(() => {
      checkUserSubscribe()
    }, 1000);
  }
}

// 检查数据收集设置
const checkUserSubscribe = () => {
  // 判断是否需要关注公众号, 弹出二维码识别
  if (formSetting.value.wxzq_must_follow && formSetting.value.x_field_weixin_subscribe) {
    // 标记用户已关注
    localStorage.setItem('weixin_subscribe', 1);
    show_qrcode.value = false;
    // 清理定时器
    if (subscribeCheckInterval) {
      clearInterval(subscribeCheckInterval);
      subscribeCheckInterval = null;
    }
  }
  // 凭密码填写设置
  if (formSetting.value.mmtx_enable) {
    pwd_show.value = true;
  } else {
    pwd_show.value = false;
  }
}

// 检查密码验证功能
const checkUserPassword = () => {
  // 凭密码填写设置
  if (formSetting.value.mmtx_enable) {
    pwd_show.value = true;
  } else {
    pwd_show.value = false;
  }
}

/**
 * 合并并去重数据
 * @param {Array} data - 输入的数据数组,每个元素包含mode、logical_op和expr_list属性
 * @returns {Array} - 合并并去重后的数据数组
 *
 * 此函数旨在处理一组配置项,每个配置项由mode、logical_op和expr_list组成。
 * 它首先根据mode和logical_op属性合并相同的项目,然后在每个合并的项目中去重expr_list。
 * 合并的逻辑是基于mode和logical_op完全一致的情况下进行的。
 * 去重的逻辑是通过比较op、values和field_name属性来确定expr_list中的表达式是否重复。
 */
const mergeAndDeduplicate = (data) => {
  // 使用reduce函数合并数据
  return data.reduce((acc, current) => {
    // 查找是否已存在相同的项
    const existingItemIndex = acc.findIndex(item =>
        item.mode === current.mode && item.logical_op === current.logical_op
    );

    if (existingItemIndex !== -1) {
        // 如果存在相同项,则合并expr_list值
        acc[existingItemIndex].expr_list = acc[existingItemIndex].expr_list.concat(current.expr_list);
    } else {
        // 如果不存在相同项,则将当前项添加到累积器中
        acc.push(current);
    }

    // 返回处理后的累积器
    return acc;
  }, []).map(item => {
      // 从expr_list中移除重复项
      item.expr_list = item.expr_list.filter((expr, index, self) =>
          index === self.findIndex(e => (
              e.op === expr.op && JSON.stringify(e.values) === JSON.stringify(expr.values) && e.field_name === expr.field_name
          ))
      );
      return item;
  });
}

/**
 * 根据规则隐藏相应字段
 * 优化版本:修复了条件判断逻辑和规则处理顺序问题
 */
const checkRules = () => {
    const rule_list = formInfo.value['rule_list'] ? [...formInfo.value['rule_list']] : [];

    // 收集所有规则中涉及的字段
    const fieldsInRules = new Set();
    rule_list.forEach(rule => {
        if (rule.field_names && Array.isArray(rule.field_names)) {
            rule.field_names.forEach(fieldName => {
                fieldsInRules.add(fieldName);
            });
        }
    });

    // 初始化字段规则,只重置在规则中出现过的字段
    formData.value.forEach(item => {
        item.x_rules = [];
        // 只重置在规则中出现过的字段的disabled状态
        if (fieldsInRules.has(item.key) && item.component_props) {
            item.component_props.disabled = false;
        }
    });

    // 收集每个字段的规则
    rule_list.forEach(rule => {
        formData.value.forEach(item => {
            if (rule.field_names?.includes(item.key) && !rule.is_invalid) {
                item.x_rules.push({
                    mode: rule.mode,
                    logical_op: rule.logical_op,
                    expr_list: rule.expr_list,
                });
            }
        });
    });

    // 合并规则
    formData.value.forEach(item => {
        const mergedRules = mergeAndDeduplicate(item.x_rules);
        item.field_rules = mergedRules; // 保存所有合并后的规则
    });

    // 处理规则逻辑 - 支持多条规则
    formData.value.forEach(item => {
        if (item.field_rules && item.field_rules.length > 0 && item.component_props) {
            // 处理多条规则的逻辑
            const finalDisabledState = evaluateMultipleRules(item.field_rules);
            item.component_props.disabled = finalDisabledState;
        }
    });


    // 处理级联隐藏:如果规则字段被隐藏,其控制的字段也应该被隐藏
    handleCascadeHiding();
};

/**
 * 评估多条规则并确定最终的disabled状态
 * @param {Array} rulesList - 字段的所有规则数组
 * @returns {boolean} - 最终的disabled状态
 */
const evaluateMultipleRules = (rulesList) => {
    if (!rulesList || rulesList.length === 0) {
        return false; // 没有规则时默认显示
    }

    let showRules = [];
    let hideRules = [];

    // 分离SHOW和HIDE规则
    rulesList.forEach(rule => {
        if (rule.mode === 'SHOW') {
            showRules.push(rule);
        } else if (rule.mode === 'HIDE') {
            hideRules.push(rule);
        }
    });

    // 评估SHOW规则
    let showResult = true; // 默认显示
    if (showRules.length > 0) {
        // 如果有SHOW规则,需要至少一个SHOW规则条件满足才显示
        showResult = showRules.some(rule => evaluateRuleCondition(rule));
    }

    // 评估HIDE规则
    let hideResult = false; // 默认不隐藏
    if (hideRules.length > 0) {
        // 如果有HIDE规则,任何一个HIDE规则条件满足就隐藏
        hideResult = hideRules.some(rule => evaluateRuleCondition(rule));
    }

    // 最终逻辑:HIDE规则优先级更高
    // 如果任何HIDE规则满足,则隐藏
    // 否则根据SHOW规则决定
    if (hideResult) {
        return true; // 隐藏
    } else {
        return !showResult; // SHOW规则不满足时隐藏
    }
};

/**
 * 评估单条规则条件
 * @param {Object} fieldRules - 字段规则对象
 * @returns {boolean} - 条件是否满足
 */
const evaluateRuleCondition = (fieldRules) => {
    if (!fieldRules || !fieldRules.expr_list || fieldRules.expr_list.length === 0) {
        return false;
    }

    const results = [];

    fieldRules.expr_list.forEach(expr => {
        let form_submission_value = postData.value[expr.field_name];
        const rule_matching_value = expr.values || [];

        // 处理空值情况
        if (form_submission_value === null || form_submission_value === undefined) {
            results.push(false);
            return;
        }

        let matchResult = false;

        if (typeof form_submission_value === 'string') {
            // 处理字符串类型(单选,下拉)
            let cleanValue = form_submission_value;
            if (form_submission_value.indexOf(':') !== -1) {
                cleanValue = form_submission_value.split(':')[0];
            }
            matchResult = rule_matching_value.includes(cleanValue);
        } else if (Array.isArray(form_submission_value)) {
            // 处理数组类型(多选)
            const cleanValues = form_submission_value.map(item => {
                if (typeof item === 'string' && item.includes(':')) {
                    return item.split(':')[0].trim();
                }
                return item;
            });
            matchResult = _.intersection(rule_matching_value, cleanValues).length > 0;
        }

        results.push(matchResult);
    });

    // 根据逻辑操作符计算最终结果
    if (fieldRules.logical_op === 'AND') {
        return results.every(result => result === true);
    } else { // OR
        return results.some(result => result === true);
    }
};

/**
 * 处理级联隐藏逻辑
 */
const handleCascadeHiding = () => {
    const rule_list = formInfo.value['rule_list'] || [];

    // 获取所有规则控制字段的映射
    const ruleControlMap = new Map();
    rule_list.forEach(rule => {
        if (rule.expr_list && rule.expr_list.length > 0) {
            const controlField = rule.expr_list[0].field_name;
            if (!ruleControlMap.has(controlField)) {
                ruleControlMap.set(controlField, []);
            }
            ruleControlMap.get(controlField).push({
                field_names: rule.field_names || [],
                mode: rule.mode
            });
        }
    });

    // 检查级联隐藏
    formData.value.forEach(item => {
        if (ruleControlMap.has(item.key) && item.component_props && item.component_props.disabled) {
            // 如果控制字段被隐藏,则隐藏其控制的所有字段
            const controlledRules = ruleControlMap.get(item.key);
            controlledRules.forEach(rule => {
                rule.field_names.forEach(fieldName => {
                    const targetField = formData.value.find(field => field.key === fieldName);
                    if (targetField && targetField.component_props) {
                        targetField.component_props.disabled = true;
                    }
                });
            });
        }
    });
}


// 处理没有绑定值的组件的赋值
// 省市区选择,图片上传,文件上传,电子签名,评分组件
// const area_picker = ref([]);
const image_uploader = ref([]);
const file_uploader = ref([]);
const table_editor = ref([]);
const sign = ref([]);
// const rate_picker = ref([]);
// const appointment = ref([]);
// 动态绑定ref数据
const setRefMap = (el, item) => {
  if (el) {
    if (item.component_props.tag === "image_uploader") {
      image_uploader.value.push(el);
    }
    if (item.component_props.tag === "file_uploader") {
      file_uploader.value.push(el);
    }
    if (item.component_props.tag === "table_editor") {
      table_editor.value.push(el);
    }
    // if (item.component_props.tag === "sign") {
    //   sign.value.push(el);
    // }
  }
};

// 操作绑定自定义字段回调
const onActive = (item) => {
  if (item?.key === "image_uploader") {
    postData.value[item.filed_name] = item.value;
  }
  if (item?.key === "file_uploader") {
    postData.value[item.filed_name] = item.value;
  }
  // if (item.key === "sign") {
  //   postData.value[item.filed_name] = item.value;
  // }
  if (item?.type === "radio") { // 单选控件
    postData.value = _.assign(postData.value, { [item.key]: item.affix ? item.affix : item.value });
  }
  if (item?.type === "gender") { // 性别控件
    postData.value = _.assign(postData.value, { [item.key]: item.affix ? item.affix : item.value });
  }
  if (item?.type === "checkbox") { // 多选控件
    const checkbox_value = _.cloneDeep(item.value)
    checkbox_value?.forEach((element, index) => {
      for (const key in item.affix) {
        if (item.affix[key] && element === key) {
          checkbox_value[index] = item.affix[key]
        }
      }
    });
    postData.value = _.assign(postData.value, { [item.key]: checkbox_value });
  }
  if (item?.type === "volunteer_group") { // 义工组别选择控件
    postData.value = _.assign(postData.value, { [item.key]: item.affix ? item.affix : item.value });
  }
  if (item?.type === "picker") { // 下拉框控件
    postData.value[item.key] = item.value;
  }
  if (item?.key === "table_editor") { // 表单控件
    postData.value[item.filed_name] = item.value;
  }
  // 检查规则,会影响字段显示
  checkRules();
};

// 检验没有绑定name的输入项
const validOther = () => {
  let valid = {
    status: true,
    key: "",
  };
  if (image_uploader.value) {
    // 图片上传
    image_uploader.value.forEach((item, index) => {
      if (image_uploader.value[index]?.validImageUploader && !image_uploader.value[index]?.validImageUploader()) {
        valid = {
          status: image_uploader.value[index]?.validImageUploader(),
          key: "image_uploader",
        };
        return false;
      }
    });
  }
  if (file_uploader.value) {
    // 文件上传
    file_uploader.value.forEach((item, index) => {
      if (file_uploader.value[index].validFileUploader && !file_uploader.value[index].validFileUploader()) {
        valid = {
          status: file_uploader.value[index].validFileUploader(),
          key: "file_uploader",
        };
        return false;
      }
    });
  }
  if (table_editor.value) {
    // 文件上传
    table_editor.value.forEach((item, index) => {
      if (table_editor.value[index].validTableEditor && !table_editor.value[index].validTableEditor()) {
        valid = {
          status: table_editor.value[index].validTableEditor(),
          key: "table_editor",
        };
        return false;
      }
    });
  }
  // if (sign.value) {
  //   // 电子签名
  //   sign.value.forEach((item, index) => {
  //     if (!sign.value[index].validSign()) {
  //       valid = {
  //         status: sign.value[index].validSign(),
  //         key: "sign",
  //       };
  //       return false;
  //     }
  //   });
  // }
  return valid;
};

// 预处理表单数据
const preValidData = (values) => {
  // 过滤掉标识为 ignore,undefined 的字段数据
  let { ignore, undefined, ...rest_data } = values;
  // 合并自定义字段到提交表单字段
  return _.assign(postData.value, rest_data);
}

const onRemove = (value) => { // 处理组件删除事件回调, 数据结构是二维数组,删除时返回被删除的一组数据
  value[0].forEach(item => {
    for (const key in postData.value) {
      if (item.key === key) {
        delete postData.value[key]; // 删除对应的键值对
      }
    }
  });
}

// const adjGroupData = (values) => { // 调整group组件的数据结构
//   // let obj = {
//   //   "field_10_group[0]_7653" : "1",
//   //   "field_10_group[1]_4154" : "11",
//   //   "field_11_group[0]_3440" : "2",
//   //   "field_11_group[1]_4282" : "22"
//   // }

//   // let arr = [{
//   //   "field_10": "1",
//   //   "field_11": "2",
//   // }, {
//   //   "field_10": "11",
//   //   "field_11": "22",
//   // }]
// }

const submitStatus = ref(false); // 表单提交按钮状态

const successHandle = () => { // 表单成功提交后续操作
  // 删除存在cookie, 提交成功后删除
  Cookies.remove($route.query.code);
  // 清理弹框状态,表单提交成功后重置
  resetDialogState();
  //在 iframe 中调用父页面中定义的变量 - Doris需要自由控制
  let getChildVal = parent.parent.getChildVal;
  if (getChildVal) {
    getChildVal();
    return false;
  }

  // iframe 项目标识 - 现在是美乐爱觉使用
  if (x_project === 'behalo') {
      // 向父页面发送消息
      const messageData = {
        id: successInfo.value?.id,
        type: 'formSubmit',
        timestamp: Date.now(),
      };

      try {
        // 发送消息到父页面
        if (window.parent && window.parent !== window) {
          window.parent.postMessage(messageData, '*');
          console.log('已向父页面发送消息:', messageData);
        }
      } catch (error) {
        console.error('发送消息到父页面失败:', error);
      }

      // 提交成功,直接返回
      return false;
  }

  // 如果类型为跳转网页
  if (successInfo.value.commit_action === 'url') {
    window.location.href = successInfo.value.commit_url;
  } else {
    // 把成功信息写进cookies
    Cookies.set(`form_${successInfo.value.id}_s_i`, JSON.stringify(successInfo.value), { expires: 1 });
    // 跳转成功页面
    $router.push({
      path: "/success",
      query: {
        successId: successInfo.value.id,
      },
    });
  }
}

const onSubmit = async (values) => { // 表单提交回调
  // 表单数据处理
  postData.value = preValidData(values);
  // 合并扩展字段
  postData.value = { ...postData.value, x_field_1, x_cycle };
  // formData.value disabled=true 数据处理, 表单页面上不显示
  let removeField = []; // 移除字段
  formData.value?.forEach(item => {
    if (item.component_props.disabled) {
      removeField.push(item);
      // 隐藏字段的值需要被置空
      // postData.value[item.key] = '';
      // 隐藏字段的值需要被删除
      delete postData.value[item.key];
    }
  });
  // 检查非表单输入项
  if (validOther().status) {
    // 编辑模式不能提交数据
    if (model === 'edit') {
      console.warn(removeField);
      console.warn(postData.value);
    }
    if (model === 'edit' || model === 'preview' || page_type === 'info') return false;
    // 提交按钮禁用
    submitStatus.value = true;
    // TAG: 不同类型提交表单处理
    if (page_type === 'add' || page_type == null) { // 新增表单提交
      let queryObj = { ...$route.query, ...postData.value };  // 大义工传递参数
      // 通过验证
      const result = await addFormDataAPI({
        form_code: $route.query.code,
        data: queryObj,
        openid: iframe_openid,
        flow_id: formSetting.value.flow_id, // 流程相关保存接口, 把flow_id传到后台
        flow_node_action_id: 'commit', // 流程节点的操作按钮的ID, 因为只有提交操作,ID写死
        force_back,
      });
      if (result.code) {
        // 提交按钮禁用状态
        submitStatus.value = false;
        // TAG: 提交成功提示
        showSuccessToast("提交成功");
        // 缓存表单返回值
        store.changeSuccessInfo(result.data);
        // TODO:校验手机号绑定状态
        let bind_status = true;
        if (!bind_status) {
          showConfirmDialog({
            title: '温馨提示',
            message: '您还没有绑定手机号,是否去绑定?',
            confirmButtonColor: styleColor.baseColor,
            cancelButtonText: '放弃'
          })
            .then(() => { // 确定去绑定手机号
              bind_tel_show.value = true;
            })
            .catch(() => { // 放弃手机号绑定
              // 表单成功提交后续操作
              successHandle();
            });
        } else {
          // 表单成功提交后续操作
          successHandle();
        }
      } else {
        // 提交按钮禁用状态
        submitStatus.value = false;
      }
    } else if (page_type === 'edit') { // 编辑表单提交
      // 从historyData历史数据里面,把隐藏字段移除
      removeField?.forEach(item => {
        if (item.component_props.disabled) {
          // 隐藏字段的值需要被删除
          delete historyData.value[item.key];
        }
      });
      // 显示的数据不是完整的数据, 把historyData历史数据合并到postData.value提交数据里面
      for (let key in historyData.value) {
        if (!(key in postData.value)) {
          postData.value[key] = historyData.value[key];
        }
      }
      // 编辑模式表单提交
      const result = await modiFormDataAPI({
        form_code: $route.query.code,
        data: postData.value,
        openid: iframe_openid,
        data_id,
        force_back
      });
      if (result.code) {
        // 提交按钮禁用状态
        submitStatus.value = false;
        //
        showSuccessToast("提交成功");
        // 缓存表单返回值
        store.changeSuccessInfo(result.data);
        // 表单成功提交后续操作
        successHandle();
      } else {
        // 提交按钮禁用状态
        submitStatus.value = false;
      }
    } else if (page_type === 'flow') { // 流程表单提交
      // 从historyData历史数据里面,把隐藏字段移除
      removeField?.forEach(item => {
        if (item.component_props.disabled) {
          // 隐藏字段的值需要被删除
          delete historyData.value[item.key];
        }
      });
      // 显示的数据不是完整的数据,把historyData历史数据合并到postData.value提交数据里面
      for (let key in historyData.value) {
        if (!(key in postData.value)) {
          postData.value[key] = historyData.value[key];
        }
      }
      const result = await flowFormDataAPI({
        form_code: $route.query.code,
        data: postData.value,
        data_id,
        flow_node_code,
        flow_node_action_id: flow_node_action_id.value,
        flow_content: approval_note.value,
        flow_reject_to_node_codes: checked_reject.value.length ? checked_reject.value.join(',') : '',
        force_back
      });
      if (result.code) {
        // 提交按钮禁用状态
        submitStatus.value = false;
        //
        showSuccessToast("操作成功");
        // 缓存表单返回值
        // store.changeSuccessInfo(result.data);
        //在 iframe 中调用父页面中定义的变量 - Doris需要自由控制
        let getChildVal = parent.parent.getChildVal;
        if (getChildVal) {
          getChildVal();
        }
      } else {
        // 提交按钮禁用状态
        submitStatus.value = false;
      }
    } else {
      console.warn('缺参数');
    }
  } else {
    // 提交按钮禁用状态
    submitStatus.value = false;
    console.warn(validOther().key + "不通过验证");
    // // 图片上传控件报错提示
    // if (validOther().key === "image_uploader") {
    //   showFailToast("图片上传为空");
    // }
    // // 文件上传控件报错提示
    // if (validOther().key === "file_uploader") {
    //   showFailToast("文件上传为空");
    // }
  }
};

const onFailed = (errorInfo) => { // 提交表单且验证不通过后触发
  console.log('表单验证失败:', errorInfo); // 添加调试信息

  // 检查是否有错误信息
  if (!errorInfo || !errorInfo.errors || errorInfo.errors.length === 0) {
    console.warn('没有具体的错误信息');
    showToast('表单验证失败,请检查输入内容');
    return;
  }

  const error_item = errorInfo.errors[0];
  console.log('第一个错误项:', error_item); // 添加调试信息

  // 通过name找到对应的label
  let error_name = '';
  formData.value.forEach(item => {
    if (item.key === error_item.name) {
      error_name = item.component_props.label
    }
  });

  // 确保有错误名称和消息
  const finalErrorName = error_name || error_item.name || '未知字段';
  const finalErrorMessage = error_item.message || '验证失败';

  console.log('显示错误提示:', finalErrorName + ': ' + finalErrorMessage);
  showToast(finalErrorName + ': ' + finalErrorMessage);
}

// TAG: 监听formData的变化,当有新的字段添加时重新设置监听器
watch(
  () => formData.value,
  () => {
    setupFieldWatchers();
  },
  {
    immediate: false, // 是否在初始化时立即执行一次回调
    flush: 'post', // 在组件更新后执行(可访问 DOM)
  }
);

// 监听postData的变化,当数据更新时检查规则
watch(
  () => postData.value,
  () => {
    // 延迟执行checkRules,确保数据更新完成
    nextTick(() => {
      checkRules();
    });
  },
  {
    deep: true, // 深度监听对象属性变化
    immediate: false,
    flush: 'post'
  }
);


// 为每个表单字段创建单独的监听器
// 可以监听到简单组件的字段的值变化,自定义的组件无法监听到
const setupFieldWatchers = () => {
  formData.value.forEach((field) => {
    watch(
      () => field.value,
      (newValue, oldValue) => {
        if (newValue !== oldValue) {
          console.log('字段变化=>', {
            key: field.key,
            name: field.name,
            comment: field.component_props.comment,
            oldValue: oldValue,
            newValue: newValue
          });
          // 延迟执行checkRules,确保数据更新完成
          nextTick(() => {
            checkRules();
          });
          // TAG: 大义工新增功能
          /**
           * 必须表单是新增表单时才触发
           * 如果别名是手机号, 并且是11位, 类型是义工,设置义工数据
           */
          if (volunteer_source === 'leader'
              && field.component_props.comment === 'phone'
              && (/^1\d{10}$/).test(newValue)
              && ( page_type === 'add' || page_type === undefined)
          ) {
            // 设置义工数据
            setVolunteerData(newValue);
          }
        }
      }
    );
  });
};

// 获取义工信息
const setVolunteerData = async (volunteer_phone) => {
  const volunteer_data = await getVolunteerSourceLeaderAPI({ form_code: $route.query.code, force_back, page_type, volunteer_source, volunteer_phone });
  if (volunteer_data.code) {
    let object = volunteer_data.data;
    const objectMap = new Map(Object.entries(object)); // 将 object 转换为 Map,Object.entries() 方法用于返回一个给定对象自身可枚举属性的键值对数组,数组中的每个元素是一个包含键值对的数组,[ ["name", "Alice"], ["age", 30], ["city", "New York"] ]
    formData.value.forEach((item) => {
      if (objectMap.has(item.key)) {
        item.component_props.default = objectMap.get(item.key);
      }
    });
  }
}

// TAG: 分页逻辑抽离为组合式函数
const {
    pages_raw,
    enable_pagination,
    current_page_index,
    filtered_pages,
    visible_keys,
    visible_form_data,
    buildPages,
    page_nav,
    handlePrev,
    handleNext,
    handleSubmit,
} = usePagination(formData, {
    myFormRef: myForm,
    validOther,
    afterSwitch: async () => {
        image_uploader.value = [];
        file_uploader.value = [];
        table_editor.value = [];
        await nextTick();
    }
});
</script>

<style lang="less">

:root:root {
  --van-floating-bubble-background: #C2915F;
}

:root {
  --border-style: 1px solid #eaeaea;
}

.table-title {
  padding: 1rem;
  font-size: 1.15rem;
  text-align: center;
  white-space: pre-wrap;
}

.table-desc {
  padding: 0rem 1rem;
  color: #666;
  font-size: 0.9rem;
  white-space: pre-wrap;
  line-height: 1.5;

  img {
    width: 100%;
  }
}

.table-box {
  background-color: #ffffff;
  padding-bottom: 1rem;
  overflow: auto;
  margin: 1rem 0;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  width: 10rem;
  // height: 10rem;
  background-color: #fff;
}

.pwd-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;

  .block {
    width: 80vw;
    background-color: #fff;
    padding: 1rem;
    border-radius: 5px;
  }
}

.bind-tel-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;

  .block {
    width: 80vw;
    background-color: #fff;
    padding: 1rem;
    border-radius: 5px;
  }
}

.PHeader-Text {
  padding: 1rem;
  font-weight: bold;
  white-space: pre;
}

// :deep(.van-icon) { // 处理正式服务器上箭头上下位移问题
//   font-size: var(--van-cell-icon-size);
//   line-height: var(--van-cell-line-height);
// }
</style>