<template>
  <div class="p-2">
    <!-- 工单信息区域 -->
    <h4 class="form-header h4">工单信息</h4>
    <el-card shadow="never" class="mb-[10px]">
      <el-form label-width="120px">
        <el-row>
          <el-col :span="8" :offset="2">
            <el-form-item label="工单编号">
              <el-input v-model="billsInfo.billsRepairCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="工单状态">
              <el-input v-model="billsStatusCheck" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="申请人">
              <el-input v-model="billsInfo.createBy" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="申请时间">
              <el-input v-model="billsInfo.createTime" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="2">
            <el-form-item label="备注">
              <el-input v-model="billsInfo.remark" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 流程步骤展示区域 -->
    <el-card shadow="never" class="mb-[10px]">
      <el-form ref="stepFormRef" :model="form" label-width="100px">
        <!-- 第一步 -->
        <h4 class="form-header h4" v-if="dmsRepairInstanceActivityList.length > 0">已处理节点：步骤1（要求参数）</h4>
        <el-row v-if="dmsRepairInstanceActivityList.length > 0">
          <el-col :span="8">
            <el-form-item label="检修类型" prop="repairType">
              <el-select v-model="form.repairType" placeholder="检修类型" disabled>
                <el-option v-for="dict in repair_type" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检修组别" prop="repairGroup">
              <el-input v-model="form.repairGroup" placeholder="请输入检修组别" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检修负责人" prop="repairSupervisor">
              <el-input v-model="form.repairSupervisor" placeholder="请输入检修负责人" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 中间步骤 (已处理的后续节点) -->
        <template v-for="activity in dmsRepairInstanceActivityList" :key="activity.instanceActivityId">
          <div v-if="activity.processStepOrder && activity.processStepOrder > 1">
            <h4 class="form-header h4">{{ `已处理节点：步骤${activity.processStepOrder}（${activity.processStepOrder === 2 ? '实际参数' : '工单完成'}）` }}</h4>
            <el-row>
              <el-col :span="8">
                <el-form-item label="检修类型">
                  <el-select v-model="activity.repairType" placeholder="检修类型" disabled>
                    <el-option v-for="dict in repair_type" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
          </el-select>
        </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="检修组别">
                  <el-input v-model="activity.repairGroup" disabled placeholder="检修组别"> </el-input>
        </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="检修负责人">
                  <el-input v-model="activity.repairSupervisor" disabled placeholder="检修负责人"> </el-input>
        </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="处理意见">
                  <el-input v-model="activity.processHandleResolution" disabled placeholder="处理意见"> </el-input>
        </el-form-item>
              </el-col>
            </el-row>
          </div>
        </template>

        <!-- 当前步骤表单 (用于提交新节点) -->
        <div v-if="isUpdate">
          <h4 class="form-header h4">
            {{
              isCreatingWorkflow && dmsRepairInstanceActivityList.length === 0
                ? `创建工单：步骤1（要求参数）`
                : `当前处理节点：步骤${nextStepOrder}${nextStepOrder === 2 ? '（实际参数）' : nextStepOrder === 3 ? '（工单完成）' : ''}`
            }}
          </h4>
          <el-form ref="nextStepFormRef" :model="nextStepForm" :rules="nextStepFormRules" label-width="100px">
            <el-row>
              <el-col :span="8">
                <el-form-item label="检修类型" prop="repairType">
                  <el-select v-model="nextStepForm.repairType" placeholder="检修类型" :disabled="nextStepOrder === 3">
                    <el-option v-for="dict in repair_type" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
          </el-select>
        </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="检修组别" prop="repairGroup">
                  <el-input v-model="nextStepForm.repairGroup" placeholder="检修组别" :disabled="nextStepOrder === 3"></el-input>
        </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="检修负责人" prop="repairSupervisor">
                  <el-input v-model="nextStepForm.repairSupervisor" placeholder="检修负责人" :disabled="nextStepOrder === 3"></el-input>
        </el-form-item>
              </el-col>
              <el-col :span="24" v-if="!(isCreatingWorkflow && dmsRepairInstanceActivityList.length === 0)">
                <el-form-item label="处理意见" prop="processHandleResolution">
                  <el-input v-model="nextStepForm.processHandleResolution" placeholder="处理意见"></el-input>
        </el-form-item>
              </el-col>
              <el-col :span="24" class="text-center mt-4">
                <el-button
                  type="primary"
                  @click="submitForm"
                  :loading="buttonLoading"
                  :disabled="buttonLoading || (!currentTaskId && !isCreatingWorkflow)"
                >
                  {{ buttonText }}
                </el-button>
                <el-button
                  v-if="billsInfo && billsInfo.repairInstanceId !== null && billsInfo.status !== 'draft'" 
                  type="primary"
                  @click="handleApprovalRecord"
                >
                  流程进度
                </el-button>
              </el-col>
            </el-row>
      </el-form>
        </div>
      </el-form>
    </el-card>

    <!-- 提交组件 -->
    <submitVerify ref="submitVerifyRef" :task-variables="taskVariables as any" @submit-callback="submitCallback" @cancel-callback="cancelCallback" />
    <!-- 审批记录 -->
    <approvalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup name="DmsRepairInstanceActivity" lang="ts">
import { ref, reactive, toRefs, getCurrentInstance, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus';
import {
  addDmsRepairInstanceActivity,
  getDmsRepairInstanceActivityList,
} from '@/api/dms/dmsRepairInstanceActivity';
import {
  DmsRepairInstanceActivityVO,
  DmsRepairInstanceActivityForm
} from '@/api/dms/dmsRepairInstanceActivity/types';
import { getDmsRepairInstance } from '@/api/dms/dmsRepairInstance';

import { startWorkFlow, pageByTaskWait } from '@/api/workflow/task';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import { FlowTaskVO } from '@/api/workflow/task/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { repair_type, process_handle_status, repair_status } = toRefs<any>(proxy?.useDict('repair_type', 'process_handle_status', 'repair_status'));
const route = useRoute();

const stepFormRef = ref<FormInstance>();
const nextStepFormRef = ref<FormInstance>();

const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const taskVariables = ref<any>({});
const submitFormData = ref<StartProcessBo>({
  businessId: '',
  flowCode: 'Repair01', // 检修工单流程编码，请根据实际情况修改
  variables: {}
});

const loading = ref(true);
const dmsRepairInstanceActivityList = ref<DmsRepairInstanceActivityVO[]>([]);
const billsInfo = ref<any>({});
const billsStatusCheck = ref('');
const isUpdate = ref(true);
const repairInstanceId = route.params.repairInstanceId as string;
const buttonLoading = ref(false);

const currentTaskId = ref<string | number | null>(null);
const isCreatingWorkflow = ref(false);
const buttonText = ref('创建工单并提交');

const pendingActivityData = ref<DmsRepairInstanceActivityForm | null>(null);

const nextStepOrder = computed(() => {
  return dmsRepairInstanceActivityList.value.length + 1;
});

const form = reactive<Partial<DmsRepairInstanceActivityForm>>({
  repairType: undefined,
  repairGroup: undefined,
  repairSupervisor: undefined,
  remark: undefined,
});

const nextStepForm = reactive<DmsRepairInstanceActivityForm>({
  instanceActivityId: undefined,
  repairInstanceId: repairInstanceId,
  repairType: undefined,
  repairGroup: undefined,
  repairSupervisor: undefined,
  processHandleResolution: undefined,
  processHandleStatus: undefined,
  processStepOrder: undefined,
  startTime: undefined,
  endTime: undefined,
  handleUserId: undefined,
  handleBy: undefined,
  handleTime: undefined,
  transferUserId: undefined,
  attr1: undefined,
  remark: undefined,
});

const nextStepFormRules = reactive<FormRules>({
  repairType: [{ required: true, message: "检修类型不能为空", trigger: "change" }],
  repairGroup: [{ required: true, message: "检修组别不能为空", trigger: "blur" }],
  repairSupervisor: [{ required: true, message: "检修负责人不能为空", trigger: "blur" }],
  processHandleResolution: [{ required: false, message: "处理意见不能为空", trigger: "blur" }],
});

onMounted(async () => {
    await loadData();
});

async function loadData() {
  loading.value = true;
  try {
    if (nextStepFormRef.value) {
      nextStepFormRef.value.clearValidate();
    }

    await dmsRepairInstance(); 
    await getList(); 

    if (dmsRepairInstanceActivityList.value.length === 0) {
      currentTaskId.value = null;
      isCreatingWorkflow.value = true;
    } else {
      isCreatingWorkflow.value = false;
      currentTaskId.value = null; 
      const completedSteps = dmsRepairInstanceActivityList.value.length;

      if (completedSteps < 3) {
        proxy?.$modal.loading("正在获取最新流程任务...");
        let expectedNodeName = '';
        if (completedSteps === 1) expectedNodeName = '工单处理'; 
        else if (completedSteps === 2) expectedNodeName = '工单完成';

        console.log(`[loadData] Attempting to find current task. Completed steps: ${completedSteps}, Expected next node: '${expectedNodeName}' for businessId: ${repairInstanceId}`);

        try {
          let tasks: FlowTaskVO[] = [];
          if (expectedNodeName) {
            const taskRes = await pageByTaskWait({
    pageNum: 1,
    pageSize: 10,
              flowCode: submitFormData.value.flowCode, 
              nodeName: expectedNodeName
            });
            if (taskRes.rows) {
              tasks = taskRes.rows.filter(task => task.businessId === repairInstanceId);
              if (tasks.length > 0) {
                 console.log(`[loadData] Found ${tasks.length} task(s) using specific nodeName '${expectedNodeName}' and businessId '${repairInstanceId}'.`);
              } else {
                 console.log(`[loadData] No tasks found using specific nodeName '${expectedNodeName}' for businessId '${repairInstanceId}'. Will try broader search.`);
              }
            }
          }

          let foundTask: FlowTaskVO | undefined = tasks.length > 0 ? tasks[0] : undefined; 
          if (tasks.length > 1) {
            console.warn(`[loadData] Multiple tasks (${tasks.length}) found with specific nodeName '${expectedNodeName}' and businessId '${repairInstanceId}'. Using the first one found: ${foundTask?.id}.`);
          }

          if (!foundTask) {
            console.log(`[loadData] Task not found with specific nodeName. Fetching all waiting tasks for flowCode '${submitFormData.value.flowCode}' to filter by businessId '${repairInstanceId}'.`);
            const taskResAll = await pageByTaskWait({
              pageNum: 1,
              pageSize: 50, 
              flowCode: submitFormData.value.flowCode
            });

            if (taskResAll.rows && taskResAll.rows.length > 0) {
              const businessTasks = taskResAll.rows.filter(task => task.businessId === repairInstanceId);
              if (businessTasks.length === 1) {
                foundTask = businessTasks[0];
                console.log(`[loadData] Found single task by businessId from all waiting tasks: ${foundTask.id}, Node: ${foundTask.nodeName}`);
              } else if (businessTasks.length > 1) {
                console.warn(`[loadData] Multiple tasks (${businessTasks.length}) found for businessId '${repairInstanceId}' from all waiting tasks. Attempting to match with expectedNodeName '${expectedNodeName}'.`);
                if (expectedNodeName) {
                  foundTask = businessTasks.find(task => task.nodeName === expectedNodeName);
                }
                if (foundTask) {
                  console.log(`[loadData] Matched task by expectedNodeName from multiple: ${foundTask.id}`);
                } else {
                  foundTask = businessTasks[0];
                  console.warn(`[loadData] Could not specifically match by nodeName among multiple tasks for businessId '${repairInstanceId}'. Using the first one found: ${foundTask?.id}, Node: ${foundTask?.nodeName}. Review workflow design if this is not correct.`);
                }
              } else {
                 console.log(`[loadData] No tasks found for businessId '${repairInstanceId}' even after broader search by flowCode '${submitFormData.value.flowCode}'.`);
              }
            }
          }

          if (foundTask) {
            currentTaskId.value = foundTask.id;
            console.log(`[loadData] Successfully set currentTaskId via pageByTaskWait to: ${currentTaskId.value} (Node: ${foundTask.nodeName}, BusinessID: ${foundTask.businessId})`);
          } else {
            console.warn(`[loadData] No suitable waiting task found for businessId ${repairInstanceId} with flowCode ${submitFormData.value.flowCode}. Button may show '暂无操作'.`);
          }
        } catch (error) {
          console.error("[loadData] Error fetching current task via pageByTaskWait:", error);
          proxy?.$modal.msgError("获取最新流程任务失败");
        } finally {
          proxy?.$modal.closeLoading();
        }
      } else {
        console.log("[loadData] All expected business steps completed (>=3) or initial creation. No active task to fetch from workflow via pageByTaskWait for middle steps.");
      }
    }

    updateButtonAndFormState();

    setTimeout(() => {
      if (nextStepFormRef.value) {
        nextStepFormRef.value.clearValidate();
      }
    }, 100);
  } catch (error) {
    console.error("Failed to load initial data", error);
    proxy?.$modal.msgError("加载数据失败");
    currentTaskId.value = null;
    isCreatingWorkflow.value = dmsRepairInstanceActivityList.value.length === 0;
    updateButtonAndFormState();
  } finally {
    loading.value = false;
  }
}

function updateButtonAndFormState() {
  const activitiesCount = dmsRepairInstanceActivityList.value.length;
  
  if (activitiesCount === 0 && isCreatingWorkflow.value) {
    buttonText.value = '创建工单并提交';
    nextStepFormRules.processHandleResolution = [{ required: false, message: "处理意见不能为空", trigger: "blur" }];
    Object.assign(nextStepForm, {
    instanceActivityId: undefined,
        repairInstanceId: repairInstanceId, 
    repairType: undefined,
    repairGroup: undefined,
    repairSupervisor: undefined,
    processHandleResolution: undefined,
    processHandleStatus: undefined,
    processStepOrder: undefined,
    startTime: undefined,
    endTime: undefined,
    handleUserId: undefined,
    handleBy: undefined,
    handleTime: undefined,
    transferUserId: undefined,
    attr1: undefined,
        remark: undefined,
    });
  } 
  else if (currentTaskId.value && !isCreatingWorkflow.value) { 
    const currentStepBasedOnActivities = activitiesCount + 1;

    if (currentStepBasedOnActivities === 2) {
      buttonText.value = '工单处理';
      nextStepFormRules.processHandleResolution = [{ required: true, message: "处理意见不能为空", trigger: "blur" }];
    } else if (currentStepBasedOnActivities === 3) {
      buttonText.value = '工单完成';
      nextStepFormRules.processHandleResolution = [{ required: true, message: "处理意见不能为空", trigger: "blur" }];
    } else {
      buttonText.value = '提交处理';
      nextStepFormRules.processHandleResolution = [{ required: true, message: "处理意见不能为空", trigger: "blur" }];
    }
    
    if (activitiesCount > 0) {
      const firstActivity = dmsRepairInstanceActivityList.value[0];
      const lastActivity = dmsRepairInstanceActivityList.value[activitiesCount - 1];
      if (currentStepBasedOnActivities === 2) { 
         Object.assign(nextStepForm, {
          instanceActivityId: undefined,
          repairInstanceId: repairInstanceId,
          repairType: firstActivity.repairType,
          repairGroup: firstActivity.repairGroup, 
          repairSupervisor: firstActivity.repairSupervisor, 
          processHandleResolution: '', 
          remark: '', 
          processHandleStatus: undefined,
          processStepOrder: undefined,
        });
      } else if (currentStepBasedOnActivities === 3) { 
        Object.assign(nextStepForm, {
          instanceActivityId: undefined, 
          repairInstanceId: repairInstanceId,
          repairType: firstActivity.repairType,
          repairGroup: firstActivity.repairGroup, 
          repairSupervisor: firstActivity.repairSupervisor, 
          processHandleResolution: '', 
          remark: '', 
          processHandleStatus: undefined,
          processStepOrder: undefined,
        });
      } else { 
        Object.assign(nextStepForm, {
          instanceActivityId: undefined, 
          repairInstanceId: repairInstanceId,
          repairType: lastActivity.repairType,
          repairGroup: lastActivity.repairGroup,
          repairSupervisor: lastActivity.repairSupervisor,
          processHandleResolution: '', 
          remark: '', 
          processHandleStatus: undefined,
          processStepOrder: undefined,
        });
      }
    } else { 
        Object.assign(nextStepForm, {
            instanceActivityId: undefined,
            repairInstanceId: repairInstanceId,
            processHandleResolution: '',
            remark: '',
        });
    }
  } else { 
    buttonText.value = '暂无操作';
    if (isUpdate.value) { 
        nextStepFormRules.processHandleResolution = [{ required: false }];
    }
  }
}

const dmsRepairInstance = async () => {
    const _repairInstanceId = repairInstanceId;
    const res = await getDmsRepairInstance(_repairInstanceId);
    billsInfo.value = res.data;

    if (repair_status.value && billsInfo.value.billsStatus !== undefined) { 
        const statusItem = repair_status.value.find((item: any) => String(item.value) === String(billsInfo.value.billsStatus));
        billsStatusCheck.value = statusItem ? statusItem.label : '未知状态';
    } else {
        billsStatusCheck.value = '未知状态';
    }
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await getDmsRepairInstanceActivityList({repairInstanceId: repairInstanceId}); 
    dmsRepairInstanceActivityList.value = res.data;
    
    if (res.data && res.data.length > 0) {
        Object.assign(form, { 
            repairType: res.data[0].repairType,
            repairGroup: res.data[0].repairGroup,
            repairSupervisor: res.data[0].repairSupervisor,
            remark: res.data[0].remark
        });
    } else { 
        Object.assign(form, {
            repairType: undefined,
            repairGroup: undefined,
            repairSupervisor: undefined,
            remark: undefined
        });
    }
    updateButtonAndFormState(); 

  } catch (error) {
    console.error('获取工单实例节点数据失败', error);
    proxy?.$modal.msgError("获取工单实例节点数据失败");
  } finally {
  loading.value = false;
}
};

const submitForm = async () => {
  if (!nextStepFormRef.value) return;
  
  try {
    buttonLoading.value = false;
    pendingActivityData.value = null;
    
    nextStepFormRef.value.clearValidate();
    
    const valid = await nextStepFormRef.value.validate().catch(errors => {
      console.error("表单验证错误:", errors);
      return false;
    });
    
    if (valid) {
      buttonLoading.value = true;
      
      try {
        nextStepForm.processStepOrder = dmsRepairInstanceActivityList.value.length + 1;
        nextStepForm.repairInstanceId = repairInstanceId; 

        if (nextStepForm.processStepOrder > 1 && (nextStepForm.processHandleResolution === undefined || nextStepForm.processHandleResolution === null)) {
          nextStepForm.processHandleResolution = '';
        }
        
        pendingActivityData.value = JSON.parse(JSON.stringify(nextStepForm));

        taskVariables.value = { 
          entity: { 
            repairInstanceId: pendingActivityData.value.repairInstanceId,
            repairType: pendingActivityData.value.repairType,
            repairGroup: pendingActivityData.value.repairGroup,
            repairSupervisor: pendingActivityData.value.repairSupervisor,
            processHandleResolution: pendingActivityData.value.processHandleResolution,
            processStepOrder: pendingActivityData.value.processStepOrder
          }
        };

        if (isCreatingWorkflow.value && dmsRepairInstanceActivityList.value.length === 0) {
          submitFormData.value.businessId = repairInstanceId;
          submitFormData.value.variables = taskVariables.value;

          console.log("[submitForm] 开始启动工作流, businessId:", repairInstanceId);
          const workflowRes = await startWorkFlow(submitFormData.value);
          
          if (!workflowRes || !workflowRes.data || !workflowRes.data.taskId) {
            buttonLoading.value = false;
            throw new Error("工作流启动失败，未能获取有效的任务ID");
          }
          
          console.log("[submitForm] 工作流启动成功, taskId:", workflowRes.data.taskId);
          
          if (submitVerifyRef.value) {
            buttonLoading.value = false; 
            submitVerifyRef.value.openDialog(String(workflowRes.data.taskId));
          } else {
            buttonLoading.value = false;
            throw new Error("提交流程组件不可用");
          }
        } else if (currentTaskId.value && !isCreatingWorkflow.value) {
          console.log("[submitForm] 处理工作流节点, taskId:", currentTaskId.value);
          
          if (submitVerifyRef.value) {
            buttonLoading.value = false;
            submitVerifyRef.value.openDialog(String(currentTaskId.value));
          } else {
            buttonLoading.value = false;
            throw new Error("提交流程组件不可用");
          }
        } else {
          buttonLoading.value = false;
          throw new Error("未知的提交流程状态或没有待办任务ID");
        }
      } catch (error: any) {
        buttonLoading.value = false;
        pendingActivityData.value = null; 
        console.error('[submitForm] 提交失败:', error);
        proxy?.$modal.msgError(error.message || "提交失败，请检查数据或联系管理员");
      }
    } else {
      buttonLoading.value = false;
      proxy?.$modal.msgError("表单校验失败，请检查输入项");
    }
  } catch (error) {
    buttonLoading.value = false;
    console.error('[submitForm] 意外错误:', error);
    proxy?.$modal.msgError("表单提交过程中发生错误");
  }
};

const handleApprovalRecord = () => {
  approvalRecordRef.value.init(repairInstanceId); 
};

const submitCallback = async () => {
  console.log('[submitCallback] Invoked.');

  try {
    if (pendingActivityData.value) {
      const activityRes = await addDmsRepairInstanceActivity(pendingActivityData.value); 
      console.log("[submitCallback] Business data saved successfully:", activityRes.data);

      const stepOrderOfSavedData = pendingActivityData.value.processStepOrder;

      if (stepOrderOfSavedData === 1) {
        proxy?.$modal.msgSuccess("工单创建数据已保存，流程已流转。");
      } else if (stepOrderOfSavedData === 2) {
        proxy?.$modal.msgSuccess("工单处理数据已保存，流程已流转。");
      } else if (stepOrderOfSavedData === 3) {
        proxy?.$modal.msgSuccess("工单完成数据已保存，工作流已结束。");
      } else {
        proxy?.$modal.msgSuccess("业务数据已保存，操作已继续。");
      }
    } else {
      console.warn("[submitCallback] pendingActivityData was null upon callback.");
    }
  } catch (error) {
    console.error('[submitCallback] Error saving business data:', error);
    proxy?.$modal.msgError("关键错误：业务数据保存失败！工作流可能已推进，请紧急核查数据一致性。");
  } finally {
    buttonLoading.value = false;
    pendingActivityData.value = null; 

    if (isUpdate.value) {
      try {
        console.log("[submitCallback] Reloading data to reflect current workflow state...");
        await loadData(); 
        console.log("[submitCallback] Data reloaded. Current Task ID is now:", currentTaskId.value);
      } catch (loadError) {
        console.error('[submitCallback] Failed to reload data post-submission attempt:', loadError);
        proxy?.$modal.msgError("数据刷新失败，请手动刷新页面以查看最新状态。");
      }
    }
  }
};

const cancelCallback = () => {
  console.log('[cancelCallback] 用户取消了操作');
  pendingActivityData.value = null; 
  buttonLoading.value = false;
};
</script>

<style scoped>
.form-header {
  font-size: 15px;
  color: #409eff;
  border-bottom: 1px solid #ddd;
  margin: 8px 0 15px;
  padding-bottom: 10px;
}
</style>
