<script setup lang="ts">
import BeautifulLoading from '@af-mobile-client-vue3/components/core/BeautifulLoading/index.vue'

import FileItem from '@af-mobile-client-vue3/components/data/step/file-item.vue'
import HistoryFormData from '@af-mobile-client-vue3/components/data/step/history-form-data.vue'

import PersonSelect from '@af-mobile-client-vue3/components/data/step/person-select.vue'

import XForm from '@af-mobile-client-vue3/components/data/XForm/index.vue'

import XFormItem from '@af-mobile-client-vue3/components/data/XFormItem/index.vue'
import JSONObject from '@af-mobile-client-vue3/expression/instances/JSONObject'
import LogicRunner from '@af-mobile-client-vue3/logic/LogicRunner'
import { getConfigByName, runLogic } from '@af-mobile-client-vue3/services/api/common'
import useStepStore from '@af-mobile-client-vue3/stores/modules/step'
import useUserStore from '@af-mobile-client-vue3/stores/modules/user'
import * as util from '@af-mobile-client-vue3/utils/common'

import { getDictItemByValue } from '@af-mobile-client-vue3/utils/dictUtil'
import { executeStrFunctionByContext } from '@af-mobile-client-vue3/utils/runEvalFunction'

import { formatDate } from '@vueuse/core'
import {
  closeDialog,
  showConfirmDialog,
  showToast,
  ActionSheet as VanActionSheet,
  Button as VanButton,
  Cell as VanCell,
  CellGroup as VanCellGroup,
  Empty as VanEmpty,
  Field as VanField,
  FloatingBubble as VanFloatingBubble,
  Icon as VanIcon,
} from 'vant'
import { computed, getCurrentInstance, onActivated, onBeforeMount, provide, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

defineOptions({ name: 'StepDetailBase' })

const props = withDefaults(defineProps<Props>(), {
  workflowId: undefined,
  stepId: undefined,
  serviceName: 'af-apply',
  onSelectAddress: undefined,
  onFormFunc: undefined,
})

interface Props {
  workflowId?: string
  stepId?: string
  serviceName?: string
  // 业务相关的处理函数
  onSelectAddress?: () => void
  onFormFunc?: (func: string) => void
}

const router = useRouter()
const route = useRoute()
const workflowId: string = props.workflowId || (route.query.workflowId as string)
const stepId: string = props.stepId || (route.query.stepId as string)

const userStore = useUserStore()

const stepStore = useStepStore()

const serviceName = ref(props.serviceName)

const isLoading = ref(false)
const isFinish = ref(false)
const isError = ref(false)
// 错误信息
const errorMsg = ref('')
// 错误图片类型
const errorImage = ref('default')
// 录入表单实例
const xAddForm = ref<any>(undefined)
// 展示类型 0 表单 1 只读资源
const showType = ref(0)
// 显示供用户填写的当前步骤表单
const showForm = ref(false)
// 当前步骤完成状态
const stepDone = ref(false)
// 工作流详情数据
const workflowDetailData = ref(undefined)
// 所有步骤定义
const stepDefines = ref([])
// 所有流程元数据
const stepMetaDefines = ref([])
// 当前步骤信息
const currentStep = ref(undefined)
// 流程表单定义
const stepFormDefine = ref(undefined)
const historyFormCompletedDataPreview = ref(undefined)
// 流程表单数据
const stepFormData = ref(undefined)
// 流程附件数据
const stepFilesData = ref(undefined)
// 流程图片数据
const stepImageData = ref(undefined)
// 所有节点联通数据
const directions = ref([])
// 当前步骤能通向的后续步骤
const currentDirections = ref([])
// 当前步骤是否是最后一步
const isLastStep = ref(false)
// 是否显示下一步按钮
const isShowNextStepBtn = ref(false)
// 是否显示回退按钮
const isShowPrevStepBtn = ref(false)
// 是否显示跳过按钮
const isShowSkipStepBtn = ref(false)
// 下一步按钮目标
const nextStepBtnToObj = ref(undefined)
// 回退按钮目标
const prevStepBtnToObj = ref(undefined)
// 跳过按钮目标
const skipStepBtnToObj = ref(undefined)
// 下一步按钮提示
const nextBtnPrompt = ref('')
// 回退按钮提示
const prevBtnPrompt = ref('')
// 跳过按钮提示
const skipBtnPrompt = ref('')
// 操作类型，提交到下一步或跳过
const operationType = ref('submit')
// 是否需要选择人员
const isNeedSelectPerson = ref(false)
// 已选择的下一环节处理人
const checkedNextStepPerson = ref(undefined)
// 已选择的下一环节处理人名称
const checkedNextStepPersonName = ref(undefined)
// 下一环节处理人选项列表
const nextStepPersonOptions = ref([])
// 下一环节人员信息
const nextStepPersonInfo = ref(undefined)
// 下一环节截止时间
const deadline = ref(undefined)
// 备注表单内容
const noteContent = ref('')
// 退回原因内容
const backNoteContent = ref('')
// 用于将已有数据，填回x-add表单中
const formCompletedData = ref({})
// 用于展示提交的数据
const formCompletedDataPreview = ref(undefined)
// 展示更多按钮下拉菜单
const showMoreMenu = ref(false)
// 所有操作按钮
const allButtons = ref([])
// 展示工具下拉菜单
const showToolsMenu = ref(false)
// 浮动按钮工具列表
const toolActions = ref([])
/** 分支节点相关数据 */
// 需要选择人员的分支节点列表
const branchNodes = ref([])
// 分支节点人员选择 格式：{stepId: personId}
const branchChargePersons = ref({})
// 是否需要为多个分支节点预先选择人员（包含WF_RESULT的条件分支或并行分支）
const needMultipleBranchSelection = ref(false)
// 前台计算出的目标节点
const calculatedTargetNode = ref(undefined)
// 缓存当前的分支动作，避免重复调用
const currentBranchActions = ref(undefined)
// xAddForm 默认值初始化
const xAddFormData = ref({})
// 是否展示Dialog
const dialogVisible = ref(false)
// Dialog标题
const dialogTitle = ref('')
// 当前环节 小工具中工具名称
const mobileToolNames = ref('')

// 是否可以提交
const canSubmit = computed(() => {
  // 对于超级管理员直接认为可以提交
  if (userStore.getUserInfo().username === '1') {
    return true
  }
  if (!currentStep.value) {
    return false
  }
  // 已完成节点，检查是否展示表单数据
  if (currentStep.value.status !== 1 || workflowDetailData.value?.f_state === 1) {
    // 历史节点为当前登录人操作则不做查看数据权限校验
    if (currentStep.value.handler === userStore.getUserInfo().name) {
      return true
    }
    const viewers = currentStep.value.properties?.otherProperty?.viewers ?? []
    if (viewers.length > 0) {
      // 使用some方法判断当前人员是否满足任一条件
      return viewers.some((item) => {
        if (item.type === 'role') {
          // 检查rolestr是否存在并包含指定角色
          return userStore.getUserInfo().rolestr && userStore.getUserInfo().rolestr.split(',').includes(item.name)
        }
        if (item.type === 'department') {
          // 检查depname是否存在并包含指定部门
          return userStore.getUserInfo().deps && userStore.getUserInfo().deps?.includes(item.name)
        }
        return false
      })
    }
    else {
      return true
    }
  }
  else {
    // 检查角色和部门权限
    if (currentStep.value.properties && currentStep.value.properties.chargePerson) {
      // 如果当前节点的负责人选项中有设置选择人员 当前节点就只能由上一步设置的负责人操作
      if (currentStep.value.properties.chargePerson.needSelectPerson) {
        return currentStep.value.handler === userStore.getUserInfo().name
      }
      if (currentStep.value.properties.chargePerson.personList && currentStep.value.properties.chargePerson.personList.length > 0) {
        // 使用some方法判断当前人员是否满足任一条件
        return currentStep.value.properties.chargePerson.personList.some((item) => {
          if (item.type === 'role') {
            // 检查rolestr是否存在并包含指定角色
            return userStore.getUserInfo().rolestr && userStore.getUserInfo().rolestr.split(',').includes(item.name)
          }
          if (item.type === 'department') {
            // 检查parentname是否存在并包含指定部门
            return userStore.getUserInfo().parentname && userStore.getUserInfo().parentname.includes(item.name)
          }
          return false
        })
      }
    }

    // 检查handler是否包含当前用户
    if (currentStep.value && currentStep.value.handler) {
      return currentStep.value.handler.includes(userStore.getUserInfo().name)
    }
  }
  return false
})

// 判断当前节点的分支状态
const isBranchLastNode = computed(() => {
  // 默认返回值
  const defaultResult = {
    isBranchNode: false, // 是否为分支流程中的节点
    isLastBranch: false, // 是否为最后一个未完成的分支（需要选择下一环节人员）
  }

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

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

  // 如果下一个节点的flowRole不是branchExit，说明不是分支的最后一个节点
  if (!nextStep || nextStep.properties?.flowRole !== 'branchExit') {
    return defaultResult
  }

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

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

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

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

  return {
    isBranchNode: true, // 当前节点是分支流程中的节点
    isLastBranch: allOtherBranchesCompleted, // 只有当其他所有分支都已完成时，当前分支才是最后一个
  }
})

// 实际展示的按钮
const displayedButtons = computed(() => {
  if (allButtons.value.length <= 3) {
    return allButtons.value
  }

  // 当按钮超过3个时，显示前2个和一个"更多"按钮
  const buttons = [...allButtons.value.slice(0, 2)]
  buttons.push({
    text: '更多',
    isMoreButton: true,
    action: 'showMore',
  })
  return buttons
})

// 扩展按钮（从第3个开始）
const actionSheetActions = computed(() => {
  if (allButtons.value.length <= 3)
    return []
  return allButtons.value.slice(2).map((button) => {
    if (button.show === true) {
      return {
        name: button.text,
        action: button.action,
        func: button.func,
      }
    }
    else {
      return undefined
    }
  }).filter(item => item !== undefined)
})

// 初始化组件
async function initComponent() {
  isLoading.value = true;
  // 设置标题
  (window as any).microApp?.dispatch({ title: route.query.title })
  // 获取流程定义集合和当前流程信息
  const defineData: any = await runLogic('getStepNoteAndHandler', {
    workflowId,
  }, serviceName.value)
  const stepIdValue = Number.parseInt(stepId as string)
  stepDefines.value = defineData
  // 当前节点状态信息
  const currentStepState: any = await runLogic('getWorkFlowCurrentSubState', {
    workflowId,
  }, serviceName.value)
  // 当前节点定义信息
  const currentStepDefine: any = defineData.filter((item: any) => item.id === stepIdValue)[0]
  const currentStepData: any = {}
  Object.assign(currentStepData, currentStepDefine)
  Object.assign(currentStepData, currentStepState)
  currentStep.value = currentStepData
  mobileToolNames.value = currentStep.value.properties?.otherProperty?.mobileToolsRoutes?.map(d => d.name).join('、') ?? ''
  if (!currentStep.value) {
    errorMsg.value = '工作流步骤不存在'
    errorImage.value = 'default'
    isError.value = true
    return
  }
  if (!canSubmit.value) {
    errorMsg.value = '您没有访问该步骤的权限'
    errorImage.value = 'error'
    isError.value = true
    return
  }
  // 获取到当前步骤后复制下一步时间
  deadline.value = getDefaultDeadline(currentStep.value.properties?.otherProperty?.nextNodeInterval)
  // 获取当前步骤节点，连通的节点
  await getDirection()
  if (!currentStep.value.note) {
    currentStep.value.note = '无'
  }
  // 获取工单基本信息
  await getBaseInfo()
  if (currentStep.value.status !== 1 || workflowDetailData.value?.f_state === 1) {
    // 已完成流程获取流程表单数据
    const formData: any = await runLogic('getWorkFlowCompletedStepData', {
      workflowId,
      stepId,
    }, serviceName.value)
    stepFormData.value = getFormData(formData.data)
    stepFilesData.value = formData.files
    stepImageData.value = formData.images
    showType.value = 1
  }
  else {
    stepFormDefine.value = currentStep.value.properties.form
    addActionButtons()
    appendCustomizeButtons()
    showType.value = 0
  }
  // 当前环节配置的历史表单数据展示配置
  await buildHistoryFormCompletedData()
  isLoading.value = false
  isFinish.value = true
}
async function buildHistoryFormCompletedData() {
  historyFormCompletedDataPreview.value = null
  const otherProperty = currentStep.value?.properties?.otherProperty
  const historyFormDataConfig = otherProperty?.historyFormData

  if (!Array.isArray(historyFormDataConfig))
    return

  // ===== 预处理 =====
  const stepIdByName = new Map(
    stepDefines.value.map(step => [step.name, step.id]),
  )

  const stepFormJsonByStepId = new Map(
    stepDefines.value.map(step => [
      step.id,
      step?.properties?.form?.formJson,
    ]),
  )

  // ===== 收集需要查询的 stepId =====
  const stepIdSet = new Set()

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

  const stepIdS = Array.from(stepIdSet)
  if (stepIdS.length === 0)
    return

  // ===== 请求所有步骤数据 =====
  const allStepData = await runLogic('geWorkFlowCompletedStepDataBySteps', {
    workflowId,
    stepIdS,
  }, serviceName.value)

  // ===== 组装数据 =====
  const historyFormData = []
  const stepAttachmentsMap = new Map()

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

    const targetStepId = Number.parseInt(stepId)

    const stepFormJson = stepFormJsonByStepId.get(targetStepId)
    if (!Array.isArray(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
        : []

      continue
    }

    // ===== 普通字段 =====
    const model = historyFormConfig.formLabel

    const value = stepDataRaw.data?.[model]
    if (value === undefined || value === null)
      continue

    historyFormData.push({
      label: historyFormConfig.displayLabel,
      value,
    })
  }

  // ===== 汇总结果 =====
  historyFormCompletedDataPreview.value = {
    data: historyFormData,
    stepAttachments: Array.from(stepAttachmentsMap.values()),
  }
}

// 获取默认截止时间
function 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')
}

// 获取表单数据
function getFormData(stepFormData: any) {
  const formDataArr = []
  const formConfig = currentStep.value?.properties?.form
  const isKeyHandle = formConfig?.isKeyHandle || false
  const formJson = formConfig?.formJson || []

  for (const stepDefine of formJson) {
    // 如果是特殊函数展示的字段，跳过
    if (stepDefine.showFormItemFunc)
      continue

    const key = getRealKey(stepDefine.model, isKeyHandle)
    if (!(key in stepFormData) || ['FilesId', 'Images'].includes(key) || ['image', 'signature'].includes(stepDefine.type))
      continue

    const value = stepFormData[key]
    const item = { label: stepDefine.name, value }

    // 如果是需要字典转换的 select
    if (stepDefine.type === 'select' && stepDefine.keyName?.includes('config@')) {
      const dictKey = stepDefine.keyName.split('@')[1]
      convertDictValue(dictKey, value, (label) => {
        item.value = label
      })
    }

    formDataArr.push(item)
  }

  return formDataArr.length > 0 ? formDataArr : null
}

function getRealKey(key: string, isHandleFormKey: boolean) {
  if (!key)
    return ''
  if (key === 'selected_id')
    return key
  return isHandleFormKey ? key.split('_').slice(1).join('_') : key
}

// 获取当前步骤节点，连通的节点
async function getDirection() {
  // 获取流程定义
  const res: any = await runLogic('getWorkFlowDefine', {
    id: workflowId,
  }, serviceName.value)
  directions.value = []
  stepMetaDefines.value = res.steps
  await resolveDirections()
  appendToolsViewOptions()
}

// 追加自定义按钮
function appendCustomizeButtons() {
  // 获取当前步骤的按钮组配置
  if (currentStep.value.properties?.buttonGroup?.actionArr) {
    for (const item of currentStep.value.properties.buttonGroup.actionArr) {
      allButtons.value.push({
        text: item.text,
        isMoreButton: false,
        action: 'other',
        func: item.func,
        show: checkButtonVisible(item),
      })
    }
  }
}

// 追加浮动按钮的工具选项
function appendToolsViewOptions() {
  // 获取当前步骤的浮动按钮工具集配置
  toolActions.value = []
  if (currentStep.value.properties?.otherProperty?.mobileToolsRoutes) {
    for (const item of currentStep.value.properties.otherProperty.mobileToolsRoutes) {
      toolActions.value.push({
        name: item.name,
        value: item.value,
        type: 'tools',
        func: item.func,
      })
    }
  }
  toolActions.value.push({
    name: '流程查看',
    value: 'applyDetail',
    type: 'applyDetail',
  })
  toolActions.value.push({
    name: '返回首页',
    value: 'home',
    type: 'backHome',
  })
}

// 浮动按钮点击操作
function handleToolsPopoverClick() {
  showToolsMenu.value = true
}

// 分析当前节点，能通向的节点
async function resolveDirections() {
  if (currentStep.value?.properties?.actions) {
    currentDirections.value = currentStep.value.properties.actions
  }
  // 判断是否是最后ige节点
  isLastStep.value = (currentStep.value?.properties?.actions || []).filter((item) => {
    return item.type !== 'back'
  }).length === 0

  // 处理跳转按钮
  workflowControl()

  if (!isLastStep.value) {
    // 分析分支节点并设置智能人员选择
    await analyzeBranchNodes()
  }
}

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

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

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

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

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

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

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

  for (const action of branchActions) {
    const stepDefine = stepMetaDefines.value.find(step => step.id === action.to)
    const stepPerson = stepDefine?.properties?.chargePerson

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

    if (stepPerson?.needSelectPerson) {
      // 需要选择人员的分支
      nodeData.chargePersonOptions = await getStepPersonOptionsForStep(action.to)

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

    branchNodes.value.push(nodeData)
  }

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

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

  if (conditionalActions.length === 0) {
    // 如果当前节点不是在分支流程中，才清空人员选择
    // 避免在并行分支节点中误清除人员选择框
    const isInBranch = currentStep.value?.properties?.branchPath
    if (!isInBranch) {
      clearPersonSelection()
    }
    return
  }

  try {
    const formData = xAddForm.value.form || {}

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

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

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

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

  // 情况2: 条件分支包含WF_RESULT（后台结果决定）
  if (branchActions.conditionalActions.length > 0) {
    const conditionalActions = currentDirections.value.filter(action => action.type === 'conditionalBranch')
    if (conditionalActions.length === 0)
      return false

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

  return false
}

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

  calculatedTargetNode.value = targetStepId
  const stepDefine = stepMetaDefines.value.find(step => step.id === targetStepId)

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

  const defineProperties = stepDefine.properties
  nextStepPersonInfo.value = defineProperties?.chargePerson

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

  if (defineProperties?.chargePerson?.needSelectPerson) {
    await setupSingleTargetPersonSelection(targetStepId)
    // 确保 branchChargePersons 中有该节点的数据结构
    branchChargePersons.value[targetStepId] = {
      handler: '',
      handlerId: undefined,
      ...defineProperties.chargePerson,
    }
  }
  else {
    // 不需要选择人员的情况，直接存储配置
    branchChargePersons.value[targetStepId] = defineProperties?.chargePerson || {}
    isNeedSelectPerson.value = false
    nextStepPersonOptions.value = []
  }
}

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

  if (!stepDefine?.properties?.chargePerson?.needSelectPerson) {
    isNeedSelectPerson.value = false
    nextStepPersonOptions.value = []
    return
  }

  // 设置人员选择
  nextStepPersonInfo.value = stepDefine.properties.chargePerson
  checkedNextStepPerson.value = undefined
  checkedNextStepPersonName.value = undefined
  nextStepPersonOptions.value = await getStepPersonOptionsForStep(stepId)
  // 如果只有一个选项，自动选中
  if (nextStepPersonOptions.value.length === 1) {
    checkedNextStepPerson.value = nextStepPersonOptions.value[0].value
    checkedNextStepPersonName.value = nextStepPersonOptions.value[0].label
  }

  isNeedSelectPerson.value = true
}

// 获取下一步操作人的人员列表
async function getStepPersonOptionsForStep(stepId) {
  const define = stepMetaDefines.value.find(item => item.id === stepId)
  if (!define?.properties?.chargePerson)
    return []

  const stepPerson = define.properties.chargePerson
  nextStepPersonInfo.value = normalizeChargePersonFormat(stepPerson)

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

  // 获取所有用户信息
  const allUser = await runLogic('getAllUserOptionList', {}, 'af-system')

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

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

// 根据人员配置筛选用户
function 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]
  }, [])
}

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

// 清空人员选择
function clearPersonSelection() {
  calculatedTargetNode.value = undefined
  isNeedSelectPerson.value = false
  nextStepPersonOptions.value = []
  checkedNextStepPerson.value = undefined
  checkedNextStepPersonName.value = undefined
}

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

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

// 根据步骤id获取步骤名称
function getStepNameByStepId(stepId) {
  return stepMetaDefines.value.find(item => item.id === stepId)?.name
}

// 根据当前节点，判断之后流程，以及按钮的显示
function workflowControl() {
  // 重置所有控制数据为默认值，避免之前状态的影响
  isShowNextStepBtn.value = false
  isShowPrevStepBtn.value = false
  isShowSkipStepBtn.value = false
  nextStepBtnToObj.value = undefined
  prevStepBtnToObj.value = undefined
  skipStepBtnToObj.value = undefined
  nextBtnPrompt.value = ''
  prevBtnPrompt.value = ''
  skipBtnPrompt.value = ''

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

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

  // 处理跳过按钮
  if (skipActions.length > 0) {
    isShowSkipStepBtn.value = true
    skipStepBtnToObj.value = skipActions[0].to
    if (skipActions.length === 1) {
      skipBtnPrompt.value = `跳至${getStepNameByStepId(skipActions[0].to)}`
    }
    else {
      const targetSteps = skipActions.map(item => getStepNameByStepId(item.to)).join(' , ')
      skipBtnPrompt.value = `跳至${targetSteps}`
    }
  }

  // 处理退回按钮
  if (backActions.length > 0) {
    const backAction = backActions[0] // 通常只有一个back action
    for (let i = currentStep.value.id - 1; i > 0; i--) {
      if (backAction.to >= i && stepDefines.value.find(item => item.id === i)?.handler) {
        prevStepBtnToObj.value = i
        prevBtnPrompt.value = `退至${getStepNameByStepId(i)}`
        isShowPrevStepBtn.value = true
        break
      }
    }
  }
}

// 清理数据
function clearData() {
  checkedNextStepPerson.value = undefined
  checkedNextStepPersonName.value = undefined
  directions.value = []
  currentDirections.value = []
  isShowNextStepBtn.value = false
  isShowSkipStepBtn.value = false
  isShowPrevStepBtn.value = false
  stepDone.value = false
  formCompletedData.value = {}
  formCompletedDataPreview.value = undefined
  operationType.value = 'submit'

  // 清理分支节点相关数据
  branchNodes.value = []
  branchChargePersons.value = {}
  needMultipleBranchSelection.value = false
  calculatedTargetNode.value = undefined
  currentBranchActions.value = undefined

  // 清理操作按钮
  allButtons.value = []
}

// 分离出字典转换逻辑
function convertDictValue(dictKey: string, value: string, callback: Function) {
  getDictItemByValue(dictKey, serviceName.value, value, (dictItem: any) => {
    if (dictItem) {
      callback(dictItem.label)
    }
  })
}

// 获取工单基础信息
async function getBaseInfo() {
  const res: any = await runLogic('getWorkFlowBasicInfo', {
    workflowId,
  }, serviceName.value)
  // 主动传入得优先级较高
  if (currentStep.value.id) {
    res.f_sub_state = stepDefines.value.find(item => item.id === currentStep.value.id)?.name
  }
  else {
    res.f_sub_state = stepDefines.value.find(item => item.id === res.f_step_id)?.name
  }
  workflowDetailData.value = res
}

// 检查按钮是否显示
function checkButtonVisible(button) {
  try {
    if (button.customFunction) {
      getBaseInfo()
      return executeStrFunctionByContext(getCurrentInstance(), button.customFunction, [workflowDetailData.value, xAddForm.value, util, runLogic, getConfigByName])
    }
    return true
  }
  catch (error) {
    console.error('执行按钮显示函数失败:', error)
    return false
  }
}

// 处理动态按钮点击
function handleCustomButtonClick(button) {
  try {
    // 执行自定义函数
    if (button.func) {
      getBaseInfo()
      const result = executeStrFunctionByContext(getCurrentInstance(), button.func, [workflowDetailData.value, xAddForm.value, util, runLogic, getConfigByName, 'mobile', userStore.getUserInfo(), showToast, showConfirmDialog])
      if (result) {
        // 如果返回true，执行对应的操作
        if (button.text === '提交') {
          handleButtonClick({
            action: 'submit',
          })
        }
      }
    }
  }
  catch (error) {
    console.error('执行自定义按钮函数失败:', error)
    showToast('执行操作失败')
  }
}

// 表单提交的回调
async function submitForm(obj) {
  const formData = obj.realForm
  const time = formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
  return runLogic('saveWorkFlowStepFormData', {
    workflowId,
    stepId: currentStep.value.id,
    form: formData,
    data: time,
    handler: userStore.getUserInfo().name,
    note: noteContent.value.trim(),
  }, serviceName.value).then(() => {
    noteContent.value = ''
    showForm.value = false
    stepDone.value = true
  })
}

// 保存工作流日志
function saveWorkflowLog(operation, desc, extra) {
  runLogic('saveWorkFlowLog', {
    workflowId,
    operation,
    desc,
    operator: userStore.getUserInfo().name,
    notes: '',
    setHandler: '',
    setDeadline: '',
    ...extra,
  }, serviceName.value)
}

// 业务提交统一处理
async function handleButtonClick(button: any) {
  if (button.action === 'showMore') {
    showMoreMenu.value = true
    return
  }

  if ((button.action === 'submit' || button.action === 'skip' || button.action === 'done')) {
    await xAddForm.value.validate()
  }

  if (button.action === 'submit' || button.action === 'skip' || button.action === 'back') {
    operationType.value = button.action
    // 重新分析分支节点
    checkedNextStepPerson.value = undefined
    checkedNextStepPersonName.value = undefined
    branchChargePersons.value = {}
    await analyzeBranchNodes()
  }

  // 根据按钮类型执行不同操作
  switch (button.action) {
    case 'submit': {
      dialogTitle.value = '提交环节'
      dialogVisible.value = true
      break
    }
    case 'skip': {
      dialogTitle.value = '跳过环节'
      dialogVisible.value = true
      break
    }
    case 'done': {
      await doneClick()
      break
    }
    case 'back': {
      dialogTitle.value = `${prevBtnPrompt.value}环节`
      dialogVisible.value = true
      break
    }
    case 'other': {
      handleCustomButtonClick(button)
      break
    }
  }
}

// 完工按钮
async function doneClick() {
  xAddForm.value.asyncSubmit().then((res) => {
    submitForm(res).then((_) => {
      runLogic('afterWorkFlowFinalStepSubmit', {
        workflowId,
        stepId: currentStep.value.id,
        submitUser: userStore.getUserInfo().name,
        submitUserId: userStore.getUserInfo().id,
      }, serviceName.value).then((_res) => {
        saveWorkflowLog('确认完工', `最后一步: ${getStepNameByStepId(currentStep.value.id)}`, { notes: noteContent.value.trim() })
        showToast('已完工')
        clearData()
        back()
      }, () => {
        showToast('提交失败！')
      })
    })
  }).catch((err) => {
    if (err && err.message === 'Form validation failed') {
      showToast('请检查表单必填项！')
    }
    else {
      // 对于其他错误，继续向上抛出
      throw err
    }
  })
}

function back() {
  history.back()
}

// 获取提交步骤的额外数据
function getApplyStepExtraData(stepId) {
  // 验证人员选择 - 只有在需要显示人员选择器的情况下才验证
  // 判断条件与模板中的 WorkflowPersonSelector 显示条件保持一致
  const shouldShowPersonSelector = !isBranchLastNode.value.isBranchNode || isBranchLastNode.value.isLastBranch

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

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

  return {
    form: xAddForm.value.getFormData(),
    workflowId,
    activeStepId: currentStep.value.id,
    stepId, // 当前步骤ID
    stepIds, // 目标步骤IDs数组（统一格式）
    name: getStepNameByStepId(stepId),
    handler: getStepHandler(),
    handlerId: checkedNextStepPerson.value,
    needSelectPerson: isNeedSelectPerson.value,
    personList: nextStepPersonInfo.value?.personList || [],
    deadline: deadline.value,
    submitUser: userStore.getUserInfo().name,
    submitUserId: userStore.getUserInfo().id,
    branchChargePersons: branchChargePersons.value,
  }
}

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

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

      if (node.needSelectPerson && branchData) {
        // 需要选择人员的分支：显示选中的人员
        const personName = 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 (checkedNextStepPerson.value) {
      // 使用 value 找到对应的 label
      stepHandler = nextStepPersonOptions.value.find(item => item.value === checkedNextStepPerson.value)?.label
    }
    else if (nextStepPersonInfo.value && nextStepPersonInfo.value.personList && nextStepPersonInfo.value.personList.length > 0) {
      stepHandler = nextStepPersonInfo.value.personList.map(item => item.name).join(',')
    }
  }

  return stepHandler
}

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

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

  const person = node.chargePersonOptions.find(p => p.value === personId)
  return person ? person.label : ''
}

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

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

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

function showConfirmDialogPromise(title: string, message: string): Promise<void> {
  if (mobileToolNames.value.length > 0) {
    const mobileToolMessage = `注意：当前环节工具箱中支持添加【${mobileToolNames.value}】`
    message = `${message}<br><span style=\"color:#1677ff;\">${mobileToolMessage}</span>`
  }
  return new Promise((resolve, reject) => {
    showConfirmDialog({
      title,
      message,
      allowHtml: true,
    })
      .then(() => resolve())
      .catch(() => {
        closeDialog()
        // eslint-disable-next-line prefer-promise-reject-errors
        reject()
      })
  })
}

async function dialogClick() {
  switch (operationType.value) {
    case 'back':
      await backStep()
      break
    case 'skip':
      await skipStep()
      break
    case 'submit':
      await submitStep()
      break
  }
}

async function backStep() {
  const notes = backNoteContent.value.trim()
  if (!notes) {
    showToast('退回请在备注中填写理由')
    return
  }
  return runLogic('updateWorkFlowState', {
    stepId: prevStepBtnToObj.value,
    workflowId,
    type: 'back',
  }, serviceName.value)
    .then(
      () => {
        saveWorkflowLog('退回', generateStepChangeText(currentStep.value.id, prevStepBtnToObj.value), { notes })
        showToast('退回成功')
        clearData()
        back()
      },
      (err) => {
        showToast('退回失败！')
        console.log(err)
      },
    )
}

async function submitStep() {
  // 检查是否为非最后分支节点
  const branchStatus = isBranchLastNode.value
  const isWaitingBranch = branchStatus.isBranchNode && !branchStatus.isLastBranch

  const extraData = getApplyStepExtraData(nextStepBtnToObj.value)
  if (!extraData) {
    return
  }

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

  await showConfirmDialogPromise('提交确认', confirmContent)

  xAddForm.value.asyncSubmit().then((res) => {
    submitForm(res).then((_) => {
      extraData.form = res.realForm
      runLogic('submitToNextStep', extraData, serviceName.value)
        .then(
          () => {
            let successMessage = '提交成功'

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

              const extra = {
                setHandler: getStepHandler(),
                setDeadline: deadline.value,
                notes: noteContent.value.trim(),
              }
              saveWorkflowLog(operation, generateBranchStepChangeText(currentStep.value.id), extra)
            }
            else {
              successMessage = '分支完成，等待其他分支完成后自动汇合'
            }
            showToast(successMessage)
            clearData()
            back()
          },
          (err) => {
            showToast('提交失败！')
            console.log(err)
          },
        )
    })
  }).catch((err) => {
    if (err && err.message === 'Form validation failed') {
      showToast('请检查表单必填项！')
    }
    else {
      // 对于其他错误，继续向上抛出
      throw err
    }
  })
}

async function skipStep() {
  const extraData = getApplyStepExtraData(skipStepBtnToObj.value)
  if (!extraData) {
    return
  }
  // 跳过前确认
  await showConfirmDialogPromise('跳过确认', '确定跳过当前步骤吗？跳过后将进入下一环节。')
  xAddForm.value.asyncSubmit().then((res) => {
    submitForm(res).then((_) => {
      runLogic('submitToNextStep', extraData, serviceName.value)
        .then(
          () => {
            const extra = {
              setHandler: getStepHandler(),
              setDeadline: deadline.value,
              notes: noteContent.value.trim(),
            }
            saveWorkflowLog('跳过', generateBranchStepChangeText(currentStep.value.id), extra)
            showToast('提交成功')
            clearData()
            back()
          },
          (err) => {
            showToast('提交失败！')
            console.log(err)
          },
        )
    })
  }).catch((err) => {
    if (err && err.message === 'Form validation failed') {
      showToast('请检查表单必填项！')
    }
    else {
      // 对于其他错误，继续向上抛出
      throw err
    }
  })
}

// 增加操作按钮组
function addActionButtons() {
  allButtons.value = []
  // 根据按钮类型执行不同操作
  if (operationType.value === 'submit' && !isLastStep.value) {
    allButtons.value.push({
      text: '提交申请',
      icon: 'checked',
      isMoreButton: false,
      action: 'submit',
      type: 'primary',
      class: 'submit-btn',
      show: true,
    })
  }
  if (isShowSkipStepBtn.value && !isLastStep.value) {
    allButtons.value.push({
      text: `${skipBtnPrompt.value}`,
      icon: 'share',
      isMoreButton: false,
      action: 'skip',
      class: 'skip-btn',
      show: true,
    })
  }
  if (isLastStep.value) {
    allButtons.value.push({
      text: '确认完成',
      isMoreButton: false,
      action: 'done',
      type: 'primary',
      show: true,
    })
  }
  if (canSubmit.value && isShowPrevStepBtn.value && workflowDetailData.value?.f_state !== 1) {
    allButtons.value.push({
      text: `${prevBtnPrompt.value}`,
      icon: 'edit',
      isMoreButton: false,
      action: 'back',
      type: 'warning',
      class: 'prev-btn',
      show: true,
    })
  }
}

// 扩展按钮ActionSheet 选项选择
async function onActionSheetSelect(item: any) {
  showMoreMenu.value = false
  await handleButtonClick(item)
}

// 工具集ActionSheet 选项选择
function onActionToolsSelect(item: any) {
  showToolsMenu.value = false
  if (item.type === 'tools') {
    const formData = xAddForm.value?.form || {}
    stepStore.setWorkflowId(workflowId)
    stepStore.setStepDefines(stepDefines.value)
    stepStore.setFormData(formData)
    stepStore.setCurrentStepData(currentStep.value)
    stepStore.setReadOnly(showType.value === 1)
    if (item.func) {
      stepStore.setCallbackFunction(async (data: any) => {
        return await executeStrFunctionByContext(
          getCurrentInstance(),
          item.func,
          [data, stepDefines.value, formData, currentStep.value, util, runLogic, getConfigByName],
        )
      })
    }
    router.push({
      name: item.value,
    })
  }
  else if (item.type === 'clearTempData') {
    showToast('清除临时数据成功')
    stepStore.setCallbackFunction(undefined)
  }
  else if (item.type === 'backHome') {
    stepStore.setCallbackFunction(undefined)
    router.push({
      path: '/',
    })
  }
  else if (item.type === 'applyDetail') { // 小工具 流程查看
    stepStore.setCallbackFunction(undefined)
    router.push({
      name: 'applyDetail',
      query: {
        workflowid: workflowId,
      },
    })
  }
}

// 处理业务相关的表单函数
function formFunc(func: string) {
  if (props.onFormFunc) {
    props.onFormFunc(func)
  }
}

// 处理地址选择
function selectAddressFunc() {
  if (props.onSelectAddress) {
    props.onSelectAddress()
  }
}

provide('workflowHandleWrap', {
  branchChargePersons,
  calculatedTargetNode,
  isNeedSelectPerson,
  needMultipleBranchSelection,
  branchNodes,
  checkedNextStepPerson,
  checkedNextStepPersonName,
  nextStepPersonOptions,
  getStepNameByStepId,
})

// 暴露方法给父组件
defineExpose({
  xAddForm,
  setForm: (data) => {
    xAddForm.value?.setForm(data)
  },
  workflowDetailData,
})

// 从缓存中还原之后 执行编辑路由回调函数
async function callbackFunction() {
  if (stepStore.getCallbackFunction()) {
    try {
      const func = stepStore.getCallbackFunction()
      await func({ workflowId })
    }
    catch (error) {
      console.error('func 执行出错:', error)
    }
    finally {
      stepStore.setCallbackFunction(undefined)
    }
  }
}

onActivated(async () => {
  await callbackFunction()
})

onBeforeMount(async () => {
  if (!workflowId || !stepId) {
    router.push({
      path: '/',
    })
  }
  else {
    await initComponent()
  }
})
</script>

<template>
  <div v-if="isFinish" id="apply-step">
    <div v-if="currentStep.properties?.otherProperty?.toast" class="info-card">
      <VanIcon name="info-o" color="#1890ff" class="info-icon" />
      <div class="info-content">
        <div> {{ currentStep.properties?.otherProperty?.toast }} </div>
      </div>
    </div>
    <VanCellGroup title="步骤信息">
      <VanCell title="步骤名称" :value="currentStep.name" />
      <VanCell title="负责人" :value="currentStep.handler" />
      <VanCell v-if="currentStep.date" title="填报时间" :value="currentStep.date" />
      <VanCell title="截止时间" :value="currentStep.deadline" />
    </VanCellGroup>
    <VanCellGroup v-if="currentStep.back" title="退回信息">
      <VanCell title="说明" value="流程被退回，请重新填写信息发起提交" />
      <VanCell title="操作人" :value="currentStep.back.f_operator" />
      <VanCell title="操作时间" :value="currentStep.back.f_date" />
      <VanCell title="退回原因" :value="currentStep.back.f_notes" />
    </VanCellGroup>
    <template v-if="showType === 0">
      <HistoryFormData
        v-if="historyFormCompletedDataPreview"
        :data="historyFormCompletedDataPreview.data"
        :step-attachments="historyFormCompletedDataPreview.stepAttachments"
      />
      <XForm
        ref="xAddForm"
        mode="新增"
        group-title="填写表单"
        :is-group-form="true"
        :form-data="xAddFormData"
        :group-form-items="stepFormDefine"
        :submit-button="false"
        :service-name="serviceName"
        :is-handle-form-key="false"
        :param-logic-name-param="{ workflowId }"
        @select-address="selectAddressFunc"
        @x-form-item-emit-func="formFunc"
      >
        <template #extraCellGroup>
          <VanCellGroup title="工单信息">
            <!--     备注信息    -->
            <VanField
              v-model="noteContent"
              rows="3"
              autosize
              label="备注"
              type="textarea"
              maxlength="200"
              placeholder="填写本环节备注事项"
              show-word-limit
            />
          </VanCellGroup>
        </template>
        <template #extraActionSpace>
          <div class="form-footer-fixed">
            <!-- 按钮容器 -->
            <div class="button-container">
              <!-- 显示的主按钮 (最多3个) -->
              <template v-for="(button, index) in displayedButtons" :key="index">
                <VanButton
                  :type="button.type || 'default'"
                  class="flex-1" :class="[
                    button.class,
                    { 'more-button': button.isMoreButton },
                  ]"
                  @click="handleButtonClick(button)"
                >
                  <template v-if="button.icon">
                    <VanIcon class="btn-icon" :name="button.icon" />
                  </template>
                  <template v-if="button.isMoreButton">
                    <VanIcon name="ellipsis" />
                  </template>
                  <template v-else>
                    {{ button.text }}
                  </template>
                </VanButton>
              </template>
            </div>
          </div>
        </template>
      </XForm>
      <!-- 扩展操作弹出区域 -->
      <VanActionSheet
        v-model:show="showMoreMenu"
        :actions="actionSheetActions"
        cancel-text="取消"
        @select="onActionSheetSelect"
        @cancel="showMoreMenu = false"
      />
    </template>
    <template v-else-if="showType === 1">
      <VanCellGroup title="填写历史">
        <template v-if="stepFormData && stepFormData.length > 0">
          <template v-for="(item, i) in stepFormData" :key="`${stepFormData.label} - ${i}`">
            <VanCell :title="item.label" :value="item.value" />
          </template>
        </template>
        <template v-else>
          <VanEmpty description="该步骤暂无数据" />
        </template>
      </VanCellGroup>
      <VanCellGroup title="备注">
        <VanCell title="备注信息" :value="currentStep.note" />
      </VanCellGroup>
      <VanCellGroup v-if="stepFilesData.length > 0" title="附件">
        <FileItem :files="stepFilesData" />
      </VanCellGroup>
      <VanCellGroup v-if="stepImageData.length > 0" title="图片">
        <FileItem :files="stepImageData" />
      </VanCellGroup>
    </template>
    <!-- 工具集弹出区域 -->
    <VanActionSheet
      v-model:show="showToolsMenu"
      :actions="toolActions"
      cancel-text="取消"
      @select="onActionToolsSelect"
      @cancel="showToolsMenu = false"
    />
    <!-- 磁吸工具按钮 -->
    <VanFloatingBubble
      axis="xy"
      icon="more-o"
      magnetic="x"
      @click="handleToolsPopoverClick"
    />
  </div>
  <div v-else-if="isError">
    <VanEmpty :image="errorImage" :description="errorMsg">
      <VanButton round type="primary" class="bottom-button" @click="back">
        返回上一页
      </VanButton>
    </VanEmpty>
  </div>
  <div v-else-if="isLoading">
    <BeautifulLoading />
  </div>
  <VanActionSheet v-model:show="dialogVisible" class="actionSheetBox" :close-on-click-overlay="false" :close-on-click-action="true" :title="dialogTitle">
    <div class="actionSheetContent">
      <template v-if="operationType === 'submit' || operationType === 'skip'">
        <div class="dialog-box">
          <!-- 智能分支人员选择组件 - 只有非分支节点或最后一个分支才显示 -->
          <template v-if="!isBranchLastNode.isBranchNode || isBranchLastNode.isLastBranch">
            <PersonSelect />
            <XFormItem
              v-model="deadline"
              mode="新增"
              label="截止时间"
              :attr="{ name: '截止时间', type: 'datePicker', rule: { required: 'true' } }"
            />
          </template>
        </div>
      </template>
      <template v-else-if="operationType === 'back'">
        <VanField
          v-model="backNoteContent"
          rows="3"
          autosize
          label="退回原因"
          type="textarea"
          maxlength="200"
          placeholder="填写退回原因/备注"
          show-word-limit
        />
      </template>
    </div>
    <div class="actionSheetFoot">
      <VanButton type="default" @click="() => { dialogVisible = false }">
        取消
      </VanButton>
      <VanButton type="primary" @click="dialogClick">
        确认
      </VanButton>
    </div>
  </VanActionSheet>
</template>

<style scoped lang="less">
.x-form-container {
  padding-bottom: 90px;
  display: block;
  max-height: initial;
}
.form-footer-fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;

  padding: 12px;
  box-sizing: border-box;

  /* 阴影效果 - 向上投射 */
  box-shadow:
    0 -4px 12px rgba(0, 0, 0, 0.1),
    0 -2px 4px rgba(0, 0, 0, 0.06);

  /* 毛玻璃背景 (移动端高级效果) */
  background-color: rgba(255, 255, 255, 0.85);
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);

  /* 边框增强立体感 */
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}
.button-container {
  display: flex;
  gap: 8px;

  .van-button {
    flex: 1; /* 所有按钮等分宽度 */
    min-width: 0; /* 防止文本溢出 */

    /* 按钮文字超出时显示省略号 */
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .more-button {
    flex: 0 0 50px; /* 更多按钮固定宽度 */
    padding: 0;
  }

  .submit-btn {
    background-color: #1890ff;
    border: 0;
  }

  .skip-btn {
    background-color: #52c41a;
    border: 0;
    color: #fff;
  }

  .prev-btn {
    border: 0;
  }

  .btn-icon {
    padding-right: 6px;
  }
}
.info-card {
  display: flex;
  align-items: flex-start;
  background: #eaf6ff;
  border-left: 3px solid #1677ff;
  border-radius: 12px;
  padding: 10px 16px 8px 14px;
  margin: 16px 16px 0 16px;
  font-size: 15px;
  color: #1677ff;
  min-height: 44px;
  box-shadow: none;
  border-top: none;
  border-right: none;
  border-bottom: none;
}
.info-icon {
  font-size: 20px;
  margin-right: 8px;
  margin-top: 2px;
  color: #1677ff;
  flex-shrink: 0;
}
.info-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.info-content > div:first-child {
  font-weight: bold;
  color: #1677ff;
  font-size: 15px;
  margin-bottom: 2px;
}
.info-content > div:last-child {
  font-size: 14px;
  color: #1677ff;
}
.actionSheetBox {
  .actionSheetContent {
    padding-bottom: 0;
  }
  .actionSheetFoot {
    display: grid;
    grid-template-columns: auto auto;
    width: 100%;
    margin-top: 20px;
    :deep(.van-button) {
      border-radius: 0 !important;
    }
  }
}
</style>
