form-dialog.vue 31.9 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
<template>
  <el-dialog 
    title="创建报销申请" 
    :visible.sync="visible" 
    :close-on-click-modal="false"
    class="NCC-dialog NCC-dialog_center" 
    width="1200px"
    @close="handleClose"
  >
    <div class="form-content" v-loading="loading">
      <el-form 
        ref="form" 
        :model="dataForm" 
        :rules="rules" 
        label-width="120px" 
        label-position="right"
      >
        <!-- 基本信息 -->
        <el-card class="form-card" shadow="hover">
          <div slot="header" class="card-header">
            <i class="el-icon-document"></i>
            <span class="card-title">基本信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="申请人" prop="applicationUserId">
                <user-select 
                  v-model="dataForm.applicationUserId" 
                  placeholder="请选择申请人" 
                  clearable
                  @change="handleUserChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请人姓名" prop="applicationUserName">
                <el-input 
                  v-model="dataForm.applicationUserName" 
                  placeholder="自动填充" 
                  readonly
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请门店" prop="applicationStoreId">
                <el-select 
                  v-model="dataForm.applicationStoreId" 
                  placeholder="自动填充" 
                  disabled
                  style="width: 100%"
                >
                  <el-option
                    v-for="store in storeOptions"
                    :key="store.id"
                    :label="store.dm"
                    :value="store.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请时间" prop="applicationTime">
                <el-date-picker
                  v-model="dataForm.applicationTime"
                  type="datetime"
                  placeholder="请选择申请时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="timestamp"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总金额" prop="amount">
                <el-input 
                  v-model="dataForm.amount" 
                  placeholder="自动计算" 
                  readonly
                >
                  <template slot="prepend">¥</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 选择购买记录 -->
        <el-card class="form-card" shadow="hover">
          <div slot="header" class="card-header">
            <i class="el-icon-shopping-cart-full"></i>
            <span class="card-title">选择购买记录</span>
          </div>
          <div>
            <el-button 
              type="primary" 
              icon="el-icon-plus" 
              @click="openPurchaseDialog"
            >
              选择购买记录
            </el-button>
            <span v-if="selectedPurchaseRecords.length > 0" class="selected-count">
              已选择 {{ selectedPurchaseRecords.length }} 条记录
            </span>
          </div>
          
          <!-- 已选择的购买记录列表 -->
          <div v-if="selectedPurchaseRecords.length > 0" class="purchase-list">
            <el-table :data="selectedPurchaseRecords" border size="small">
              <el-table-column prop="reimbursementCategoryName" label="分类名称" />
              <el-table-column prop="unitPrice" label="单价" >
                <template slot-scope="scope">
                  ¥{{ formatMoney(scope.row.unitPrice) }}
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量"  />
              <el-table-column prop="amount" label="金额" >
                <template slot-scope="scope">
                  ¥{{ formatMoney(scope.row.amount) }}
                </template>
              </el-table-column>
              <el-table-column prop="purchaseTime" label="购买时间" width="180">
                <template slot-scope="scope">
                  {{ formatDateTime(scope.row.purchaseTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template slot-scope="scope">
                  <el-button 
                    type="text" 
                    icon="el-icon-delete" 
                    @click="removePurchaseRecord(scope.$index)"
                    style="color: #F56C6C"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>

        <!-- 审批节点配置 -->
        <el-card class="form-card" shadow="hover">
          <div slot="header" class="card-header">
            <i class="el-icon-s-order"></i>
            <span class="card-title">审批流程配置</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item 
                label="选择审批流程" 
                prop="workflowConfigId"
                :rules="{ required: true, message: '请选择审批流程', trigger: 'change' }"
              >
                <el-select 
                  v-model="dataForm.workflowConfigId" 
                  placeholder="请选择审批流程"
                  filterable
                  clearable
                  @change="handleWorkflowConfigChange"
                  style="width: 100%"
                  :loading="workflowConfigLoading"
                >
                  <el-option
                    v-for="config in workflowConfigOptions"
                    :key="config.id"
                    :label="config.workflowName"
                    :value="config.id"
                  >
                    <span style="float: left">{{ config.workflowName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">
                      {{ config.description || '无描述' }}
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 显示选中的流程节点信息 -->
          <div v-if="dataForm.nodes && dataForm.nodes.length > 0" class="nodes-preview">
            <el-divider content-position="left">
              <i class="el-icon-info"></i>
              <span>流程节点信息</span>
            </el-divider>
            <div class="nodes-list">
              <div 
                v-for="(node, index) in dataForm.nodes" 
                :key="index"
                class="node-item"
              >
                <div class="node-header">
                  <span class="node-order">节点 {{ node.nodeOrder }}</span>
                  <el-tag :type="node.approvalType == '会签' ? 'success' : 'warning'" size="small">
                   {{ node.approvalType  }}
                  </el-tag>
                </div>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <div class="node-info">
                      <span class="info-label">节点名称:</span>
                      <span class="info-value">{{ node.nodeName || '无' }}</span>
                    </div>
                  </el-col>
                  <el-col :span="24" v-if="node.approverNames && node.approverNames.length > 0">
                    <div class="node-info">
                      <span class="info-label">审批人:</span>
                      <el-tag 
                        v-for="(name, nameIndex) in node.approverNames" 
                        :key="nameIndex"
                        size="small"
                        style="margin-right: 8px;"
                      >
                        {{ name }}
                      </el-tag>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
          <div v-else-if="dataForm.workflowConfigId" class="empty-nodes">
            <el-empty description="加载中..." :image-size="80" />
          </div>
          <div v-else class="empty-nodes">
            <el-empty description="请选择审批流程" :image-size="80" />
          </div>
        </el-card>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button 
        type="primary" 
        @click="handleSubmit"
        :loading="submitting"
      >
        创建并提交审批
      </el-button>
    </span>

    <!-- 选择购买记录弹窗 -->
    <el-dialog
      title="选择购买记录"
      :visible.sync="showPurchaseDialog"
      width="900px"
      append-to-body
    >
      <div class="purchase-dialog-content">
        <div class="purchase-search">
          <el-input
            v-model="purchaseSearchKeyword"
            placeholder="搜索分类名称"
            clearable
            @input="handlePurchaseSearch"
            style="width: 300px"
          >
            <el-button slot="append" icon="el-icon-search" @click="loadPurchaseRecords" />
          </el-input>
        </div>
        <el-table
          :data="purchaseRecordList"
          v-loading="purchaseLoading"
          @selection-change="handlePurchaseSelectionChange"
          border
          max-height="400"
        >
          <el-table-column type="selection" width="55"/>
          <el-table-column prop="reimbursementCategoryName" label="分类名称" />
          <el-table-column prop="unitPrice" label="单价" >
            <template slot-scope="scope">
              ¥{{ formatMoney(scope.row.unitPrice) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量"  />
          <el-table-column prop="amount" label="金额" >
            <template slot-scope="scope">
              ¥{{ formatMoney(scope.row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="purchaseTime" label="购买时间" width="180">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.purchaseTime) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="purchase-pagination">
          <el-pagination
            @size-change="handlePurchaseSizeChange"
            @current-change="handlePurchaseCurrentChange"
            :current-page="purchaseQuery.currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="purchaseQuery.pageSize"
            layout="total, sizes, prev, pager, next"
            :total="purchaseTotal"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showPurchaseDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmPurchaseSelection">确 定</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { getUserInfoList } from '@/api/permission/user'

export default {
  name: 'FormDialog',
  data() {
    return {
      visible: false,
      loading: false,
      submitting: false,
      storeOptions: [],
      dataForm: {
        applicationUserId: '',
        applicationUserName: '',
        applicationStoreId: '',
        applicationTime: null,
        amount: '0.00',
        selectedPurchaseRecordIds: [],
        workflowConfigId: '', // 选中的工作流配置ID
        nodes: []
      },
      workflowConfigOptions: [], // 工作流配置选项列表
      workflowConfigLoading: false, // 工作流配置加载状态
      rules: {
        applicationStoreId: [
          { required: true, message: '请选择申请门店', trigger: 'change' }
        ],
        applicationTime: [
          { required: true, message: '请选择申请时间', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '总金额不能为空', trigger: 'blur' }
        ],
        selectedPurchaseRecordIds: [
          { required: true, message: '请至少选择一条购买记录', trigger: 'change', validator: this.validatePurchaseRecords }
        ],
        workflowConfigId: [
          { required: true, message: '请选择审批流程', trigger: 'change' }
        ]
      },
      selectedPurchaseRecords: [],
      showPurchaseDialog: false,
      purchaseRecordList: [],
      purchaseLoading: false,
      purchaseSearchKeyword: '',
      purchaseQuery: {
        currentPage: 1,
        pageSize: 20,
        reimbursementCategoryName: ''
      },
      purchaseTotal: 0,
      purchaseSelection: []
    }
  },
  created() {
    this.loadStoreOptions()
    this.loadWorkflowConfigOptions()
  },
  methods: {
    openPurchaseDialog() {
      this.showPurchaseDialog = true
      this.loadPurchaseRecords()
    },
    async init() {
      this.visible = true
      this.loading = false
      this.submitting = false
      
      // 获取当前登录用户信息
      const currentUser = this.$store.getters.userInfo
      const defaultUserId = currentUser && (currentUser.userId || currentUser.id) ? (currentUser.userId || currentUser.id) : ''
      const defaultUserName = currentUser && (currentUser.realName || currentUser.fullName || currentUser.userName) ? (currentUser.realName || currentUser.fullName || currentUser.userName) : ''
      
      this.dataForm = {
        applicationUserId: defaultUserId,
        applicationUserName: defaultUserName,
        applicationStoreId: '',
        applicationTime: new Date().getTime(),
        amount: '0.00',
        selectedPurchaseRecordIds: [],
        workflowConfigId: '', // 重置工作流配置ID
        nodes: []
      }
      this.selectedPurchaseRecords = []
      
      // 如果有默认用户,自动填充门店
      if (defaultUserId) {
        this.handleUserChange(defaultUserId)
      }
    },

    // 加载启用的工作流配置列表
    async loadWorkflowConfigOptions() {
      this.workflowConfigLoading = true
      try {
        const response = await request({
          url: '/api/Extend/LqReimbursementWorkflowConfig/Actions/GetEnabledList',
          method: 'GET'
        })
        if (response.code === 200 && response.data && response.data.list) {
          this.workflowConfigOptions = response.data.list
        } else {
          this.workflowConfigOptions = []
        }
      } catch (error) {
        console.error('加载工作流配置列表失败:', error)
        this.$message.error('加载工作流配置列表失败')
        this.workflowConfigOptions = []
      } finally {
        this.workflowConfigLoading = false
      }
    },

    // 工作流配置改变时,加载详情
    async handleWorkflowConfigChange(workflowConfigId) {
      if (!workflowConfigId) {
        this.dataForm.nodes = []
        return
      }
      
      this.loading = true
      try {
        const response = await request({
          url: `/api/Extend/LqReimbursementWorkflowConfig/${workflowConfigId}`,
          method: 'GET'
        })
        
        if (response.code === 200 && response.data) {
          const configData = response.data
          
          // 转换节点数据格式
          if (configData.nodes && Array.isArray(configData.nodes)) {
            this.dataForm.nodes = configData.nodes.map(node => {
              // 从 approvers 数组中提取 userId 和 userName
              let approverIds = []
              let approverNames = []
              
              if (Array.isArray(node.approvers) && node.approvers.length > 0) {
                approverIds = node.approvers.map(approver => approver.userId).filter(id => id)
                approverNames = node.approvers.map(approver => approver.userName).filter(name => name)
              } else if (Array.isArray(node.approverIds)) {
                approverIds = node.approverIds
                approverNames = node.approverNames || []
              }
              
              // 处理 approvalType:可能是字符串 "1" 或数字 1
              let approvalType = node.approvalType
              if (typeof approvalType === 'string') {
                approvalType = approvalType === '1' || approvalType === '会签' ? '会签' : '或签'
              } else if (typeof approvalType === 'number') {
                approvalType = approvalType == 1 ? '会签' : '或签'
              } else {
                approvalType = '会签'
              }
              
              return {
                nodeOrder: node.nodeOrder,
                nodeName: node.nodeName || '',
                approvalType: approvalType,
                approverIds: approverIds, // 提交时需要数组格式
                approverNames: approverNames
              }
            })
          } else {
            this.dataForm.nodes = []
            this.$message.warning('该工作流配置没有节点信息')
          }
        } else {
          this.$message.error('加载工作流配置详情失败')
          this.dataForm.nodes = []
        }
      } catch (error) {
        console.error('加载工作流配置详情失败:', error)
        this.$message.error('加载工作流配置详情失败')
        this.dataForm.nodes = []
      } finally {
        this.loading = false
      }
    },

    async loadStoreOptions() {
      try {
        const response = await request({
          url: '/api/Extend/LqMdxx',
          method: 'GET',
          data: {
            currentPage: 1,
            pageSize: 1000
          }
        })
        if (response.code === 200 && response.data && response.data.list) {
          this.storeOptions = response.data.list
        }
      } catch (error) {
        console.error('加载门店列表失败:', error)
      }
    },

    // 申请人改变时,自动填充申请人姓名和申请门店
    handleUserChange(userId) {
      if (userId) {
        // 处理userId可能是字符串(逗号分隔)的情况,取第一个
        const userIdArray = typeof userId === 'string' 
          ? userId.split(',').filter(id => id && id.trim())
          : [userId]
        const actualUserId = userIdArray.length > 0 ? userIdArray[0] : userId
        
        // 获取用户信息
        request({
          url: '/api/permission/Users/' + actualUserId,
          method: 'GET',
        }).then(res => {
          if (res.code === 200 && res.data) {
            this.dataForm.applicationUserName = res.data.realName || res.data.userName || res.data.fullName || ''
            this.dataForm.applicationStoreId = res.data.mdid || ''
          }
        }).catch(error => {
          console.error('获取用户信息失败:', error)
        })
      } else {
        // 清空申请人时,也清空姓名和门店
        this.dataForm.applicationUserName = ''
        this.dataForm.applicationStoreId = ''
      }
    },

    async handleApproverChange(index, userIds) {
      const node = this.dataForm.nodes[index]
      
      // user-select组件返回的是字符串(逗号分隔的ID)
      // 但我们需要保存为字符串格式,因为组件期望字符串
      const idsString = userIds || ''
      node.approverIds = idsString
      
      // 转换为数组用于获取用户名
      const idsArray = idsString ? idsString.split(',').filter(id => id && id.trim()) : []
      
      // 获取用户名列表
      if (idsArray.length > 0) {
        try {
          const response = await getUserInfoList(idsArray)
          if (response.code === 200 && response.data && response.data.list) {
            // 创建ID到用户信息的映射,确保顺序正确
            const userMap = new Map()
            response.data.list.forEach(user => {
              userMap.set(user.id, user.fullName || user.realName || user.id)
            })
            
            // 按照原始ID数组的顺序,从映射中取出对应的用户名
            node.approverNames = idsArray.map(id => {
              return userMap.get(id) || id
            })
          } else {
            node.approverNames = idsArray
          }
        } catch (error) {
          console.error('获取用户名失败:', error)
          // 如果获取失败,使用ID作为名称
          node.approverNames = idsArray
        }
      } else {
        node.approverNames = []
      }
      console.error(node)
    },

    async loadPurchaseRecords() {
      this.purchaseLoading = true
      try {
        const params = {
          currentPage: this.purchaseQuery.currentPage,
          pageSize: this.purchaseQuery.pageSize,
          approveStatus: '未审批', // 只选择未审批的购买记录
          createUserStoreId: this.dataForm.applicationStoreId || '暂无',
        }
        if (this.purchaseSearchKeyword) {
          params.reimbursementCategoryName = this.purchaseSearchKeyword
        }
        const response = await request({
          url: '/api/Extend/LqPurchaseRecords',
          method: 'GET',
          data: params
        })
        if (response.code === 200 && response.data) {
          this.purchaseRecordList = response.data.list || []
          this.purchaseTotal = (response.data.pagination && response.data.pagination.total) || 0
        }
      } catch (error) {
        console.error('加载购买记录失败:', error)
        this.$message.error('加载购买记录失败')
      } finally {
        this.purchaseLoading = false
      }
    },

    handlePurchaseSearch() {
      this.purchaseQuery.currentPage = 1
      this.loadPurchaseRecords()
    },

    handlePurchaseSelectionChange(selection) {
      this.purchaseSelection = selection
    },

    confirmPurchaseSelection() {
      // 合并新选择的记录
      const newRecords = this.purchaseSelection.filter(item => {
        return !this.selectedPurchaseRecords.find(record => record.id === item.id)
      })
      this.selectedPurchaseRecords = [...this.selectedPurchaseRecords, ...newRecords]
      this.calculateAmount()
      this.showPurchaseDialog = false
    },

    removePurchaseRecord(index) {
      this.selectedPurchaseRecords.splice(index, 1)
      this.calculateAmount()
    },

    calculateAmount() {
      // 计算总金额
      let total = 0
      this.selectedPurchaseRecords.forEach(record => {
        total += Number(record.amount || 0)
      })
      this.dataForm.amount = total.toFixed(2)
      this.dataForm.selectedPurchaseRecordIds = this.selectedPurchaseRecords.map(record => record.id)
    },

    handlePurchaseSizeChange(val) {
      this.purchaseQuery.pageSize = val
      this.loadPurchaseRecords()
    },

    handlePurchaseCurrentChange(val) {
      this.purchaseQuery.currentPage = val
      this.loadPurchaseRecords()
    },

    validatePurchaseRecords(rule, value, callback) {
      if (!this.selectedPurchaseRecords || this.selectedPurchaseRecords.length === 0) {
        callback(new Error('请至少选择一条购买记录'))
      } else {
        callback()
      }
    },

    async handleSubmit() {
      // 验证表单
      this.$refs.form.validate(async (valid) => {
        if (!valid) {
          return false
        }

        // 验证节点数量
        if (!this.dataForm.nodes || this.dataForm.nodes.length < 1) {
          this.$message.warning('请选择审批流程')
          return false
        }
        
        if (this.dataForm.nodes.length > 5) {
          this.$message.warning('审批节点数量不能超过5个')
          return false
        }

        // 验证每个节点
        for (let i = 0; i < this.dataForm.nodes.length; i++) {
          const node = this.dataForm.nodes[i]
          if (!node.nodeName) {
            this.$message.warning(`节点${node.nodeOrder}的名称不能为空`)
            return false
          }
          if (!node.approvalType) {
            this.$message.warning(`节点${node.nodeOrder}的审批类型不能为空`)
            return false
          }
          // 验证审批人:approverIds应该是数组
          let approverIdsArray = []
          if (node.approverIds) {
            if (Array.isArray(node.approverIds)) {
              approverIdsArray = node.approverIds.filter(id => id && id.trim())
            } else if (typeof node.approverIds === 'string') {
              approverIdsArray = node.approverIds.split(',').filter(id => id && id.trim())
            }
          }
          if (approverIdsArray.length === 0) {
            this.$message.warning(`节点${node.nodeOrder}至少需要选择一个审批人`)
            return false
          }
        }

        // 验证购买记录
        if (!this.selectedPurchaseRecords || this.selectedPurchaseRecords.length === 0) {
          this.$message.warning('请至少选择一条购买记录')
          return false
        }

        this.submitting = true
        try {
          // 准备提交数据
          const submitData = {
            applicationUserId: this.dataForm.applicationUserId || undefined,
            applicationUserName: this.dataForm.applicationUserName || undefined,
            applicationStoreId: this.dataForm.applicationStoreId,
            applicationTime: this.dataForm.applicationTime,
            amount: this.dataForm.amount,
            workflowConfigId: this.dataForm.workflowConfigId || undefined,
            selectedPurchaseRecordIds: this.dataForm.selectedPurchaseRecordIds,
            nodes: this.dataForm.nodes.map(node => {
              // 确保 approverIds 是数组格式
              let approverIds = []
              if (node.approverIds) {
                if (Array.isArray(node.approverIds)) {
                  approverIds = node.approverIds.filter(id => id && id.trim())
                } else if (typeof node.approverIds === 'string') {
                  approverIds = node.approverIds.split(',').filter(id => id && id.trim())
                }
              }
              
              // 确保 approverNames 是数组格式
              let approverNames = []
              if (node.approverNames && Array.isArray(node.approverNames)) {
                approverNames = node.approverNames
              } else if (approverIds.length > 0) {
                // 如果没有名称,使用ID作为名称
                approverNames = approverIds
              }
              
              // 确保 approvalType 是字符串格式("会签" 或 "或签")
              let approvalType = node.approvalType
              if (typeof approvalType === 'number') {
                approvalType = approvalType == 1 ? '会签' : '或签'
              } else if (typeof approvalType === 'string') {
                // 如果是 "1" 或 "0",转换为 "会签" 或 "或签"
                if (approvalType === '1') {
                  approvalType = '会签'
                } else if (approvalType === '0') {
                  approvalType = '或签'
                }
                // 如果已经是 "会签" 或 "或签",保持不变
              } else {
                approvalType = '会签' // 默认值
              }
              
              return {
                nodeOrder: node.nodeOrder,
                nodeName: node.nodeName,
                approvalType: approvalType,
                approverIds: approverIds,
                approverNames: approverNames
              }
            })
          }
          console.log(submitData)
          // return
          // 创建报销申请
          const response = await request({
            url: '/api/Extend/LqReimbursementApplication',
            method: 'POST',
            data: submitData
          })

          if (response.code === 200) {
            this.$message.success('创建成功')
            
            // 创建成功后,自动提交审批
            let applicationId = null
            if (response.data) {
              // 如果返回的是对象,取id字段
              if (typeof response.data === 'object' && response.data.id) {
                applicationId = response.data.id
              } else if (typeof response.data === 'string') {
                // 如果返回的是字符串,直接使用
                applicationId = response.data
              } else {
                // 如果返回的是其他类型,尝试转换为字符串
                applicationId = String(response.data)
              }
            }
            
            if (applicationId) {
              try {
                await request({
                  url: `/api/Extend/LqReimbursementApplication/${applicationId}/Actions/SubmitApproval`,
                  method: 'POST'
                })
                this.$message.success('已自动提交审批')
              } catch (error) {
                console.error('提交审批失败:', error)
                this.$message.warning('创建成功,但提交审批失败,请手动提交')
              }
            } else {
              this.$message.warning('创建成功,但无法获取申请ID,请手动提交审批')
            }
            
            this.visible = false
            this.$emit('refresh')
          } else {
            this.$message.error(response.msg || '创建失败')
          }
        } catch (error) {
          console.error('创建失败:', error)
          this.$message.error('创建失败')
        } finally {
          this.submitting = false
        }
      })
    },

    handleClose() {
      this.visible = false
      this.$refs.form && this.$refs.form.resetFields()
      this.dataForm = {
        applicationUserId: '',
        applicationUserName: '',
        applicationStoreId: '',
        applicationTime: new Date().getTime(),
        amount: '0.00',
        selectedPurchaseRecordIds: [],
        workflowConfigId: '',
        nodes: []
      }
      this.selectedPurchaseRecords = []
    },

    formatMoney(amount) {
      if (!amount) return '0.00'
      return Number(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },

    formatDateTime(dateTime) {
      if (!dateTime) return '无'
      const date = new Date(dateTime)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }
  }
}
</script>

<style lang="scss" scoped>
.form-content {
 // max-height: 70vh;
  overflow-y: auto;
  padding: 0 10px;
}

.form-card {
  margin-bottom: 20px;

  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #303133;

    i {
      font-size: 18px;
      color: #409EFF;
    }

    .card-title {
      flex: 1;
    }
  }
}

.selected-count {
  margin-left: 12px;
  color: #67C23A;
  font-size: 14px;
}

.purchase-list {
  margin-top: 16px;
}

.nodes-list {
  .node-item {
    padding: 16px;
    margin-bottom: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    background: #fafafa;

    .node-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      padding-bottom: 12px;
      border-bottom: 1px solid #e4e7ed;

      .node-order {
        font-weight: 600;
        color: #409EFF;
        font-size: 16px;
      }
    }
    
    .node-info {
      margin-bottom: 12px;
      
      .info-label {
        color: #606266;
        font-weight: 500;
        margin-right: 8px;
      }
      
      .info-value {
        color: #303133;
      }
    }
  }

  .empty-nodes {
    padding: 40px;
    text-align: center;
  }
}

.nodes-preview {
  margin-top: 16px;
}

.purchase-dialog-content {
  .purchase-search {
    margin-bottom: 16px;
  }

  .purchase-pagination {
    margin-top: 16px;
    text-align: right;
  }
}
</style>