<template>
  <div>
    <!--   上方流程显示   -->
    <a-card :bordered="false" :loading="loading">
      <!--  项目进度流程  -->
      <work-flow-timeline
        :current-step-id="currentStepId"
        :active-step-id="activeStepId"
        :workflow-id="workflowId"
        :steps="stepsForChild"
        :state="workflowState"
        change-able
        @activeStep="activeStep"
        @reloadFromStep="handleReloadFromStep"/>
    </a-card>
    <!-- 无权访问的提示 -->
    <a-result v-show="!canSubmit" status="403" title="无权操作" sub-title="您没有访问该步骤的权限.">
    </a-result>
    <div v-show="canSubmit">
      <!-- 流程被退回的提示 -->
      <a-alert v-if="currentStep && currentStep.back && !(beforeStepActive || workflowState)" type="info" show-icon style="margin-bottom: 14px">
        <div slot="message">
          <span style="font-weight: bold">流程被退回</span>
          <span style="margin-left: 14px; font-size: 14px; color: rgba(0, 0, 0, 0.65)">请重新填写信息发起提交</span>
        </div>
        <div slot="description">
          <div>操作人：{{
            currentStep.back.f_operator
          }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;操作时间：{{ currentStep.back.f_date }}
          </div>
          <div>原因：{{ currentStep.back.f_notes }}</div>
        </div>
      </a-alert>
      <!-- 步骤内容主体 -->
      <a-tabs default-active-key="1" @change="note = ''" type="card">
        <a-tab-pane key="0" tab="步骤详情" v-if="beforeStepActive || workflowState">
          <a-card :bordered="false" :loading="loadingHistory" :body-style="{ paddingTop: 0 }">
            <!--   当前步骤历史记录   -->
            <template v-if="showTab">
              <x-tab
                :compProp="{ buttonState: { add: false, edit: false, delete: false, import: false, extra: false }, disableAction: true }"
                :local-config="tabDesigner"
                :body-style="{ padding: 0 }"
                :tabBarGutter="24"
                :extra-data="{ workflowId: workflowId, stepId: activeStepId }"
                default-active-key="workFlowTab">
                <a-tab-pane
                  :forceRender="true"
                  v-if="formCompletedDataPreview"
                  slot="extraBeforeTabs"
                  key="workFlowTab"
                  tab="表单"
                >
                  <work-flow-preview :form-completed-data-preview="formCompletedDataPreview"/>
                </a-tab-pane>
              </x-tab>
            </template>
            <template v-else-if="formCompletedDataPreview">
              <work-flow-preview :form-completed-data-preview="formCompletedDataPreview"/>
            </template>
            <template v-else>
              <a-result status="404" title="暂无数据" sub-title="该步骤暂无数据。">
              </a-result>
            </template>
          </a-card>
        </a-tab-pane>
        <a-tab-pane key="1" tab="业务操作" v-else v-show="renderCurrentNode">
          <a-card :bordered="false" :loading="loadingHistory" :body-style="{ paddingTop: 0 }">
            <x-tab
              v-if="showTab"
              :compProp="{ buttonState: { extra: true }, disableAction: false }"
              :local-config="tabDesigner"
              :extra-data="{ workflowId: workflowId, stepId: activeStepId }"
              :body-style="{ padding: 0 }"
              :tabBarGutter="24"
              default-active-key="workFlowTab">
              <a-tab-pane
                :forceRender="true"
                v-if="showForm"
                slot="extraBeforeTabs"
                key="workFlowTab"
                tab="表单"
                >
                <div v-if="historyFormCompletedDataPreview">
                  <work-flow-step-files-preview
                    :preview="historyFormCompletedDataPreview"
                  />
                  <a-divider/>
                </div>
                <x-add-native-form
                  ref="xAddForm"
                  @x-form-item-emit-func="formItemEmitFunc"
                  @onSubmit="submitForm"/>
              </a-tab-pane>
            </x-tab>
            <div v-else>
               <div v-if="historyFormCompletedDataPreview">
                 <work-flow-step-files-preview
                   :preview="historyFormCompletedDataPreview"
                 />
                 <a-divider/>
               </div>
              <x-add-native-form
                ref="xAddForm"
                @x-form-item-emit-func="formItemEmitFunc"
                @onSubmit="submitForm"/>
            </div>
            <a-divider/>

            <!-- 分支节点状态提示 -->
            <a-alert
              v-if="isBranchLastNode.isBranchNode && !isBranchLastNode.isLastBranch"
              type="info"
              show-icon
              style="margin-bottom: 16px"
            >
              <template slot="message">
                <span style="font-weight: bold;">分支节点等待中</span>
              </template>
              <template slot="description">
                <div>当前为分支节点，其他分支仍在进行中。完成当前分支后将等待其他分支完成，然后自动汇合到下一环节。</div>
                <div style="margin-top: 8px; color: #666; font-size: 12px;">
                  <a-icon type="info-circle" style="margin-right: 4px;" />
                  提示：此操作无需选择下一环节负责人，系统将自动处理流程流转。
                </div>
              </template>
            </a-alert>

            <a-alert
              v-if="isBranchLastNode.isBranchNode && isBranchLastNode.isLastBranch"
              type="success"
              show-icon
              style="margin-bottom: 16px"
            >
              <template slot="message">
                <span style="font-weight: bold;">分支汇合节点</span>
              </template>
              <template slot="description">
                <div>您正在处理最后一个未完成的分支节点，完成后将触发分支汇合并进入下一环节。</div>
              </template>
            </a-alert>

            <a-form v-show="!lastStep" label-align="left" :label-col="{ span: 3 }" :wrapper-col="{ span: 13 }">
              <a-form-item v-if="showStepNextBtn" label="操作类型" required>
                <a-radio-group v-model="operationType" @change="handleOperationTypeChange">
                  <a-radio value="submit">到下一步</a-radio>
                  <a-radio value="skip">{{ stepNextBtnTitle }}</a-radio>
                </a-radio-group>
              </a-form-item>

              <!-- 智能分支人员选择组件 - 只有非分支节点或最后一个分支才显示 -->
              <WorkflowPersonSelector
                v-if="!isBranchLastNode.isBranchNode || isBranchLastNode.isLastBranch"
                ref="personSelector"/>

              <a-form-item
                v-if="!isBranchLastNode.isBranchNode || isBranchLastNode.isLastBranch"
                label="下一环节截止时间"
                :validate-status="deadlineValidateStatus"
                :help="deadlineHelp"
                required>
                <a-date-picker
                  :getCalendarContainer="(triggerNode) => triggerNode.parentNode"
                  v-model="deadline"
                  value-format="YYYY-MM-DD HH:mm"
                  format="YYYY-MM-DD HH:mm"
                  :allow-clear="false"
                  :show-today="false"
                  show-time
                  placeholder="请选择"/>
              </a-form-item>
            </a-form>
            <a-divider/>
            <!--     备注信息    -->
            <a-textarea
              v-model="note"
              :auto-size="{ minRows: 3, maxRows: 5 }"
              placeholder="填写本环节备注事项"
            />
            <!--  当前步骤完成后，控制流程按钮  -->
            <div style="text-align: center">
              <a-radio-group style="margin-top: 20px">
                <a-space>
                  <!-- 动态按钮渲染 -->
                  <template v-if="buttonGroup && buttonGroup.actionArr">
                    <a-button
                      v-for="(button, index) in buttonGroup.actionArr"
                      :key="index"
                      v-show="checkButtonVisible(button)"
                      :type="button.type ? button.type : 'default'"
                      @click="handleCustomButtonClick(button)"
                    >
                      {{ button.text }}
                    </a-button>
                  </template>
                  <!-- 原有的按钮逻辑 -->
                  <template>
                    <a-popover v-if="operationType === 'submit'">
                      <template slot="content">
                        <p v-if="isBranchLastNode.isBranchNode && !isBranchLastNode.isLastBranch">
                          完成当前分支，等待其他分支完成后自动汇合
                        </p>
                        <p v-else-if="isBranchLastNode.isBranchNode && isBranchLastNode.isLastBranch">
                          完成最后一个分支并触发汇合到下一环节
                        </p>
                        <p v-else>{{ nextBtnTitle }}</p>
                      </template>
                      <a-button
                        v-if="!lastStep"
                        :disabled="!showNextBtn && !stepDone"
                        type="primary"
                        @click="nextClick"
                      >
                        完成提交
                        <a-icon type="right"/>
                      </a-button>
                    </a-popover>
                    <a-popover v-else :title="stepNextBtnTitle">
                      <template slot="content">
                        <p v-for="(item,index) in stepNextBtnText" :key="index">{{ item }}</p>
                      </template>
                      <a-button
                        v-if="showStepNextBtn && !lastStep"
                        type="primary"
                        @click="stepNextClick"
                      >
                        跳过
                      </a-button>
                    </a-popover>
                    <a-button
                      v-if="lastStep"
                      type="primary"
                      @click="lastStepNextClick"
                    >
                      确认完成
                    </a-button>
                  </template>
                </a-space>
              </a-radio-group>
            </div>
          </a-card>
        </a-tab-pane>
        <!-- 退回 -->
        <a-tab-pane v-if="canSubmit && !beforeStepActive && showPrevBtn && !workflowState" key="2" tab="退回">
          <a-form layout="vertical">
            <a-form-item label="退回原因" :wrapper-col="{ span: 24 }" required>
              <a-textarea
                v-model="backNote"
                :auto-size="{ minRows: 4, maxRows: 10 }"
                placeholder="请填写退回原因 / 备注"
              />
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 11 }">
              <a-popover :title="preBtnTitle">
                <template slot="content">
                  <p v-for="(item,index) in preBtnText" :key="index">{{ item }}</p>
                </template>
                <a-button
                  type="danger"
                  @click="preClick"
                >
                  <a-icon type="left"/>
                  退回
                </a-button>
              </a-popover>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <!--        <a-tab-pane v-if="canSubmit && !beforeStepActive && showPrevBtn && !workflowState" key="3" tab="工单拆分">
          &lt;!&ndash;   分配工单   &ndash;&gt;
          <workflow-list-resolution :workflow-project-id="workflowId" :details="details"></workflow-list-resolution>
        </a-tab-pane>-->
      </a-tabs>
    </div>
  </div>
</template>

<script>
import XAddNativeForm from '@vue2-client/base-client/components/common/XAddNativeForm'
import XFormTable from '@vue2-client/base-client/components/common/XFormTable/XFormTable'
import XAddForm from '@vue2-client/base-client/components/common/XAddForm/XAddForm'
import { postByServiceName } from '@vue2-client/services/api/restTools'
import { workFlowViewApi } from '@vue2-client/services/api/workFlow'
import { commonApi } from '@vue2-client/services/api'
import { formatDate } from '@vue2-client/utils/util'
import { mapState } from 'vuex'
import moment from 'moment'
import FilePreview from '@vue2-client/components/FilePreview'
import WorkFlowTimeline from '@vue2-client/pages/WorkflowDetail/WorkflowPageDetail/WorkFlowTimeline.vue'
import { FileItem, ImageItem } from '@vue2-client/components/FileImageItem'
import WorkflowListResolution from '@vue2-client/pages/WorkflowDetail/WorkflowPageDetail/WorkflowListResolution'
import { executeStrFunctionByContext } from '@vue2-client/utils/runEvalFunction'
import * as util from '@vue2-client/utils/util'
import { getConfigByNameAsync, runLogic } from '@vue2-client/services/api/common'
import LogicRunner from '@vue2-client/logic/LogicRunner'
import XTab from '@vue2-client/base-client/components/common/XTab/XTab.vue'
import WorkFlowPreview from '@vue2-client/pages/WorkflowDetail/WorkflowPageDetail/WorkFlowPreview'
import WorkFlowStepFilesPreview from '@vue2-client/pages/WorkflowDetail/WorkflowPageDetail/WorkFlowStepFilesPreview.vue'
import WorkflowPersonSelector from '@vue2-client/pages/WorkflowDetail/WorkflowPageDetail/components/WorkflowPersonSelector.vue'

export default {
  name: 'WorkFlowHandle',
  provide () {
    return {
      formDataChange: this.handleFormDataChange,
      workflowHandleWrap: this.workflowHandleWrap
    }
  },
  components: {
    XTab,
    WorkflowListResolution,
    XAddNativeForm,
    WorkFlowTimeline,
    XFormTable,
    XAddForm,
    FilePreview,
    FileItem,
    ImageItem,
    WorkFlowPreview,
    WorkFlowStepFilesPreview,
    WorkflowPersonSelector
  },
  computed: {
    workflowHandleWrap () {
      return this
    },
    ...mapState('account', { currUser: 'user' }),
    // 判断当前节点的分支状态
    isBranchLastNode () {
      // 默认返回值
      const defaultResult = {
        isBranchNode: false, // 是否为分支流程中的节点
        isLastBranch: false // 是否为最后一个未完成的分支（需要选择下一环节人员）
      }

      // 如果是最后一步或没有下一步或者不能提交，则不是分支节点
      if (this.lastStep || !this.nextBtnTo || !this.canSubmit) {
        return defaultResult
      }

      // 检查下一个节点是否为分支退出节点
      const nextStep = this.stepsDefine.find(step => step.id === this.nextBtnTo)

      // 如果下一个节点 没有有等待节点 waitStepIds, 说明不是分支的最后一个节点
      if (!nextStep
        || !(Object.prototype.hasOwnProperty.call(nextStep.properties, 'waitStepIds') &&
          Array.isArray(nextStep.properties?.waitStepIds) &&
          nextStep.properties?.waitStepIds.length > 0)
      ) {
        return defaultResult
      }

      // 获取分支退出节点等待的所有分支步骤ID
      const waitStepIds = nextStep.properties.waitStepIds || []
      if (waitStepIds.length === 0) {
        return {
          isBranchNode: true,
          isLastBranch: true // 如果没有等待步骤配置，默认认为是最后一个
        }
      }

      // 当前步骤必须在等待列表中才算是分支节点
      if (!waitStepIds.includes(this.activeStepId)) {
        return defaultResult
      }

      // 检查除当前步骤外的其他分支步骤状态
      const otherBranchSteps = waitStepIds.filter(stepId => stepId !== this.activeStepId)

      // 判断其他所有分支步骤是否都已完成（状态为2）
      const allOtherBranchesCompleted = otherBranchSteps.every(stepId => {
        const step = this.stepsForChild.find(s => s.id === stepId)
        return step && step.status === 2 // 已处理
      })

      return {
        isBranchNode: true, // 当前节点是分支流程中的节点
        isLastBranch: allOtherBranchesCompleted // 只有当其他所有分支都已完成时，当前分支才是最后一个
      }
    },
    canSubmit () {
      // 对于超级管理员直接认为可以提交
      if (this.currUser.rolesnames.indexOf('超级管理员') > -1) {
        return true
      }
      // currentStepId可能还没初始化，此处拿不到先返回false
      if (!this.currentStepId) {
        return false
      }
      const activeStep = this.stepsForChild.find(item => item.id === this.activeStepId)
      // 如果当前选中节点不是正在进行的节点，则判断viewers权限
      if ((this.activeStepId !== this.currentStepId && activeStep != null && activeStep.status !== 1) || (this.details.f_state === 1 && this.activeStepId === this.currentStepId)) {
        // 历史节点为当前登录人操作则不做查看数据权限校验
        if (activeStep.handler === this.currUser.name) {
          return true
        }
        const viewers = activeStep?.properties?.otherProperty?.viewers ?? []
        if (viewers.length > 0) {
          // 使用some方法判断当前人员是否满足任一条件
          return viewers.some(item => {
            if (item.type === 'role') {
              // 检查rolestr是否存在并包含指定角色
              return this.currUser.rolestr && this.currUser.rolestr.split(',').includes(item.name)
            }
            if (item.type === 'department') {
              // 检查depname是否存在并包含指定部门
              return this.currUser.deps && this.currUser.deps.includes(item.name)
            }
            return false
          })
        } else {
          return true
        }
      } else {
        // 当前进行节点的数据
        const step = this.stepsForChild.find(item => item.id === this.activeStepId)
        // 检查角色和部门权限
        if (step && step.properties && step.properties.chargePerson) {
          // 如果当前节点的负责人选项中有设置选择人员 当前节点就只能由上一步设置的负责人操作
          if (step.properties.chargePerson.needSelectPerson) {
            return step.handler === this.currUser.name
          }
          if (step.properties.chargePerson.personList && step.properties.chargePerson.personList.length > 0) {
            // 首先判断 是否 isCurrently 的值, 如果存在 isCurrently 使用 isCurrently 进行判断
            if ('isCurrently' in step) {
              return step.isCurrently
            }
            // 使用some方法判断当前人员是否满足任一条件
            return step.properties.chargePerson.personList.some(item => {
              if (item.type === 'role') {
                // 检查rolestr是否存在并包含指定角色
                return this.currUser.rolestr && this.currUser.rolestr.split(',').includes(item.name)
              }
              if (item.type === 'department') {
                // 检查parentname是否存在并包含指定部门
                return this.currUser.parentname && this.currUser.parentname.includes(item.name)
              }
              return false
            })
          }
        }

        // 检查handler是否包含当前用户
        if (step && step.handler) {
          return step.handler.includes(this.currUser.name)
        }
      }
      return false
    },
    formPreviewNoFileData () {
      return this.formCompletedDataPreview.data.filter(item => item.label !== '附件上传')
    }
  },
  data () {
    return {
      // noCache请求
      noCache: false,
      // 显示供用户填写的当前步骤表单
      showForm: false,
      // 显示步骤的tab页
      showTab: false,
      // tab页的配置
      tabDesigner: undefined,
      // 当前步骤表单标题
      formTitle: '',
      // 当前步骤表单定义Json
      stepDefine: [],
      // 当前步骤
      currentStep: undefined,
      // 当前步骤完成状态
      stepDone: false,
      // 所有节点连通数据
      directions: [],
      // 所有流程定义数据
      stepsDefine: [],
      // 当前步骤能通向的节点
      currentDirections: [],
      // 当前节点id
      currentStepId: undefined,
      // 当前活动节点 id
      activeStepId: 1,
      // 下一步按钮显示
      showNextBtn: false,
      // 回退按钮显示
      showPrevBtn: false,
      // 跳过按钮显示
      showStepNextBtn: false,
      // 定义三个按钮气泡提示内容
      preBtnTitle: '',
      preBtnText: [],
      nextBtnTitle: '',
      stepNextBtnTitle: '',
      stepNextBtnText: [],
      // 控制三个按钮跳转目标
      preBtnTo: undefined,
      nextBtnTo: undefined,
      stepNextBtnTo: undefined,
      // 控制当前标签页显示
      activeKey: '1',
      // 之前的节点是否激活
      beforeStepActive: false,
      // 之前节点中的数据
      beforeStepData: [],
      // 用于将已有数据，填回x-add表单中
      formCompletedData: {},
      // 用于展示提交的数据
      formCompletedDataPreview: null,
      historyFormCompletedDataPreview: null,
      // 切换至目标流程时，目标流程定义
      targetStepDefine: [],
      // 控制历史记录加载
      loadingHistory: true,
      // 控制表单校验
      formValid: false,
      // 备忘
      note: '',
      backNote: '', // 新增退回原因专用变量
      // 是否是最后一步
      lastStep: false,
      // 存储每一步骤填表人和时间数据
      stepsExtraInfo: [],
      // 控制基础信息页流程展示加载
      loading: true,
      // 激活的步骤名
      activeStepName: '',
      stepsParse: undefined,
      // 下一步处理人选择框数据
      chargePersonOptions: [],
      // 已选择下一步处理人
      checkedChargePerson: undefined,
      // 下一步截止时间
      deadline: this.getDefaultDeadline(),
      deadlineValidateStatus: '',
      deadlineHelp: '',
      // 当前任务是否延期
      // taskIsOverdue: moment().isAfter(this.completeTime, 'day'),
      // 操作类型，提交到下一步或跳过
      operationType: 'submit',
      // 获取微信推送是否成功信息
      information: [],
      // 是否需要选择人员
      needSelectPerson: true,
      // 下一环节人员信息
      chargePerson: {},
      // 动态按钮配置
      buttonGroup: null,
      // 分支节点相关数据
      branchNodes: [], // 需要选择人员的分支节点列表
      branchChargePersons: {}, // 分支节点人员选择 格式：{stepId: personId}
      needMultipleBranchSelection: false, // 是否需要为多个分支节点预先选择人员（包含WF_RESULT的条件分支或并行分支）
      calculatedTargetNode: null, // 前台计算出的目标节点
      currentBranchActions: null // 缓存当前的分支动作，避免重复调用
    }
  },
  async mounted () {
    await this.init()
    // this.checkDeadline()
  },
  props: {
    workflowId: {
      type: [String, Number],
      required: true
    },
    visible: {
      type: Boolean,
      default: false
    },
    stepsForChild: {
      type: Array,
      required: true
    },
    workflowState: {
      type: [Boolean, Number],
      required: true
    },
    completeTime: {
      type: String,
      required: true
    },
    taskName: {
      type: String,
      required: true
    },
    details: {
      type: Object,
      required: true
    },
    // 展开详情初始化的节点
    // 适用于不让第一个节点默认展示的情况
    initStepId: {
      type: [String, Number],
      required: false,
      default: null
    },
    renderCurrentNode: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    init () {
      this.getCurrentStep()
    },
    onClose () {
      this.activeStepId = this.currentStepId
      this.checkedChargePerson = undefined
      this.loadingHistory = true
      this.currentStepId = undefined
      this.directions = []
      this.currentDirections = []
      this.preBtnText = []
      this.stepNextBtnText = []
      this.stepsExtraInfo = []
      this.loading = true
      this.showNextBtn = false
      this.showStepNextBtn = false
      this.showPrevBtn = false
      this.stepDone = false
      this.formCompletedData = {}
      this.formCompletedDataPreview = null
      this.operationType = 'submit'

      // 清理分支节点相关数据
      this.branchNodes = []
      this.branchChargePersons = {}
      this.needMultipleBranchSelection = false
      this.calculatedTargetNode = null
      this.currentBranchActions = null
    },
    async showQueryFormItemFunc () {
      if (this.attr.showQueryFormItemFunc) {
        const obj = executeStrFunctionByContext(this, this.attr.showQueryFormItemFunc, [this.form, this.setForm, this.attr, util, this.mode])
        // 判断是 bool 还是  obj  兼容
        if (typeof obj === 'boolean') {
          this.show = obj
        } else if (obj && typeof obj === 'object') {
          // obj 是一个对象，并且不是数组
          this.show = obj?.show
          this.readOnly = obj?.readOnly
        }
      } else {
        this.show = true
      }
    },
    // 获取单个步骤的定义
    getSingleStepDefine (name) {
      for (const step of this.stepsDefine) {
        if (name === step.name) {
          return step.properties.form
        }
      }
    },
    // 日期格式化
    format (date, format) {
      return formatDate(date, format)
    },
    // 从指定步骤重新加载流程
    handleReloadFromStep (stepId) {
      this.$confirm({
        title: '确认操作',
        content: `确定要从步骤 ${stepId} 重新加载流程吗？`,
        onOk: async () => {
          try {
            // 调用后端 API 重新加载流程到指定步骤
            await postByServiceName(workFlowViewApi.refreshWorkFlowToStep, {
              workflowId: this.workflowId,
              stepId: stepId
            })
            this.currentStepId = stepId
            this.activeStepId = stepId
            this.$emit('refresh')
            this.noCache = true
            this.onClose()
            this.init()
            this.$message.success('已从指定节点重新加载')
          } catch (err) {
            this.$message.error('重新加载失败！')
            console.error(err)
          }
        }
      })
    },
    // 获取当前步骤
    getCurrentStep () {
      return postByServiceName(workFlowViewApi.getWorkFlowCurrentSubState, {
        workflowId: this.workflowId
      })
        .then(res => {
          // 优先级：主动传入的 > 获取到的
          this.currentStepId = this.initStepId || res.id

          // 如果指定了具体节点，同时设置activeStepId
          if (this.initStepId) {
            this.activeStepId = this.initStepId
          }

          const currentStep = this.stepsForChild.find(item => item.id === res.id)
          res.state = currentStep.name
          // 获取到当前步骤后复制下一步时间
          this.deadline = this.getDefaultDeadline(currentStep.properties?.otherProperty?.nextNodeInterval)
          this.currentStep = res
          this.getDirection()
        }, err => {
          console.log(err)
        })
    },
    // 完工按钮
    async lastStepNextClick () {
      this.$refs.xAddForm.asyncSubmit().then((res) => {
        this.submitForm(res).then(_ => {
          postByServiceName(workFlowViewApi.afterWorkFlowFinalStepSubmit, {
            workflowId: this.workflowId,
            stepId: this.currentStepId,
            submitUser: this.currUser.name,
            submitUserId: this.currUser.id
          }).then(_res => {
              this.saveWorkflowLog('确认完工', '最后一步: ' + this.getStepNameByStepId(this.currentStepId), { notes: this.note.trim() })
              this.$message.success('已完工！')
              this.loading = true
              this.loadingHistory = true
              this.onClose()
              this.$emit('success', { note: this.note.trim(), form: res.realForm, workflowId: this.workflowId })
            },
            () => {
              this.$message.error('提交失败！')
            }
          )
        })
      }).catch(err => {
        if (err && err.message === 'Form validation failed') {
          this.$message.error('请检查表单必填项！')
        } else {
          // 对于其他错误，继续向上抛出
          throw err
        }
      })
    },
    // 三个按钮点击后逻辑
    async nextClick () {
      // 检查是否为非最后分支节点
      const branchStatus = this.isBranchLastNode
      const isWaitingBranch = branchStatus.isBranchNode && !branchStatus.isLastBranch

      const extraData = this.getApplyStepExtraData(this.nextBtnTo)
      if (!extraData) {
        return
      }

      // 确认对话框
      const confirmContent = isWaitingBranch
        ? '确定完成当前分支么？完成后将等待其他分支，不会立即流转到下一环节。'
        : '确定提交么？提交之后数据不可更改！'

      await new Promise(resolve => {
        this.$confirm({
          title: '提交确认',
          content: confirmContent,
          onOk () {
            resolve()
            return Promise.resolve()
          }
        })
      })

      this.$refs.xAddForm.asyncSubmit().then(res => {
        this.submitForm(res).then(_ => {
          extraData.form = res.realForm
          postByServiceName(workFlowViewApi.submitToNextStep, extraData)
            .then(
              () => {
                let successMessage = '提交成功'

                // 只有非等待分支节点才保存工作流日志
                if (!isWaitingBranch) {
                  const branchStatus = this.isBranchLastNode
                  const operation = branchStatus.isBranchNode && branchStatus.isLastBranch ? '分支汇合' : '提交'

                  const extra = {
                    setHandler: this.getStepHandler(),
                    setDeadline: this.deadline,
                    notes: this.note.trim()
                  }
                  this.saveWorkflowLog(operation, this.generateBranchStepChangeText(this.currentStepId), extra)
                } else {
                  successMessage = '分支完成，等待其他分支完成后自动汇合'
                }

                this.$message.success(successMessage)
                this.loading = true
                this.loadingHistory = true
                this.$emit('nextClick', {
                  note: this.note.trim(),
                  form: res.realForm,
                  workflowId: this.workflowId,
                  isBranchWaiting: isWaitingBranch, // 标记是否为分支等待状态
                  ...this.generateStepChange(this.currentStepId, this.nextBtnTo)
                })
                this.$emit('refresh')
                this.onClose()
                this.init()
              },
              err => {
                this.$message.error('提交失败！')
                console.log(err)
              }
            )
        })
      }).catch((err) => {
        if (err && err.message === 'Form validation failed') {
          this.$message.error('请检查表单必填项！')
        } else {
          // 对于其他错误，继续向上抛出
          throw err
        }
      })
    },
    async preClick () {
      const notes = this.backNote.trim()
      if (!notes) {
        this.$message.error('退回请在备注中填写理由')
        return
      }
      return postByServiceName(workFlowViewApi.updateWorkFlowState, {
        stepId: this.preBtnTo,
        workflowId: this.workflowId,
        type: 'back'
      })
        .then(
          res => {
            this.saveWorkflowLog('退回', this.generateStepChangeText(this.currentStepId, this.preBtnTo), { notes })
            this.$message.success('退回成功')
            this.backNote = '' // 退回成功后清空退回原因
            this.loading = true
            this.loadingHistory = true
            this.currentStepId = this.preBtnTo
            this.activeStepId = this.preBtnTo

            // 新增：重置按钮状态
            this.stepDone = false
            this.beforeStepActive = false
            this.operationType = 'submit'

            this.$emit('refresh')
            this.$emit('preClick', {
              notes: notes,
              fromStepId: this.currentStepId,
              toStepId: this.preBtnTo
            })
            this.onClose()
            this.init()
          },
          err => {
            this.$message.error('退回失败！')
            console.log(err)
          }
        )
    },
    async stepNextClick () {
      const extraData = this.getApplyStepExtraData(this.stepNextBtnTo)
      if (!extraData) {
        return
      }
      this.$refs.xAddForm.asyncSubmit().then(res => {
        this.submitForm(res).then(_ => {
          extraData.form = res.realForm
          postByServiceName(workFlowViewApi.submitToNextStep, extraData)
            .then(
              () => {
                const extra = {
                  setHandler: this.getStepHandler(),
                  setDeadline: this.deadline,
                  notes: this.note.trim()
                }
                this.saveWorkflowLog('跳过', this.generateBranchStepChangeText(this.currentStepId), extra)
                this.$message.success('提交成功')
                this.$emit('nextClick', {
                  note: this.note.trim(),
                  form: res.realForm,
                  workflowId: this.workflowId,
                  ...this.generateStepChange(this.currentStepId, this.stepNextBtnTo)
                })
                this.loading = true
                this.loadingHistory = true
                this.$emit('refresh')
                this.onClose()
                this.init()
              },
              err => {
                this.$message.error('提交失败！')
                console.log(err)
              }
            )
        })
      }).catch(err => {
        if (err && err.message === 'Form validation failed') {
          this.$message.error('请检查表单必填项！')
        } else {
          // 对于其他错误，继续向上抛出
          throw err
        }
      })
    },
    // 获取当前步骤节点，连通的节点
    async getDirection () {
      // 获取流程定义
      const api = this.noCache ? workFlowViewApi.getWorkFlowDefineCache : workFlowViewApi.getWorkFlowDefine
      return postByServiceName(api, {
        id: this.workflowId
      })
        .then(async res => {
          this.noCache = false
          this.directions = []
          this.stepsDefine = res.steps
          await this.resolveDirections()
          this.resolveStep()
        }, err => {
          console.log(err)
        })
    },
    // 分析当前节点，能通向的节点
    async resolveDirections () {
      const currentStep = this.stepsForChild.find(item => item.id === this.activeStepId)
      if (currentStep?.properties?.actions) {
        this.currentDirections = currentStep.properties.actions
      }
      // 判断是否是最后ige节点
      this.lastStep = (currentStep?.properties?.actions || []).filter(item => {
        return item.type !== 'back'
      }).length === 0

      // 处理跳转按钮
      this.workflowControl()

      if (!this.lastStep) {
        // 分析分支节点并设置智能人员选择
        await this.analyzeBranchNodes()
      }
    },
    // 根据步骤id获取步骤名称
    getStepNameByStepId (stepId) {
      return this.stepsDefine.find(item => item.id === stepId)?.name
    },
    // 根据步骤id获取步骤状态
    getStepStatusByStepId (stepId) {
      return this.stepsForChild.find(item => item.id === stepId)?.status
    },
    // 表单提交的回调
    submitForm (obj) {
      this.formValid = true
      const formData = obj.realForm
      const time = this.format(new Date(), 'yyyy-MM-dd hh:mm:ss')
      return postByServiceName(workFlowViewApi.saveWorkFlowStepFormData, {
        workflowId: this.workflowId,
        stepId: this.activeStepId,
        form: formData,
        data: time,
        handler: this.currUser.name,
        note: this.note.trim()
      })
        .then(
          res => {
            console.log('表单提交成功')
            this.note = ''
            this.showForm = false
            this.stepDone = true
          },
          err => {
            this.$message.error('保存失败，请检查后重试')
            console.log(err)
          }
        )
    },
    // 获取当前步骤定义内容，构建组件
    async buildComp (stepId) {
      const properties = this.stepsDefine.find(item => item.id === stepId).properties
      this.historyFormCompletedDataPreview = null
      // 表单的渲染
      if (properties.form && properties.form.formJson) {

        // 当前处理环节 是否展示历史数据配置
        if (properties.otherProperty && properties.otherProperty.historyFormData) {
          const historyFormDataConfig = properties.otherProperty.historyFormData

          // 预处理
          const stepIdByName = new Map(this.stepsForChild.map(step => [step.name, step.id]))
          const stepFormJsonByStepId = new Map(
            this.stepsDefine.map(step => [step.id, step?.properties?.form?.formJson])
          )

          const stepIdSet = new Set()
          for (const historyFormConfig of historyFormDataConfig) {
            const targetStepId = stepIdByName.get(historyFormConfig.stepName)
            if (targetStepId == null) continue
            stepIdSet.add(targetStepId)
          }

          const stepIdS = Array.from(stepIdSet)
          if (stepIdS.length > 0) {
            const allStepData = await postByServiceName('/logic/geWorkFlowCompletedStepDataBySteps', {
              workflowId: this.workflowId,
              stepIdS
            })

            // 组装历史表单数据（data 部分）和按步骤分组的附件
            const historyFormData = []
            const stepAttachmentsMap = new Map()

            for (const historyFormConfig of historyFormDataConfig) {
              const targetStepId = stepIdByName.get(historyFormConfig.stepName)
              if (targetStepId == null) continue

              const stepFormJson = stepFormJsonByStepId.get(targetStepId)
              if (!stepFormJson) continue

              const stepDataRaw = allStepData?.[targetStepId] || allStepData?.[String(targetStepId)]
              if (!stepDataRaw) continue

              const isAttachment = historyFormConfig.displayLabel === '附件' && historyFormConfig.formLabel === '附件'

              if (isAttachment) {
                // 仅在配置了附件时才收集对应步骤的附件
                if (!stepAttachmentsMap.has(targetStepId)) {
                  stepAttachmentsMap.set(targetStepId, {
                    stepId: targetStepId,
                    stepName: historyFormConfig.stepName,
                    data: [],
                    images: [],
                    files: []
                  })
                }
                const attachment = stepAttachmentsMap.get(targetStepId)
                attachment.images = Array.isArray(stepDataRaw.images) ? stepDataRaw.images : []
                attachment.files = Array.isArray(stepDataRaw.files) ? stepDataRaw.files : []
              } else {
                const model = historyFormConfig.formLabel
                // 普通字段：从 data 中取值，并按 displayLabel 组织
                const value = stepDataRaw.data ? stepDataRaw.data[model] : undefined
                if (value === undefined || value === null) continue
                historyFormData.push({
                  label: historyFormConfig.displayLabel,
                  value
                })
              }
            }

            // 聚合所有步骤的附件到统一的 images/files，同时保留按步骤分组的数据
            const stepAttachments = Array.from(stepAttachmentsMap.values())

            this.historyFormCompletedDataPreview = {
              data: historyFormData,
              stepAttachments,
            }
          }
        }
        this.stepDefine = properties.form.formJson
        this.showForm = true
        this.$nextTick(() => {
          this.$refs.xAddForm && this.$refs.xAddForm.init({
            ...properties.form,
            paramLogicNameParam: { workflowId: this.workflowId },
            businessType: '修改',
            formItems: this.stepDefine,
            layout: properties.form.xAddFormLayout,
            showSubmitBtn: false
          })
          // 初始化的数据渲染（流程第一步）
          console.log('导入的原始数据-json', this.stepsForChild[0].f_data)
          console.log('转换后的数据-对象', JSON.parse(this.stepsForChild[0].f_data))
          if (stepId === 1) {
            this.$refs.xAddForm.setForm(JSON.parse(this.stepsForChild[0].f_data))
          }
        })
      } else {
        this.showForm = false
      }
      // Tab的渲染
      this.tabDesigner = properties.tabDesigner
      this.showTab = !!this.tabDesigner
      // 以当前激活节点分析节点
      await this.resolveDirections()
      this.resolveStep()
    },
    // 根据当前节点，判断之后流程，以及按钮的显示
    workflowControl () {
      // 重置所有控制数据为默认值，避免之前状态的影响
      this.showNextBtn = false
      this.nextBtnTo = undefined
      this.nextBtnTitle = ''
      this.showStepNextBtn = false
      this.stepNextBtnTo = undefined
      this.stepNextBtnTitle = ''
      this.stepNextBtnText = []
      this.showPrevBtn = false
      this.preBtnTo = undefined
      this.preBtnTitle = ''
      this.preBtnText = []

      // 分类收集不同类型的actions
      const submitActions = this.currentDirections.filter(item => item.type === 'submit')
      const conditionalActions = this.currentDirections.filter(item => item.type === 'conditionalBranch')
      const parallelActions = this.currentDirections.filter(item => item.type === 'parallelBranch')
      const skipActions = this.currentDirections.filter(item => item.type === 'skip')
      const backActions = this.currentDirections.filter(item => item.type === 'back')

      // 处理提交按钮 - 优先级：submit > conditionalBranch > parallelBranch
      if (submitActions.length > 0) {
        this.showNextBtn = true
        this.nextBtnTo = submitActions[0].to // 如果有多个submit，取第一个作为主要跳转目标
        if (submitActions.length === 1) {
          this.nextBtnTitle = '进行下一环节：' + this.getStepNameByStepId(submitActions[0].to)
        } else {
          this.nextBtnTitle = '将进入以下环节：' + submitActions.map(item => this.getStepNameByStepId(item.to)).join(' , ')
        }
      } else if (conditionalActions.length > 0) {
        this.showNextBtn = true
        this.nextBtnTo = conditionalActions[0].to // 条件分支的第一个作为主要跳转目标
        const targetSteps = conditionalActions.map(item => this.getStepNameByStepId(item.to)).join(' , ')
        this.nextBtnTitle = '后台判断后跳转到：' + targetSteps
      } else if (parallelActions.length > 0) {
        this.showNextBtn = true
        this.nextBtnTo = parallelActions[0].to // 并行分支的第一个作为主要跳转目标
        const targetSteps = parallelActions.map(item => this.getStepNameByStepId(item.to)).join(' , ')
        this.nextBtnTitle = '将并行进入以下分支：' + targetSteps
      }

      // 处理跳过按钮
      if (skipActions.length > 0) {
        this.showStepNextBtn = true
        this.stepNextBtnTo = skipActions[0].to
        if (skipActions.length === 1) {
          this.stepNextBtnTitle = '跳至：' + this.getStepNameByStepId(skipActions[0].to) + '环节'
          this.stepNextBtnText.push('将跳过以下环节：')
          for (let i = this.currentStepId; i < skipActions[0].to - 1; i++) {
            this.stepNextBtnText.push(this.stepsDefine[i].name)
          }
        } else {
          const targetSteps = skipActions.map(item => this.getStepNameByStepId(item.to)).join(' , ')
          this.stepNextBtnTitle = '跳至：' + targetSteps
        }
      }

      // 处理退回按钮
      if (backActions.length > 0) {
        const backAction = backActions[0] // 通常只有一个back action
        for (let i = this.currentStepId - 1; i > 0; i--) {
          if (backAction.to >= i && this.stepsForChild.find(item => item.id === i)?.handler) {
            this.preBtnTo = i
            this.preBtnTitle = '回退至：' + this.getStepNameByStepId(i) + '环节'
            this.showPrevBtn = true
            break
          } else {
            this.preBtnText.push(this.getStepNameByStepId(i))
          }
        }
        if (this.preBtnText.length) {
          this.preBtnText.unshift('将跳过以下环节：')
        }
      }
    },
    // 获取表单字段实际值
    getRealKey (key, isHandleFormKey) {
      if (key === 'selected_id') return key
      if (isHandleFormKey) {
        return key.substring(key.indexOf('_') + 1)
      } else {
        return key
      }
    },
    // 加载完成
    resolveStep () {
      // 获取当前步骤的按钮组配置
      const currentStep = this.stepsDefine.find(item => item.id === this.activeStepId)
      if (currentStep && currentStep.properties && currentStep.properties.buttonGroup) {
        this.buttonGroup = currentStep.properties.buttonGroup
      } else {
        this.buttonGroup = null
      }
      this.loading = false
    },
    // 流程图组件给当前组件传值用，stepNo为用户点击的非当前步骤
    async activeStep (stepId) {
      // 开启加载
      this.loadingHistory = true
      this.activeStepId = stepId
      // 获取激活节点的步骤名
      this.activeStepName = this.getStepNameByStepId(stepId)
      const status = this.getStepStatusByStepId(stepId)
      // 清空回显数据
      this.formCompletedData = {}
      let formCompletedDataPreview = null
      this.getStepDefine(stepId)
      // 判断激活的节点，是不是待完成节点 (当前节点或者 当前节点状态是1的)
      if ((this.activeStepName !== this.currentStep.state && status !== 1) || this.workflowState) {
        // 获取激活节点历史数据，和字段定义
        await this.getCompletedFormData(stepId)
        // 将回显数据拷贝，避免引用传递
        formCompletedDataPreview = JSON.parse(JSON.stringify(this.formCompletedData))
        const currentStepDefine = this.stepsDefine.find(item => item.id === stepId)
        const isKeyHandle = currentStepDefine?.properties?.form?.isKeyHandle || false
        if (!!currentStepDefine.properties.form?.paramLogicName) {
          // 确保 serviceName 是一个非空字符串
          const serviceName =
            (typeof currentStepDefine.properties.form?.paramLogicServiceName === 'string' &&
              currentStepDefine.properties.form.paramLogicServiceName.trim()) || process.env.VUE_APP_SYSTEM_NAME
          // console.warn('serviceName', serviceName)
          const data = await postByServiceName(`/logic/${currentStepDefine.properties.form.paramLogicName}`, { workflowId: this.workflowId, stepId: stepId, data: formCompletedDataPreview }, serviceName)
          // const data = await postByServiceName(`/logic/${currentStepDefine.properties.form.paramLogicName}`, { workflowId: this.workflowId, stepId: stepId, data: formCompletedDataPreview })
          formCompletedDataPreview = this.mergeFormData(formCompletedDataPreview, data)
        }
        // 使用字段定义中内容，将回显数据的列名，替换为定义的中文名
        // 调整逻辑：formData中只显示流程配置表单中定义过的显示列，多余冗余的存储列不进行页面展示
        const formDataArr = []
        const dataObj = formCompletedDataPreview.data || {}
        for (let i = 0; i < this.targetStepDefine.length; i++) {
          const stepDefine = this.targetStepDefine[i]
          const key = this.getRealKey(stepDefine.model, isKeyHandle)
          if (Object.prototype.hasOwnProperty.call(dataObj, key)) {
            // 历史表单内容根据流程中配置的表单项顺序进行渲染，需要兼容表单项展示函数
            if (stepDefine.showFormItemFunc && !(await this.showFormItemFunc(stepDefine.showFormItemFunc, dataObj))) {
              continue
            }
            if (['FilesId'].includes(key) || stepDefine.type === 'signature'){
              continue
            }
            let value = dataObj[key]
            // 如果字段类型是图片，获取图片的url
            if (stepDefine.type === 'image' && Array.isArray(value) && value.length > 0) {
              const urls = await postByServiceName(workFlowViewApi.getFilesUrlByIds, {
                ids: `(${value.map(id => Number(id)).join(',')})`
              })
              formDataArr.push({ label: stepDefine.name, value: urls.urls, type: 'image' })
              continue
            }
            // 字典值处理
            if (stepDefine.formType === 'select') {
              let dictList
              if (stepDefine.selectType === 'key') {
                dictList = await this.$appdata.getDictByKeyAsync(stepDefine.selectKey)
              } else if (stepDefine.selectType === 'config') {
                const configName = stepDefine.selectKey.substring(7)
                dictList = await this.$appdata.getDictByKeyAsync(configName)
              }
              const dictItem = dictList.find(item => item.value === value)
              value = dictItem ? dictItem.label : value
            }
            formDataArr.push({ label: stepDefine.name, value })
          }
        }
        // 如果一个都没匹配上，兼容旧逻辑：把原对象转成数组
        if (formDataArr.length === 0 && dataObj && typeof dataObj === 'object') {
          for (const key in dataObj) {
            if (Object.prototype.hasOwnProperty.call(dataObj, key)) {
              formDataArr.push({ label: key, value: dataObj[key] })
            }
          }
        }
        formCompletedDataPreview.data = formDataArr.length > 0 ? formDataArr : null
        if (!formCompletedDataPreview.data) {
          formCompletedDataPreview.data = null
        }
        // 备注
        formCompletedDataPreview.note = this.stepsForChild.find(item => item.id === stepId)?.note
        if (!formCompletedDataPreview.data && !formCompletedDataPreview.files.length && !formCompletedDataPreview.images.length && !formCompletedDataPreview.note) {
          formCompletedDataPreview = {}
        }
        this.formCompletedDataPreview = formCompletedDataPreview
        // 渲染已完成步骤的Tab
        const properties = this.stepsDefine.find(item => item.id === stepId).properties
        this.tabDesigner = properties.tabDesigner
        this.showTab = !!this.tabDesigner
        // 完成
        this.loadingHistory = false
        this.beforeStepActive = this.activeStepName !== this.currentStep.state
      } else {
        this.loadingHistory = false
        this.beforeStepActive = false
        if (!this.renderCurrentNode) {
          this.formCompletedDataPreview = null
          this.showTab = false
          this.beforeStepActive = true
          return
        }
        await this.buildComp(this.activeStepId)
      }
    },
    // 获取已经完成步骤的数据
    getCompletedFormData (stepId) {
      return postByServiceName(workFlowViewApi.getWorkFlowCompletedStepData, {
        workflowId: this.workflowId,
        stepId: stepId
      })
        .then(
          res => {
            this.formCompletedData = res
          },
          err => {
            console.log(err)
          }
        )
    },
    /**
     * 表单数据合并方法（适用于 Vue2）
     *
     * 合并规则说明：
     * 1. images、files：
     *    - 类型为数组
     *    - 直接合并（concat）
     *    - 任一方不存在时按空数组处理
     *
     * 2. data：
     *    - 类型为对象
     *    - key 同时存在：以后者（newData）为准
     *    - 只存在于一方：保留
     *
     * @param {Object} oldData  原始数据
     * @param {Object} newData  新数据
     */
    mergeFormData(oldData, newData) {
      const result = {}

      // images
      if (Array.isArray(oldData.images) || Array.isArray(newData.images)) {
        result.images = [
          ...(oldData.images || []),
          ...(newData.images || [])
        ]
      }

      // files
      if (Array.isArray(oldData.files) || Array.isArray(newData.files)) {
        result.files = [
          ...(oldData.files || []),
          ...(newData.files || [])
        ]
      }

      // data（核心）
      result.data = {
        ...(oldData.data || {}),
        ...(newData.data || {})
      }

      return result
    },
    // 获取步骤定义表中，当前步骤定义
    getStepDefine (stepId) {
      const stepName = this.getStepNameByStepId(stepId)
      this.targetStepDefine = this.getSingleStepDefine(stepName).formJson
    },
    // 获取提交步骤的额外数据
    getApplyStepExtraData (stepId) {
      // 验证人员选择 - 只有在需要显示人员选择器的情况下才验证
      // 判断条件与模板中的 WorkflowPersonSelector 显示条件保持一致
      const shouldShowPersonSelector = !this.isBranchLastNode.isBranchNode || this.isBranchLastNode.isLastBranch

      if (shouldShowPersonSelector && this.needSelectPerson) {
        if (this.needMultipleBranchSelection) {
          // 多分支情况：检查是否所有需要的分支都选择了人员
          const missingSelections = this.branchNodes.filter(node => !this.branchChargePersons[node.stepId])
          if (missingSelections.length > 0) {
            const missingNames = missingSelections.map(node => node.stepName).join('、')
            this.$message.error(`请设置以下节点的处理人：${missingNames}`)
            return false
          }
        } else {
          // 单分支情况：检查是否选择了处理人
          if (!this.checkedChargePerson) {
            this.$message.error('请设置下一环节处理人')
            return false
          }
        }
      }

      // 统一获取目标步骤IDs
      let stepIds = []
      if (this.needMultipleBranchSelection) {
        // 多分支选择：获取所有分支的目标stepId（包括不需要选择人员的）
        if (!this.currentBranchActions) {
          this.currentBranchActions = this.getBranchActions()
        }
        stepIds = this.currentBranchActions.allBranchActions.map(action => action.to)
      } else if (this.calculatedTargetNode) {
        // 条件判断节点：使用计算出的目标节点
        stepIds = [this.calculatedTargetNode]
      } else {
        // 普通节点：使用传入的stepId
        stepIds = [stepId]
      }
      // 处理bug 有的时候没带到 branchChargePersons 先循环在同一地方处理
      stepIds.forEach(stepItemId => {
        if (!this.branchChargePersons[stepItemId]) {
          const chargePerson = this.stepsForChild.find(item => item.id === stepItemId)?.properties?.chargePerson
          this.branchChargePersons[stepItemId] = this.normalizeChargePersonFormat(chargePerson)
        }
      })

      return {
        workflowId: this.workflowId,
        activeStepId: this.activeStepId,
        stepId, // 当前步骤ID
        stepIds, // 目标步骤IDs数组（统一格式）
        name: this.getStepNameByStepId(stepId),
        handler: this.getStepHandler(),
        handlerId: this.checkedChargePerson,
        needSelectPerson: this.needSelectPerson,
        personList: this.chargePerson.personList,
        deadline: this.deadline,
        submitUser: this.currUser.name,
        submitUserId: this.currUser.id,
        branchChargePersons: this.branchChargePersons
      }
    },

    // 获取当前选择的负责人
    getStepHandler () {
      let stepHandler

      if (this.needMultipleBranchSelection) {
        // 多分支情况：返回所有分支的人员信息
        const selectedHandlers = []
        for (const node of this.branchNodes) {
          const branchData = this.branchChargePersons[node.stepId]

          if (node.needSelectPerson && branchData) {
            // 需要选择人员的分支：显示选中的人员
            const personName = this.getBranchPersonName(node.stepId)
            selectedHandlers.push(`${node.stepName}:${personName}`)
          } else if (!node.needSelectPerson && branchData) {
            // 不需要选择人员的分支：显示角色/部门配置
            if (branchData.personList && branchData.personList.length > 0) {
              const personNames = branchData.personList.map(item => item.name).join(',')
              selectedHandlers.push(`${node.stepName}:${personNames}`)
            }
          }
        }
        stepHandler = selectedHandlers.join(';')
      } else {
        // 单分支情况：原有逻辑
        if (this.checkedChargePerson) {
          // 使用 value 找到对应的 label
          stepHandler = this.chargePersonOptions.find(item => item.value === this.checkedChargePerson)?.label
        } else if (this.chargePerson.personList && this.chargePerson.personList.length > 0) {
          stepHandler = this.chargePerson.personList.map(item => item.name).join(',')
        }
      }

      return stepHandler
    },

    // 获取分支节点选择的人员姓名
    getBranchPersonName (stepId) {
      const personId = this.branchChargePersons[stepId]
      if (!personId) return ''

      const node = this.branchNodes.find(n => n.stepId === stepId)
      if (!node) return ''

      const person = node.chargePersonOptions.find(p => p.value === personId)
      return person ? person.label : ''
    },
    // 生成工作流日志步骤变化描述
    generateStepChangeText (fromStepId, toStepId) {
      // 如果是多分支场景，toStepId可能是数组或字符串
      if (this.needMultipleBranchSelection && Array.isArray(toStepId)) {
        const targetSteps = toStepId.map(id => `第${id}步: ${this.getStepNameByStepId(id)}`).join('、')
        return `第${fromStepId}步: ${this.getStepNameByStepId(fromStepId)} --> ${targetSteps}`
      } else if (this.needMultipleBranchSelection && typeof toStepId === 'string') {
        // 如果传入的是目标步骤名称字符串
        return `第${fromStepId}步: ${this.getStepNameByStepId(fromStepId)} --> ${toStepId}`
      } else {
        // 单步骤场景
        return `第${fromStepId}步: ${this.getStepNameByStepId(fromStepId)} --> 第${toStepId}步: ${this.getStepNameByStepId(toStepId)}`
      }
    },

    // 生成多分支场景的步骤变化描述
    generateBranchStepChangeText (fromStepId) {
      if (!this.needMultipleBranchSelection) {
        return this.generateStepChangeText(fromStepId, this.nextBtnTo)
      }

      // 使用所有分支节点生成描述
      const targetSteps = this.branchNodes.map(node => `第${node.stepId}步: ${node.stepName}`).join('、')
      return `第${fromStepId}步: ${this.getStepNameByStepId(fromStepId)} --> ${targetSteps}`
    },

    generateStepChange (fromStepId, toStepId) {
      // 获取目标步骤IDs数组
      let stepIds = []

      if (this.needMultipleBranchSelection) {
        // 多分支选择：获取所有分支的目标stepId（包括不需要选择人员的）
        if (!this.currentBranchActions) {
          this.currentBranchActions = this.getBranchActions()
        }
        stepIds = this.currentBranchActions.allBranchActions.map(action => action.to)
      } else if (this.calculatedTargetNode) {
        // 条件判断节点：使用计算出的目标节点
        stepIds = [this.calculatedTargetNode]
      } else {
        // 普通节点：使用传入的stepId
        stepIds = [toStepId]
      }

      return {
        formStepId: fromStepId,
        fromStepId,
        stepId: toStepId,
        stepIds: stepIds,
        formStep: this.getStepNameByStepId(fromStepId),
        fromStep: this.getStepNameByStepId(fromStepId),
        toStep: this.getStepNameByStepId(stepIds[0]),
        successStepId: this.stepsDefine[this.stepsDefine.length - 1].id,
        successStep: this.stepsDefine[this.stepsDefine.length - 1].name
      }
    },
    // 保存工作流日志
    saveWorkflowLog (operation, desc, extra) {
      postByServiceName(workFlowViewApi.saveWorkFlowLog, {
        workflowId: this.workflowId,
        operation,
        desc,
        operator: this.currUser.name,
        notes: '',
        setHandler: '',
        setDeadline: '',
        ...extra
      })
    },
    // 获取默认截止时间
    getDefaultDeadline (day = 1) {
      const date = new Date()
      date.setDate(date.getDate() + day)
      date.setHours(date.getHours() + 2)
      return formatDate(date, 'yyyy-MM-dd hh:mm')
    },
    // 验证截止时间
    checkDeadline (alert) {
      const deadline = moment(this.deadline)
      if (deadline.isAfter(this.completeTime, 'day')) {
        this.deadlineValidateStatus = 'error'
        this.deadlineHelp = '不能超过任务限定完成时间'
        if (alert) {
          this.$message.error('下一环节截止时间不能超过任务限定完成时间，如需设置，请联系发起人修改任务完成时间', 5)
        }
        return false
      }
      if (deadline.diff(moment(), 'hours') < 1) {
        this.deadlineValidateStatus = 'error'
        this.deadlineHelp = '下一环节截止时间只能在1小时之后'
        return false
      }
      this.deadlineValidateStatus = 'success'
      this.deadlineHelp = ''
      return true
    },
    // 操作类型单选按钮改变时重新设置负责人选择框
    async handleOperationTypeChange (event) {
      this.checkedChargePerson = undefined
      this.branchChargePersons = {}
      // 重新分析分支节点
      await this.analyzeBranchNodes()
    },

    // 处理动态按钮点击
    handleCustomButtonClick (button) {
      try {
        // 执行自定义函数
        if (button.func) {
          const result = executeStrFunctionByContext(this, button.func, [this.details, this.$refs.xAddForm.form, util, runLogic, getConfigByNameAsync])
          if (result) {
            // 如果返回true，执行对应的操作
            if (button.text === '提交') {
              this.nextClick()
            } else if (button.text === '取消') {
              this.$emit('cancel')
            }
          }
        }
      } catch (error) {
        console.error('执行自定义按钮函数失败:', error)
        this.$message.error('执行操作失败')
      }
    },
    // 表单项展示函数--用来渲染历史节点数据时和填写表单显示内容同步
    async showFormItemFunc (func, form) {
      try {
        if (func) {
          // 一般展示项函数中不应该存在setForm函数 先屏蔽this.setForm和this.attr的传递还有在this上下文指向不同可能存在异常 流程表单的展示项函数尽量功能单一。有异常默认进行展示(先兼容到这后续有问题进行调整)
          const obj = executeStrFunctionByContext(this, func, [form, null, null, util, '新增/修改'])
          // 判断是 bool 还是  obj  兼容
          if (typeof obj === 'boolean') {
            return obj
          } else if (obj && typeof obj === 'object') {
            // obj 是一个对象，并且不是数组
            return Object.prototype.hasOwnProperty.call(obj, 'show') ? obj.show : true
          }
        } else {
          return true
        }
      } catch (e) {
        return true
      }
    },
    // 检查按钮是否显示
    checkButtonVisible (button) {
      try {
        if (button.customFunction) {
          return executeStrFunctionByContext(this, button.customFunction, [this.details, this.$refs.xAddForm.form, util, runLogic, getConfigByNameAsync])
        }
        return true
      } catch (error) {
        console.error('执行按钮显示函数失败:', error)
        return false
      }
    },
    formItemEmitFunc (func, data, value) {
      this.$emit('x-form-item-emit-func', func, data, value)
    },
    // 检查条件表达式是否包含WF_RESULT
    checkIfContainsWfResult () {
      const conditionalActions = this.currentDirections.filter(action => action.type === 'conditionalBranch')
      if (conditionalActions.length === 0) return false

      return conditionalActions.some(action => {
        return action.expression && action.expression.includes('WF_RESULT')
      })
    },

    // 分析分支节点并设置选择框
    async analyzeBranchNodes () {
      try {
        // 初始化状态
        this.resetBranchSelection()

        // 获取所有类型的分支动作并缓存
        this.currentBranchActions = this.getBranchActions()

        // 如果没有任何分支，处理普通流程
        if (!this.currentBranchActions.hasAnyBranch) {
          await this.handleNormalFlow()
          return
        }

        // 判断是否需要多分支选择
        this.needMultipleBranchSelection = this.shouldUseMultipleBranchSelection(this.currentBranchActions)

        if (this.needMultipleBranchSelection) {
          // 需要为多个分支预先选择人员
          await this.setupMultipleBranchSelection(this.currentBranchActions.allBranchActions)
        } else {
          // 可以前台实时计算的条件分支
          await this.calculateTargetNodeFromForm(this.currentBranchActions.conditionalActions)
        }
      } catch (error) {
        console.error('分析分支节点失败:', error)
        this.$message.error('工作流分支配置异常，请联系管理员')
        // 降级处理：使用普通流程
        await this.handleNormalFlow()
      }
    },

    // 重置分支选择状态
    resetBranchSelection () {
      this.branchNodes = []
      this.branchChargePersons = {}
      this.needMultipleBranchSelection = false
      this.calculatedTargetNode = null
      this.currentBranchActions = null
    },

    // 获取分支动作分类
    getBranchActions () {
      const conditionalActions = this.currentDirections.filter(action => action.type === 'conditionalBranch')
      const parallelActions = this.currentDirections.filter(action => action.type === 'parallelBranch')
      const allBranchActions = [...conditionalActions, ...parallelActions]

      return {
        conditionalActions,
        parallelActions,
        allBranchActions,
        hasAnyBranch: allBranchActions.length > 0
      }
    },

    // 判断是否应该使用多分支选择模式
    shouldUseMultipleBranchSelection (branchActions) {
      // 情况1: 有并行分支
      if (branchActions.parallelActions.length > 0) {
        return true
      }

      // 情况2: 条件分支包含WF_RESULT（后台结果决定）
      if (branchActions.conditionalActions.length > 0) {
        return this.checkIfContainsWfResult()
      }

      return false
    },

    // 根据表单数据计算目标节点
    async calculateTargetNodeFromForm (conditionalActions = null) {
      if (!conditionalActions) {
        conditionalActions = this.currentDirections.filter(action => action.type === 'conditionalBranch')
      }

      if (conditionalActions.length === 0) {
        // 如果当前节点不是在分支流程中，才清空人员选择
        // 避免在并行分支节点中误清除人员选择框
        const currentStep = this.stepsForChild.find(item => item.id === this.activeStepId)
        const isInBranch = currentStep?.properties?.branchPath

        if (!isInBranch) {
          this.clearPersonSelection()
        }
        return
      }

      try {
        const formData = this.$refs.xAddForm?.form || {}

        // 遍历条件找到匹配的
        for (const action of conditionalActions) {
          if (action.expression) {
            const result = await this.evaluateExpression(action.expression, formData)
            if (result) {
              this.calculatedTargetNode = action.to
              await this.setupSingleTargetPersonSelection(action.to)
              return
            }
          }
        }
        console.log('this.calculatedTargetNode', this.calculatedTargetNode)
        // 如果没有匹配的条件，清空选择
        this.clearPersonSelection()
      } catch (error) {
        console.warn('计算目标节点失败:', error)
        this.clearPersonSelection()
      }
    },

    // 清空人员选择
    clearPersonSelection () {
      this.calculatedTargetNode = null
      this.needSelectPerson = false
      this.chargePersonOptions = []
      this.checkedChargePerson = undefined
    },

    // 设置单个目标节点的人员选择
    async setupSingleTargetPersonSelection (stepId) {
      const stepDefine = this.stepsDefine.find(step => step.id === stepId)

      if (!stepDefine?.properties?.chargePerson?.needSelectPerson) {
        this.needSelectPerson = false
        this.chargePersonOptions = []
        return
      }

      // 设置人员选择
      this.chargePerson = stepDefine.properties.chargePerson
      this.checkedChargePerson = undefined
      this.chargePersonOptions = await this.getChargePersonOptionsForStep(stepId)

      // 如果只有一个选项，自动选中
      if (this.chargePersonOptions.length === 1) {
        this.checkedChargePerson = this.chargePersonOptions[0].value
      }

      this.needSelectPerson = true
    },

    // 表单数据变化处理函数（将通过provide传递给表单组件）
    async handleFormDataChange (formData) {
      // 只有在不是多分支选择模式且当前活动步骤有条件分支动作时才重新计算
      if (!this.needMultipleBranchSelection && this.currentDirections.some(action => action.type === 'conditionalBranch')) {
        await this.calculateTargetNodeFromForm()
      }
    },

    // 表达式评估 - 使用 LogicRunner
    async evaluateExpression (expression, formData) {
      try {
        // 构建参数对象，传递当前表单数据
        const params = {
          WF_FORM: { ...formData }
        }

        // 使用 LogicRunner 执行表达式
        const result = await LogicRunner.runExpression(expression, params)
        return result
      } catch (error) {
        console.warn('表达式评估失败:', expression, error)
        return false
      }
    },

    // 获取指定步骤的人员选项
    async getChargePersonOptionsForStep (stepId) {
      const define = this.stepsDefine.find(item => item.id === stepId)
      if (!define?.properties?.chargePerson) return []

      const chargePerson = define.properties.chargePerson
      this.chargePerson = this.normalizeChargePersonFormat(chargePerson)

      if (!chargePerson.needSelectPerson || !chargePerson.personList) return []

      // 获取所有用户信息
      const allUser = await postByServiceName(commonApi.getAllUserOptionList, {})

      // 根据配置筛选用户
      const options = this.filterUsersByPersonConfig(chargePerson.personList, allUser)

      // 去重处理
      return Array.from(new Map(options.map(item => [item.value, item])).values())
    },

    // 标准化人员配置格式（兼容旧格式）
    normalizeChargePersonFormat (chargePerson) {
      if (chargePerson.role || chargePerson.department) {
        chargePerson.needSelectPerson = true
        chargePerson.personList = [{
          type: chargePerson.role ? 'role' : 'department',
          name: chargePerson.role || chargePerson.department
        }]
      }
      return chargePerson
    },

    // 根据人员配置筛选用户
    filterUsersByPersonConfig (personList, allUsers) {
      return personList.reduce((acc, personItem) => {
        let filteredUsers = []

        if (personItem.type === 'role') {
          filteredUsers = allUsers.filter(user =>
            user.rolestr && user.rolestr.split(',').includes(personItem.name)
          ).map(user => ({
            label: user.label,
            value: user.value
          }))
        } else if (personItem.type === 'department') {
          filteredUsers = allUsers.filter(user =>
            user.depname === personItem.name
          ).map(user => ({
            label: user.label,
            value: user.value
          }))
        }

        return [...acc, ...filteredUsers]
      }, [])
    },

    // 设置多分支人员选择
    async setupMultipleBranchSelection (branchActions) {
      this.branchNodes = []
      this.branchChargePersons = {}
      let hasPersonSelection = false

      for (const action of branchActions) {
        const stepDefine = this.stepsDefine.find(step => step.id === action.to)
        const chargePerson = stepDefine?.properties?.chargePerson

        // 所有分支节点都加入branchNodes，保持数据结构完整
        const nodeData = {
          stepId: action.to,
          stepName: this.getStepNameByStepId(action.to),
          chargePerson: chargePerson,
          needSelectPerson: chargePerson?.needSelectPerson || false,
          chargePersonOptions: []
        }

        if (chargePerson?.needSelectPerson) {
          // 需要选择人员的分支
          const chargePersonOptions = await this.getChargePersonOptionsForStep(action.to)
          nodeData.chargePersonOptions = chargePersonOptions

          // 初始化选择值
          this.branchChargePersons[action.to] = undefined
          hasPersonSelection = true
        } else {
          // 不需要选择人员的分支，直接存储配置
          this.branchChargePersons[action.to] = chargePerson
        }

        this.branchNodes.push(nodeData)
      }

      // 只有当存在需要选择人员的分支时才显示选择区域
      this.needSelectPerson = hasPersonSelection
    },

    // 处理普通单线流程（没有分支的情况）
    async handleNormalFlow () {
      const targetStepId = this.operationType === 'skip' ? this.stepNextBtnTo : this.nextBtnTo

      this.calculatedTargetNode = targetStepId
      const stepDefine = this.stepsDefine.find(step => step.id === targetStepId)

      if (!stepDefine) {
        console.warn('未找到目标步骤定义:', targetStepId)
        this.clearPersonSelection()
        return
      }

      const defineProperties = stepDefine.properties
      this.chargePerson = defineProperties?.chargePerson

      // 兼容旧格式
      if (defineProperties.chargePerson) {
        defineProperties.chargePerson = this.normalizeChargePersonFormat(defineProperties.chargePerson)
      }

      if (defineProperties?.chargePerson?.needSelectPerson) {
        await this.setupSingleTargetPersonSelection(targetStepId)
        // 确保 branchChargePersons 中有该节点的数据结构
        this.branchChargePersons[targetStepId] = {
          handler: '',
          handlerId: undefined,
          ...defineProperties.chargePerson
        }
      } else {
        // 不需要选择人员的情况，直接存储配置
        this.branchChargePersons[targetStepId] = defineProperties?.chargePerson || {}
        this.needSelectPerson = false
        this.chargePersonOptions = []
      }
    }
  },
  watch: {}
}
</script>
<style lang="less" scoped>
.complete-data-title {
  margin-top: 8px;
  margin-bottom: 8px;
}

:deep(.ant-result) {
  padding: 0;
}

.descriptionPreviewItem {
  margin-bottom: 22px;

  :deep(.ant-descriptions-view) {
    overflow: visible;
  }
}

.allWidth {
  :deep(.ant-descriptions-item-content) {
    width: 100%;
  }
}

.descriptionTitle {
  position: relative;
  padding-left: 12px;

  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background-color: @primary-color;
    border-radius: 2px;
  }
}
</style>
