<template>
  <view class="page-container">
    <!-- 页面级加载组件 -->
    <up-loading-page
        v-if="loading"
        :loading="true"
        title="加载中..."
        color="#3c9cff"
    ></up-loading-page>

    <!-- 主内容容器 -->
    <view v-else class="main-content">
      <!-- 顶部固定Tabs -->
      <up-sticky :bgColor="'#fff'">
        <up-tabs
            v-model="activeTopTab"
            :list="topTabList"
            :scrollable="false"
            sticky
            active-color="#3c9cff"
            inactive-color="#666"
            class="top-tabs"
            @click="activeTopTabClick"
        ></up-tabs>
      </up-sticky>

      <!-- 顶部Tab内容区 -->
      <view class="tab-content">
        <!-- 1. 工单详情Tab -->
        <view v-show="activeTopTab == 0" class="detail-content">
          <up-cell-group :border="false" class="detail-cell-group">
            <!-- 工单编号 -->
            <up-cell title="工单编号" :value="orderDetail.orderNo || '--'" align="middle"></up-cell>

            <!-- 工单位置 -->
            <up-cell align="middle">
              <template #title>
                <view style="min-width: 200rpx">工单位置</view>
              </template>
              <template #value>
                <view class="common-text-color up-line-1">{{ orderDetail.lonLatAddress || '--' }}</view>
              </template>
            </up-cell>

            <!-- 工单名称 -->
            <up-cell align="middle">
              <template #title>
                <view style="min-width: 200rpx">工单名称</view>
              </template>
              <template #value>
                <view class="common-text-color up-line-1">{{ orderDetail.orderName || '--' }}</view>
              </template>
            </up-cell>

            <!-- 街道名称 -->
            <up-cell title="街道名称" :value="orderDetail.streetName || '--'" align="middle"></up-cell>

            <up-cell v-if="orderDetail.roadName">
              <template #title>
                <view style="min-width: 200rpx">道路名称</view>
              </template>
              <template #value>
                <view class="common-text-color up-line-1">{{ orderDetail.roadName || '--' }}</view>
              </template>
            </up-cell>

            <!-- 情况描述 -->
            <up-cell>
              <template #title>
                <view style="min-width: 200rpx">情况描述</view>
              </template>
              <template #value>
                <view class="common-text-color up-line-1">{{ orderDetail.remark || '--' }}</view>
              </template>
            </up-cell>

            <!-- 紧急程度 -->
            <up-cell
                title="紧急程度"
                :value="uni.$dict.getDictLabel('workorder_pressing_type', orderDetail.pressingType) || '--'"
                align="middle"
            ></up-cell>

            <!-- 提交人 -->
            <up-cell title="提交人" :value="orderDetail.userName || '--'" align="middle"></up-cell>

            <!-- 提交时间 -->
            <up-cell
                title="提交时间"
                :value="timeFormat(orderDetail.createTime, 'yyyy-mm-dd hh:MM:ss') || '--'"
                align="middle"
            ></up-cell>

            <!-- 处理结果 -->
            <up-cell v-if="orderDetail.handleResult">
              <template #title>
                <view style="min-width: 200rpx">处理结果</view>
              </template>
              <template #value>
                <view class="common-text-color up-line-1">{{ orderDetail.handleResult || '--' }}</view>
              </template>
            </up-cell>

            <!-- 问题照片 -->
            <up-cell title="问题照片">
              <template #value>
                <view class="cell-content-wrap">
                  <up-album
                      v-if="!!orderDetail.problemsImgs?.length"
                      :urls="orderDetail.problemsImgs.slice(0, 3)"
                      :singleSize="70"
                      :multipleSize="70"
                      :preview-full-image="true"
                  ></up-album>
                  <text v-else class="empty-text">暂无问题照片</text>
                </view>
              </template>
            </up-cell>

            <!-- 希望完成时间 -->
            <up-cell
                v-if="orderDetail.expectedFinishDate"
                title="希望完成时间"
                :value="timeFormat(orderDetail.expectedFinishDate, 'yyyy-mm-dd hh:MM:ss')"
                align="middle"
                :border="false"
            ></up-cell>

            <up-cell
                v-if="orderDetail.finishDate"
                title="工单完结时间"
                :value="timeFormat(orderDetail.finishDate, 'yyyy-mm-dd hh:MM:ss')"
                align="middle"
                :border="false"
            ></up-cell>
          </up-cell-group>

          <!-- 图片分类Tabs区块 -->
          <view class="img-tabs-block" v-if="orderDetail.startImgs.length>0">
            <up-cell-group :border="false">
              <up-cell>
                <template #title>
                  <view style="min-width: 200rpx">共同处理人</view>
                </template>
                <template #value>
                  <view class="common-text-color up-line-1">
                    {{
                      Array.isArray(orderDetail.coHandlersName) && orderDetail.coHandlersName.length > 0 ? orderDetail.coHandlersName.join(',') : '--'
                    }}
                  </view>
                </template>
              </up-cell>
            </up-cell-group>
            <up-tabs
                @change='imgTabChange'
                v-model="activeImgTab"
                :list="imgTabList"
                :scrollable="false"
                active-color="#3c9cff"
                inactive-color="#666"
                class="img-tabs"
            ></up-tabs>

            <!-- 图片Tab内容区 -->
            <view class="img-tab-content">
              <up-album
                  v-if="currentImgList.length"
                  :urls="currentImgList.slice(0, 3)"
                  :singleSize="70"
                  :multipleSize="70"
                  :preview-full-image="true"
                  class="img-album custom-album"
              ></up-album>
              <text v-else class="empty-img-text">养护员未上传图片</text>
            </view>
          </view>
        </view>

        <!-- 2. 流程节点Tab -->
        <view v-show="activeTopTab == 1" class="process-content">
          <!-- 竖向步骤条：动态绑定current属性 -->
          <up-steps
              v-if="processData.activityNodes && processData.activityNodes.length"
              :list="processData.activityNodes"
              :current="getCurrentStepIndex()"
              direction="column"
              active-color="#3c9cff"
              inactive-color="#999"
              class="vertical-steps"
          >
            <template>
              <up-steps-item
                  v-for="(item, index) in processData.activityNodes"
                  :key="`${item.id}_${index}`"
              >
                <!-- 唯一自定义模板：content，包含标题、描述、相册所有内容 -->
                <template #content>
                  <view class="step-content-wrap">
                    <!-- 1. 原标题内容：节点名称 + 操作人 -->
                    <view class="step-title">
                      {{ item.name }}
                    </view>

                    <!-- 2. 原描述内容：时间 + 处理说明（最多200字） -->
                    <view class="step-desc">
                      <view class="operator-name up-line-1">
                        处理人：
                        <text>{{ item.tasks?.map(itemName => itemName.assigneeUser?.nickname).filter(Boolean).join('，') }}</text>
                      </view>
                      <!-- 时间行 -->
                      <view class="time-line">
                        处理时间：{{ timeFormat(item.startTime, 'yyyy-mm-dd hh:MM:ss') }}
                        <text v-if="item.endTime"> 至 {{ timeFormat(item.endTime, 'yyyy-mm-dd hh:MM:ss') }}</text>
                        <text v-else class="processing-tag">（处理中）</text>
                      </view>

                      <view class="reason-line up-line-1" v-if="index!==0&&item.endTime">
                        总耗时：{{ calculateFormatTimeDiff(item.startTime, item.endTime) }}
                      </view>

                      <!-- 原因行 -->
                      <view class="reason-line up-line-2" v-if="item.tasks && item.tasks[0]?.reason">
                        描述：{{ getLimitReason(item.tasks && item.tasks[0]?.reason) }}
                      </view>
                    </view>

                    <!-- 3. 原相册内容：预留up-album -->
                    <view class="step-album-wrap">
                      <up-album
                          v-if="item.tasks && item.tasks[0]?.attattmentUrls && item.tasks[0].attattmentUrls.length"
                          :urls="item.tasks[0].attattmentUrls.slice(0, 3)"
                          :singleSize="70"
                          :multipleSize="70"
                          :preview-full-image="true"
                          class="step-album"
                      ></up-album>
                    </view>
                  </view>
                </template>
              </up-steps-item>
            </template>
          </up-steps>

          <!-- 流程节点为空时的提示 -->
          <up-empty
              v-else
              mode="data"
              title="暂无流程节点数据"
              class="empty-process"
          ></up-empty>
        </view>
      </view>
    </view>

    <!-- activeTab==0的时候才出现， 也就是待办 -->
    <view v-if="activeTab==0&&nextStepMap[orderDetail.taskKey]" class="fixed-bottom-btn-wrap">
      <view class="u-body-item u-flex common-justify-between common-item-center ">
        <up-button type="warning" size="normal" @click="handleReject(orderDetail)"
                   v-show="nextStepMap[orderDetail.taskKey].backShow">回退
        </up-button>

        <up-button type="success" size="normal" @click="handleRenew(orderDetail)"
                   v-show="nextStepMap[orderDetail.taskKey].renewShow">重新提交
        </up-button>

        <up-button type="primary" size="normal" @click="handleProcess(orderDetail)">{{
            nextStepMap[orderDetail.taskKey].btnText
          }}
        </up-button>

      </view>
    </view>

    <!-- 回退原因弹窗（新增图片上传） -->
    <up-modal
        :show="rejectModalShow"
        title="回退原因"
        :closeOnClickOverlay="false"
        :showConfirmButton="true"
        :showCancelButton="true"
        @cancel="handleRejectModalCancel"
        @confirm="confirmReject"
    >
      <view class="reject-modal-content">
        <up-textarea
            v-model.trim="rejectReason"
            placeholder="请输入回退原因（必填）"
            rows="6"
            :count="200"
            maxlength="200"
            class="reject-textarea"
        />
        <!-- 新增：回退图片上传（选填） -->
        <view class="upload-wrap mt-20">
          <view class="upload-title">上传回退图片（选填）</view>
          <up-upload
              :file-list="rejectImgs.rawImgList.value || []"
              @after-read="rejectImgs.uploadImgs"
              @delete="rejectImgs.deleteImg"
              multiple
              width="70"
              height="70"
              :max-count="rejectImgs.uploadConfig.maxCount"
              :upload-text="rejectImgs.uploadConfig.uploadText"
              :size-type="rejectImgs.uploadConfig.sizeType"
          />
        </view>
      </view>
    </up-modal>

    <!-- 验收弹窗（新增图片上传） -->
    <up-modal
        :show="acceptModalShow"
        title="验收"
        :closeOnClickOverlay="false"
        :showConfirmButton="true"
        :showCancelButton="true"
        @cancel="handleAcceptModalCancel"
        @confirm="handleAcceptModalConfirm"
    >
      <view class="accept-modal-content">
        <!-- 第一行：单选框（通过/不通过，默认通过） -->
        <view class="radio-group-wrap">
          <up-radio-group v-model="acceptRadioValue">
            <up-radio name="0" label="通过"></up-radio>
            <up-radio name="1" label="不通过"></up-radio>
          </up-radio-group>
        </view>

        <!-- 第二行：必填textarea，最多200字 -->
        <view class="textarea-wrap mt-30">
          <up-textarea
              v-model.trim="acceptReason"
              placeholder="请输入验收原因（必填，最多200字）"
              :required="true"
              maxlength="200"
              rows="5"
              count
          />
        </view>

        <!-- 新增：验收图片上传（选填） -->
        <view class="upload-wrap mt-20">
          <view class="upload-title">上传验收图片（选填）</view>
          <up-upload
              :file-list="acceptImgs.rawImgList.value || []"
              @after-read="acceptImgs.uploadImgs"
              @delete="acceptImgs.deleteImg"
              multiple
              width="70"
              height="70"
              :max-count="acceptImgs.uploadConfig.maxCount"
              :upload-text="acceptImgs.uploadConfig.uploadText"
              :size-type="acceptImgs.uploadConfig.sizeType"
          />
        </view>
      </view>
    </up-modal>

  </view>
</template>

<script setup lang="ts">
import {ref, computed} from 'vue';
import {onLoad, onShow} from '@dcloudio/uni-app';
import {timeFormat} from '@/uni_modules/uview-plus';
import {
  getMyTaskDetail,
  getDoneTaskDetail,
  getTodoTaskDetail,
  getApprovalDetail,
  daquUniversalApproval,
  qyUniversalApproval,
  dcyUniversalApproval
} from '@/api/regional-order-manage/regional-order-manage';
import {nextStepMap, buzStatusMap, calculateFormatTimeDiff} from '@/common/utils/common'
import {useUploadImgs} from '@/common/utils/useUploadImgs'
import { useUserStore } from '@/pinia/user';

// ========== 全局实例 & 常量 ==========
const userStore = useUserStore();
const USER_ROLES = userStore.userInfo?.roles || [];
// ========== 页面通信事件通道 解决未定义BUG ==========
const eventChannel = ref<any>(null);


// ========== 公共封装方法 (和列表页完全一致) ==========
/**
 * 统一提示方法
 */
const showToast = (title: string, icon: 'none'|'success'|'loading' = 'none', duration = 2000) => {
  uni.showToast({ title, icon, duration });
};

/**
 * 生成统一的临时存储key
 */
const generateTempKey = (prefix = 'order') => {
  return `${prefix}_${Date.now()}_${Math.floor(Math.random() * 10000)}`;
};

/**
 * 存储工单数据到本地缓存
 */
const setOrderStorage = (item: any, prefix: string) => {
  if (!item?.id) return null;
  const tempKey = generateTempKey(prefix);
  try {
    uni.setStorageSync(tempKey, item);
    return tempKey;
  } catch (error) {
    console.error('存储工单数据失败：', error);
    showToast('数据存储异常，请重试');
    return null;
  }
};

/**
 * 统一调用审批接口 (角色+taskKey匹配)
 */
const callApprovalApi = async (params: any, taskKey: string) => {
  if (taskKey === 'shRegionManager') return await dcyUniversalApproval(params);
  if (taskKey === 'regionManager') return await qyUniversalApproval(params);
  if (USER_ROLES.includes('regional_manager')) return await daquUniversalApproval(params);
  if (USER_ROLES.includes('Inspector_global')) return await dcyUniversalApproval(params);
  if (USER_ROLES.includes('patrol_global')) return await qyUniversalApproval(params);
  throw new Error('未匹配到对应的审批接口，请检查角色或工单taskKey');
};

/**
 * 统一跳转工单页面 支持事件回调+参数转义
 */
const navToOrderPage = (path: string, query = {}, events = {}) => {
  const queryStr = Object.keys(query).map(k => `${k}=${encodeURIComponent(query[k])}`).join('&');
  const url = `${path}${queryStr ? '?' + queryStr : ''}`;
  if(Object.keys(events).length) {
    uni.navigateTo({ url, events });
  } else {
    uni.redirectTo({ url });
  }
};

// ========== 基础状态 ==========
const loading = ref(true);
const activeTopTab = ref(0); // 顶部Tab激活索引
const activeImgTab = ref(0); // 图片分类Tab激活索引

// 顶部Tab列表
const topTabList = ref([
  {name: '工单详情'},
  {name: '流程节点'}
]);

// 流程节点数据
const processData = ref<any>({
  status: 2,
  activityNodes: [],
  formFieldsPermission: null,
  todoTask: null
});

// 图片分类Tab列表
const imgTabList = ref([
  {name: '开始', badge: {isDot: true}},
  {name: '进行中'},
  {name: '结束', badge: {isDot: true}},
  {name: '人员'},
  {name: '材料'}
]);

// 工单详情数据
const orderDetail = ref<any>({
  id: 0,
  busiLine: '',
  orderNo: '',
  orderName: '',
  sourceId: 0,
  sourceName: '',
  roadId: 0,
  roadName: '',
  streetId: '',
  streetName: '',
  curingLevelId: 0,
  curingLevelName: '',
  commitDate: 0,
  finishDate: 0,
  expectedFinishDate: 0,
  pressingType: 0,
  userId: 0,
  userName: '',
  companyId: 0,
  latLonType: 0,
  lat: 0,
  lon: 0,
  lonLatAddress: '',
  thirdWorkNo: '',
  thirdPushState: 0,
  buzStatus: null,
  status: 0,
  processInstanceId: '',
  remark: '',
  handleResult: '',
  createTime: 0,
  fileNames: null,
  coHandlers: null,
  coHandlersName: null,
  companyName: null,
  userMobile: null,
  taskId: '',
  taskName: '',
  taskKey: '',
  processDefinitionName: '',
  startTime: 0,
  endTime: 0,
  key_: '',
  problemsImgs: [],
  startImgs: [],
  processingImgs: [],
  endImgs: [],
  personImgs: [],
  materialImgs: []
});

const currentImgList = ref([])
const tabKeyMap = ['startImgs', 'processingImgs', 'endImgs', 'personImgs', 'materialImgs'];
const imgTabChange = (({index}: { index: number }) => {
  const currentKey = tabKeyMap[index]
  currentImgList.value = orderDetail.value[currentKey]
})

/**
 * 截取reason最多200字
 */
const getLimitReason = (reason: string | null | undefined) => {
  if (!reason) return '无处理说明';
  if (reason.length <= 200) return reason;
  return reason.substring(0, 200) + '...';
}

/**
 * 动态获取当前步骤索引
 */
const getCurrentStepIndex = () => {
  const {activityNodes} = processData.value;
  if (!activityNodes || !activityNodes.length) return 0;
  return activityNodes.length - 1;
}

/**
 * 获取工单详情
 */
const DetailQuery = async (taskIdStr: string) => {
  console.log('当前工单ID：', taskIdStr)
  try {
    loading.value = true;
    const tabType = Number(activeTab.value);
    let res: any;

    if (tabType === 0) {
      res = await getTodoTaskDetail({taskId: taskIdStr});
    } else if (tabType === 1) {
      res = await getMyTaskDetail({taskId: taskIdStr});
    } else if (tabType === 2) {
      res = await getDoneTaskDetail({taskId: taskIdStr});
    } else {
      uni.showToast({title: '无效的工单类型', icon: 'none'});
      return;
    }

    if (res) {
      orderDetail.value = res;
      currentImgList.value = orderDetail.value.startImgs
    }
  } catch (error) {
    console.error('获取工单详情失败：', error);
    uni.showToast({title: '加载失败，请重试', icon: 'none'});
  } finally {
    loading.value = false;
  }
};

// 页面加载参数
const taskId = ref('')
const activeTab = ref('')
const processInstanceId = ref('')

const activeTopTabClick = async (item: any) => {
  activeTopTab.value = item.index
  if (activeTopTab.value == 1) {
    let getData = {
      processInstanceId: processInstanceId.value,
    }
    const res = await getApprovalDetail(getData)
    if (res && res.activityNodes && res.activityNodes.length) {
      const filteredActivityNodes = res.activityNodes.filter(node => {
        return node.name !== '结束';
      });
      const formatActivityNodes = filteredActivityNodes.map(node => ({
        ...node,
        title: node.name
      }));
      processData.value = {
        ...res,
        activityNodes: formatActivityNodes
      };
    } else {
      processData.value = res;
    }
  }
}

// ========== 回退弹窗相关 ==========
const rejectModalShow = ref(false);
const rejectReason = ref('');
const currentRejectItem = ref<any>(null);
const rejectImgs = useUploadImgs({
  maxCount: 3,
  uploadText: '选择回退图片',
  sizeType: ['compressed'],
  formRef: null,
  fieldName: 'rejectImgs'
})

// ========== 验收弹窗相关 ==========
const acceptModalShow = ref(false);
const acceptRadioValue = ref('0');
const acceptReason = ref('');
const currentAcceptItem = ref<any>(null);
const acceptImgs = useUploadImgs({
  maxCount: 3,
  uploadText: '选择验收图片',
  sizeType: ['compressed'],
  formRef: null,
  fieldName: 'acceptImgs'
})

// ========== 重新提交工单 完整对齐列表页 ==========
const handleRenew = (item: any) => {
  if (!item?.id) {
    return showToast('工单信息异常，无法重新提交');
  }
  const tempKey = setOrderStorage(item, 'renew_order');
  if (!tempKey) return;

  const pageUrl = USER_ROLES.includes('patrol_global')
      ? '/pages-sub/problem/regional-order-manage/add-patrol-order'
      : '/pages-sub/problem/regional-order-manage/add-order';

  navToOrderPage(pageUrl, { isRenew: 1, tempKey });
};

// ========== 打开回退弹窗 ==========
const handleReject = (item: any) => {
  if (!item?.id) {
    return showToast('工单信息异常，无法回退');
  }
  currentRejectItem.value = item;
  rejectReason.value = '';
  rejectImgs.clearImgs();
  rejectModalShow.value = true;
};

// ========== 回退弹窗取消 ==========
const handleRejectModalCancel = () => {
  rejectModalShow.value = false;
  rejectReason.value = '';
  rejectImgs.clearImgs();
};

// ========== 确认回退工单 完整对齐列表页 ==========
const confirmReject = async () => {
  const reason = rejectReason.value.trim();
  if (!reason) return showToast('请填写回退原因');
  const item = currentRejectItem.value;
  if (!item?.id) return showToast('工单信息异常');

  uni.showLoading({title: '提交中...', mask: true});
  try {
    const requestData = {
      "returnImgs": rejectImgs.getSuccessImgUrls(),
      "workerDataId": item.id,
      "taskKey": item.taskKey,
      "taskId": item.taskId,
      "operateType": nextStepMap[item.taskKey].operateTypeNoPass,
      "agree": 1,
      "reason": reason
    };
    await callApprovalApi(requestData, item.taskKey);
    showToast('回退成功', 'success');
    handleRejectModalCancel();
    eventChannel.value.emit('needRefresh');
    uni.navigateBack({ delta: 1 });
  } catch (error: any) {
    console.error('回退工单失败：', error);
    showToast(error.msg || error.message || '回退失败，请重试');
  } finally {
    uni.hideLoading();
  }
};

// ========== 处理工单核心方法 完整对齐列表页+全BUG修复 ==========
const handleProcess = async (item: any) => {
  if (!item) return showToast('工单信息异常');
  const stepName = nextStepMap[item.taskKey]?.name;
  if (!stepName) return showToast('暂无处理权限或工单状态异常');

  uni.showLoading({title: '处理中...', mask: true});
  try {
    // 大区经理分配
    if (stepName === '大区经理分配') {
      const tempKey = setOrderStorage(item, 'distribute_order');
      tempKey && navToOrderPage('/pages-sub/problem/regional-order-manage/distribution-order', { tempKey });
    }
    // 养护员待实施
    else if (stepName === '养护员待实施') {
      const tempKey = setOrderStorage(item, 'maintain_order');
      tempKey && navToOrderPage('/pages-sub/problem/regional-order-manage/add-maintain-order', { tempKey });
    }
    // 督察员单子大区经理分配
    else if (stepName === '督察员单子大区经理分配') {
      const postData = {
        taskKey: item.taskKey, taskId: item.taskId, operateType:60, workerDataId:item.id,
        agree:0, reason:item.remark, roadId:item.roadId, roadName:item.roadName,
        pressingType:item.pressingType, orderName:item.orderName,
        expectedFinishDate: item.expectedFinishDate, busiLine:item.busiLine
      };
      await dcyUniversalApproval(postData);
      showToast('分配成功', 'success');
      eventChannel.value.emit('needRefresh');
      uni.navigateBack({ delta: 1 });
    }
    // 验收弹窗
    else if (['养护组长验收', '巡查员验收'].includes(stepName)) {
      currentAcceptItem.value = item;
      acceptReason.value = '';
      acceptRadioValue.value = '0';
      acceptModalShow.value = true;
    }
    // 发起人确认-结束工单
    else if (stepName === '发起人确认') {
      uni.hideLoading();
      uni.showModal({
        title: "结束工单",
        content: "请确定是否结束工单？",
        success: async (res) => {
          if (res.confirm) {
            const requestData = {
              workerDataId: item.id, taskKey: 'ylInspectorStart', taskId: item.taskId,
              operateType: 200, agree: 1, reason: '结束工单'
            };
            await callApprovalApi(requestData, item.taskKey);
            showToast('结束成功', 'success');
            eventChannel.value.emit('needRefresh');
            uni.navigateBack({ delta: 1 });
          }
        },
      });
    }
  } catch (error: any) {
    console.error('处理工单失败：', error);
    showToast(error.msg || error.message || '处理失败，请重试');
  } finally {
    uni.hideLoading();
  }
};

// ========== 验收弹窗取消 ==========
const handleAcceptModalCancel = () => {
  acceptModalShow.value = false;
  acceptReason.value = '';
  acceptRadioValue.value = '0';
  acceptImgs.clearImgs();
};

// ========== 验收弹窗确认 修复BUG+对齐列表页 ==========
const handleAcceptModalConfirm = async () => {
  const reason = acceptReason.value.trim();
  if (!reason) return showToast('请填写验收原因');
  if (reason.length > 200) return showToast('验收原因最多200字');

  const item = currentAcceptItem.value;
  if (!item?.id) return showToast('工单信息异常');

  uni.showLoading({title: '提交中...', mask: true});
  try {
    let postData: any = {}
    if (item?.taskKey == 'ylTeamLeaderConfirm') {
      postData = {
        returnImgs: acceptImgs.getSuccessImgUrls(),
        taskKey: item.taskKey,
        workerDataId: item.id,
        taskId: item.taskId,
        operateType: acceptRadioValue.value == 0 ? nextStepMap[item.taskKey].operateTypePass : nextStepMap[item.taskKey].operateTypeNoPass,
        reason
      }
    }
    if (item?.taskKey == 'ylInspector') {
      postData = {
        returnImgs: acceptImgs.getSuccessImgUrls(),
        taskKey: item.taskKey,
        taskId: item.taskId,
        workerDataId: item.id,
        operateType: acceptRadioValue.value == 0 ? nextStepMap[item.taskKey].operateTypePass : nextStepMap[item.taskKey].operateTypeNoPass,
        reason,
        agree: acceptRadioValue.value
      }
    }
    await callApprovalApi(postData, item.taskKey);
    showToast('提交成功', 'success');
    handleAcceptModalCancel();
    eventChannel.vlue.emit('needRefresh');
    uni.navigateBack({delta: 1});
  } catch (error: any) {
    console.error('验收失败：', error);
    showToast(error.msg || error.message || '验收提交失败，请重试');
  } finally {
    uni.hideLoading();
  }
};

// ========== 生命周期 ==========
onLoad((options: any) => {
  console.log('页面入参：', options)
  const {taskId: taskIdOpt, activeTab: activeTabOpt, processInstanceId: processInstanceIdOpt} = options;
  taskId.value = taskIdOpt || '';
  activeTab.value = activeTabOpt || '0';
  processInstanceId.value = processInstanceIdOpt;
  eventChannel.value = getCurrentPages()[getCurrentPages().length - 1].getOpenerEventChannel();
  DetailQuery(taskId.value);
});

onShow(() => {});
</script>

<style scoped lang="scss">
// 全局样式
.page-container {
  min-height: 100vh;
}

// 主内容容器
.main-content {
  padding-bottom: 80rpx;
}

// 顶部Tabs
.top-tabs {
}

// Tab内容区
.tab-content {
}

// 工单详情内容
.detail-content {
  .detail-cell-group {
    background-color: #fff;
    margin-bottom: 20rpx;
  }

  .cell-content-wrap {
  }

  .empty-text {
    color: #999;
    font-size: 26rpx;
  }
}

// 图片分类Tabs区块
.img-tabs-block {
  background-color: #fff;

  .img-tab-content {
    padding: 20rpx 15px ;
    text-align: center;

    .img-album {
    }

    .empty-img-text {
      height: 75px;
      line-height: 75px;
      color: #999;
      font-size: 28rpx;
    }
  }
}

// 流程节点区域
.process-content {
  .empty-process {
    margin-top: 100rpx;
  }

  .vertical-steps {
    background-color: #fff;
    padding: 20rpx;
    border-radius: 12rpx;
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }

  .step-content-wrap {
    width: 100%;
    box-sizing: border-box;

    .step-title {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 12rpx;

      .operator-name {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
        margin-left: 20rpx;
      }
    }

    .step-desc {
      font-size: 24rpx;
      color: #666;
      line-height: 1.6;
      margin-bottom: 12rpx;

      .time-line {
        .processing-tag {
          color: #f59e0b;
          margin-left: 10rpx;
        }
      }

      .reason-line {
        word-break: break-all;
      }
    }

    .step-album-wrap {
      padding: 10rpx 0;

      .step-album {
      }

      .no-img-tip {
        font-size: 24rpx;
        color: #999;
        margin-top: 10rpx;
      }
    }
  }
}

// 上传图片通用样式
.upload-wrap {
  margin-top: 20rpx;

  .upload-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
  }
}

.mt-20 {
  margin-top: 20rpx;
}

// 回退弹窗样式
.reject-modal-content {
  width: 100%;
  box-sizing: border-box;
  padding: 10rpx 0;
}

.reject-textarea {
  width: 100%;
}

// 验收弹窗样式
.accept-modal-content {
  width: 100%;
  box-sizing: border-box;
}

.radio-group-wrap {
  display: flex;
  align-items: center;
  gap: 40rpx;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.textarea-wrap {
  width: 100%;
  margin-top: 30rpx;
}

.mt-30 {
  margin-top: 30rpx;
}
// 针对 up-album 单图容器的样式
:deep .u-album__row__wrapper image {
  width: 70px !important;
  height: 70px !important;
}
</style>