<template>
  <transition name="report-detail-fade">
    <div v-if="visible" class="report-detail">
      <div class="detail-panel">
        <div class="detail-header">
          <div class="header-left">
            <el-button
              type="text"
              icon="el-icon-arrow-left"
              class="back-button"
              @click="handleBack"
            >
            </el-button>
            <div class="header-info">
              <div class="title">
                报告详情
              </div>
            </div>
          </div>
          <div class="header-right">
            <!-- 草稿状态：显示发起和修改按钮 -->
            <template v-if="reportDetail.status === 'DRAFT' && !isEditMode">
              <el-button @click="handleLaunch">
                发起
              </el-button>
              <el-button type="primary" @click="handleEdit">
                修改
              </el-button>
            </template>
            <!-- 编辑模式：显示保存和返回按钮 -->
            <template v-if="isEditMode">
              <el-button @click="handleCancelEdit">
                返回
              </el-button>
              <el-button type="primary" :loading="saving" @click="handleSave">
                保存
              </el-button>
            </template>
            <!-- 审批中状态：显示审批按钮 -->
            <el-button
              v-if="reportDetail.status === 'APPROVING' && !isEditMode"
              type="primary"
              @click="handleApprove"
            >
              审批
            </el-button>
          </div>
        </div>
        <div class="detail-content">
          <!-- 报告详情信息 -->
          <section class="block-section">
            <div class="section-title">
              报告信息
            </div>
            <!-- 只读模式 -->
            <template v-if="!isEditMode">
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">标题名称</span>
                  <span class="value">{{ reportDetail.title || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">厂家名称（全称）</span>
                  <span class="value">{{ reportDetail.manufacturerName || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">产品型号（全称）</span>
                  <span class="value">{{ reportDetail.modelName || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">厂家简称</span>
                  <span class="value">{{ reportDetail.manufacturerAbbreviation || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">产品型号简称</span>
                  <span class="value">{{ reportDetail.modelAbbreviation || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">产品编号</span>
                  <span class="value">{{ reportDetail.productNumber || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">领域/模块</span>
                  <span class="value">{{ reportDetail.module || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">板块</span>
                  <span class="value">{{ reportDetail.plate || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">平台</span>
                  <span class="value">{{ reportDetail.platform || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">系列</span>
                  <span class="value">{{ reportDetail.series || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">细分市场</span>
                  <span class="value">{{ reportDetail.marketSegment || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">项目名称</span>
                  <span class="value">{{ reportDetail.projectName || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">项目编号</span>
                  <span class="value">{{ reportDetail.projectNumber || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">创建人</span>
                  <span class="value">{{ reportDetail.createBy || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">创建时间</span>
                  <span class="value">{{ formatTime(reportDetail.uploadTime) || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">文件</span>
                  <span class="value">
                    <a v-if="reportDetail.filePath" href="javascript:void(0)" class="el-link el-link--primary" @click.stop="handleDownload(reportDetail)">{{ reportDetail.fileName }}</a>
                  </span>
                </div>
              </div>
              <div v-if="reportDetail.explanation" class="description-block">
                <span class="label">说明：</span>
                <span class="value">{{ reportDetail.explanation }}</span>
              </div>
            </template>
            <!-- 编辑模式 -->
            <template v-else>
              <el-form ref="editForm" :model="editFormData" label-width="150px">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="标题名称" prop="title">
                      <el-input v-model="editFormData.title" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="厂家名称（全称）" prop="manufacturerName">
                      <el-input v-model="editFormData.manufacturerName" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="产品型号（全称）" prop="modelName">
                      <el-input v-model="editFormData.modelName" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="厂家简称" prop="manufacturerAbbreviation">
                      <el-input v-model="editFormData.manufacturerAbbreviation" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="产品型号简称" prop="modelAbbreviation">
                      <el-input v-model="editFormData.modelAbbreviation" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="产品编号" prop="productNumber">
                      <el-input v-model="editFormData.productNumber" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="领域/模块" prop="module">
                      <el-input v-model="editFormData.module" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="板块" prop="plate">
                      <el-input v-model="editFormData.plate" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="平台" prop="platform">
                      <el-input v-model="editFormData.platform" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="系列" prop="series">
                      <el-input v-model="editFormData.series" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="细分市场" prop="marketSegment">
                      <el-input v-model="editFormData.marketSegment" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目名称" prop="projectName">
                      <el-input v-model="editFormData.projectName" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="项目编号" prop="projectNumber">
                      <el-input v-model="editFormData.projectNumber" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="附件上传" prop="attachments">
                  <el-upload
                    ref="upload"
                    :auto-upload="false"
                    :on-change="handleFileChange"
                    :on-remove="handleFileRemove"
                    :file-list="fileList"
                    :limit="1"
                    accept=".doc,.pdf,.xls,.xlsx,.ppt,.pptx"
                  >
                    <el-button type="primary" icon="el-icon-upload">
                      选择文件
                    </el-button>
                    <div slot="tip" class="el-upload__tip">
                      支持扩展名: .doc .pdf .xls .xlsx .ppt .pptx，仅支持上传一个文件
                    </div>
                  </el-upload>
                </el-form-item>
                <el-form-item label="说明" prop="explanation">
                  <el-input
                    v-model="editFormData.explanation"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-form>
            </template>
          </section>

          <!-- 审批流程 -->
          <section v-if="reportDetail.status && reportDetail.status !== 'DRAFT' && detail.flowId" class="block-section">
            <div class="section-title">
              审批流程
            </div>
            <div v-if="timelineNodes && timelineNodes.length > 0" class="approval-timeline">
              <el-timeline>
                <el-timeline-item
                  v-for="(node, index) in timelineNodes"
                  :key="index"
                  :color="getTimelineColor(node.result || node.status, index, timelineNodes.length)"
                >
                  <div class="timeline-item-content">
                    <div class="node-title">
                      {{ node.title }}
                    </div>
                    <div class="node-content">
                      <div class="node-info">
                        <div class="node-user">
                          {{ node.userName || '--' }}
                          <span class="node-time">
                            {{ formatTime(node.operateTime) }}
                          </span>
                        </div>
                      </div>
                      <div class="node-status" :class="getStatusClass(node.result || node.status)">
                        {{ setStatusText(node.result || node.status) }}
                      </div>
                      <div v-if="node.opinion" class="node-opinion">
                        审批意见：{{ node.opinion }}
                      </div>
                    </div>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
            <div v-else class="empty-progress">
              <span class="empty-text">暂无审批流程数据</span>
            </div>
          </section>
        </div>
      </div>

      <!-- 发起弹窗 -->
      <el-dialog
        title="发起"
        :visible.sync="launchDialogVisible"
        width="600px"
        :close-on-click-modal="false"
        append-to-body
        @close="handleLaunchDialogClose"
      >
        <div class="dialog-body-wrapper">
          <div class="approval-process-title">
            <div class="description-label">
              流程主题 <span class="required-mark">*</span>
            </div>
            <el-input
              v-model="launchProcessTitle"
              maxlength="100"
              show-word-limit
              placeholder="请输入流程主题"
            />
          </div>

          <div class="approval-workflow">
            <div class="workflow-title">
              审批环节
            </div>
            <div class="workflow-table">
              <table class="workflow-table-content">
                <thead>
                  <tr>
                    <th class="step-name-col">
                      环节名称
                    </th>
                    <th class="handler-col">
                      处理人
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(step, index) in launchWorkflowSteps" :key="index" class="workflow-row">
                    <td class="step-name-cell">
                      <span class="step-name">
                        {{ step.name }}
                        <span v-if="step.required" class="required-mark">*</span>
                      </span>
                    </td>
                    <td class="handler-cell">
                      <el-select
                        v-model="step.handlers"
                        multiple
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请选择"
                        :remote-method="(query) => handleLaunchRemoteSearch(query, index)"
                        :loading="step.loading"
                        class="handler-select"
                        @change="(value) => handleLaunchHandlerChange(index, value)"
                      >
                        <el-option
                          v-for="person in step.options"
                          :key="person.userNumber"
                          :value="person.userId"
                          :label="person.username"
                        >
                          <span class="username-text">{{ person.username }}</span>
                          <span class="user-id-text">{{ person.userNumber }}</span>
                        </el-option>
                      </el-select>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleLaunchDialogClose">
            取消
          </el-button>
          <el-button type="primary" :loading="launching" @click="handleLaunchSubmit">
            确定
          </el-button>
        </div>
      </el-dialog>

      <!-- 审批弹窗 -->
      <el-dialog
        title="审核"
        :visible.sync="approvalDialogVisible"
        width="500px"
        :close-on-click-modal="false"
        append-to-body
        @close="handleApprovalDialogClose"
      >
        <el-form ref="approvalForm" :model="approvalFormData" label-width="80px">
          <el-form-item label="审核">
            <el-radio-group v-model="approvalFormData.result">
              <el-radio label="PASS">
                通过
              </el-radio>
              <el-radio label="REJECT">
                退回
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="approvalFormData.opinion"
              type="textarea"
              :rows="4"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleApprovalDialogClose">
            取消
          </el-button>
          <el-button type="primary" :loading="approvalSubmitting" @click="handleApprovalSubmit">
            确定
          </el-button>
        </div>
      </el-dialog>
    </div>
  </transition>
</template>

<script>
import api from '@/api'
import { getUserId } from '@/utils'
export default {
  name: 'ReportDetail',
  props: {
    detail: {
      type: Object,
      default: () => ({})
    },
    visible: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      reportDetail: {},
      progress: [], // 保留用于兼容
      flowNodes: [], // 审批流程节点数据
      progressDetail: {}, // 审批流程详情数据
      approvalDialogVisible: false,
      approvalFormData: {
        result: '',
        opinion: ''
      },
      approvalSubmitting: false,
      isEditMode: false, // 编辑模式
      editFormData: {
        title: '',
        manufacturerName: '',
        modelName: '',
        manufacturerAbbreviation: '',
        modelAbbreviation: '',
        productNumber: '',
        module: '',
        plate: '',
        platform: '',
        series: '',
        marketSegment: '',
        projectName: '',
        projectNumber: '',
        explanation: '',
        fileUrl: '',
        fileName: ''
      },
      originalReportDetail: {}, // 保存原始数据，用于取消编辑时恢复
      selectedFile: null, // 选中的文件
      fileList: [], // 文件列表
      uploading: false, // 上传中状态
      saving: false, // 保存中状态
      launchDialogVisible: false, // 发起弹窗显示状态
      launchProcessTitle: '', // 流程主题
      launchWorkflowSteps: [
        {
          name: '校对',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '审核',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '批准',
          required: true,
          handlers: [],
          options: [],
          loading: false
        }
      ],
      launching: false // 发起中状态
    }
  },
  computed: {
    // 发起审批节点
    initiateNode() {
      if (!this.reportDetail || !this.reportDetail.createBy) {
        return null
      }
      return {
        userName: this.reportDetail.createBy,
        createTime: this.reportDetail.createTime,
        status: 'INITIATE',
        result: 'INITIATE'
      }
    },
    // 合并所有节点为时间线数据
    timelineNodes() {
      const nodes = []

      // 添加发起审批节点
      if (this.initiateNode) {
        nodes.push({
          title: '提交申请',
          userName: this.initiateNode.userName,
          operateTime: this.initiateNode.uploadTime,
          result: 'INITIATE',
          status: 'INITIATE',
          opinion: this.initiateNode.opinion || this.initiateNode.remark || this.initiateNode.comment || null
        })
      }

      // 使用 flowNodes 数据构建审批流程节点
      if (this.flowNodes && this.flowNodes.length > 0) {
        // 按照 nodeOrder 排序
        const sortedNodes = [...this.flowNodes].sort((a, b) => {
          const orderA = a.nodeOrder !== undefined && a.nodeOrder !== null ? Number(a.nodeOrder) : 0
          const orderB = b.nodeOrder !== undefined && b.nodeOrder !== null ? Number(b.nodeOrder) : 0
          return orderA - orderB
        })

        // 查找是否有 REJECT 节点
        const rejectIndex = sortedNodes.findIndex((node) => node.result === 'REJECT')

        let processedNodes = sortedNodes
        if (rejectIndex !== -1) {
          // 如果有 REJECT 节点，删除该节点后面的所有节点
          processedNodes = sortedNodes.slice(0, rejectIndex + 1)
        } else {
          // 如果没有 REJECT，将第一个 result 是"待审批"的节点改为 APPROVING
          const stayIndex = processedNodes.findIndex((node) => node.result === '待审批')
          if (stayIndex !== -1) {
            processedNodes = processedNodes.map((node, index) => {
              if (index === stayIndex) {
                return {
                  ...node,
                  result: 'APPROVING'
                }
              }
              return node
            })
          }
        }

        // 转换为时间线节点格式
        processedNodes.forEach((node) => {
          let result = 'APPROVING'
          let status = 'APPROVING'

          if (node.result) {
            if (node.result === 'REJECT') {
              result = 'REJECT'
              status = 'REJECT'
            } else if (node.result === 'APPROVING') {
              result = 'APPROVING'
              status = 'APPROVING'
            } else if (node.result === 'PASS') {
              result = 'PASS'
              status = 'PASS'
            } else if (node.result === '待审批') {
              result = 'STAY'
              status = 'STAY'
            }
          }

          // 处理审批意见：如果有 opinions 数组，取第一个；否则为空
          const opinion = node.opinions && Array.isArray(node.opinions) && node.opinions.length > 0
            ? node.opinions[0]
            : null

          // 处理用户名：优先使用 todoUserName（已处理人），如果没有则使用 undoUserName（待处理人）
          const userName = node.todoUserName || node.undoUserName || '--'

          nodes.push({
            title: node.node || '审批节点',
            userName: userName,
            operateTime: node.approvalTime || '',
            result: result,
            status: status,
            opinion: opinion
          })
        })
      } else if (this.progress && this.progress.length > 0) {
        // 兼容旧逻辑：如果没有 flowNodes，则使用原来的 progress 数据
        this.progress.forEach((stage) => {
          if (stage.steps && stage.steps.length > 0) {
            stage.steps.forEach((step) => {
              nodes.push({
                title: stage.title || '审批节点',
                userName: step.userName,
                operateTime: step.approvalTime || step.handleTime || step.createTime,
                result: step.result || step.status,
                status: step.result || step.status,
                opinion: step.opinion || step.remark || step.comment || null
              })
            })
          }
        })
      }

      return nodes
    }
  },
  watch: {
    detail: {
      handler(newVal) {
        if (newVal && newVal.reportId) {
          // 如果有 reportId，调用接口获取详情
          this.loadReportDetailFromApi(newVal.reportId, newVal.flowId)
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
  },
  methods: {
    setStatusText(result) {
      const statusMap = {
        'PASS': '通过',
        'REJECT': '驳回',
        'REFUSE': '驳回',
        'APPROVE': '批准',
        'APPROVING': '审批中',
        'PENDING': '待处理',
        'WAITING': '待处理',
        'INITIATE': '发起审批'
      }
      return statusMap[result] || result || '待处理'
    },
    formatTime(time) {
      if (!time) return '--'
      // 如果是时间戳，转换为日期格式
      if (typeof time === 'number') {
        const date = new Date(time)
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        })
      }
      // 如果已经是字符串格式，直接返回
      return time
    },
    getTimelineColor(result, stepIndex, totalSteps) {
      // 根据审批结果设置颜色
      if (result === 'PASS' || result === 'APPROVE') {
        return '#67C23A' // 绿色 - 通过
      } else if (result === 'REJECT' || result === 'REFUSE') {
        return '#F56C6C' // 红色 - 驳回
      } else if (result === 'APPROVING' || result === 'PENDING' || result === 'WAITING') {
        return '#E6A23C' // 橙色 - 审批中
      } else if (result === 'INITIATE') {
        return '#409EFF' // 蓝色 - 发起审批
      }
      // 默认颜色
      return '#409EFF' // 默认蓝色
    },
    getStatusClass(result) {
      const classMap = {
        'PASS': 'status-pass',
        'APPROVE': 'status-approve',
        'REJECT': 'status-reject',
        'REFUSE': 'status-reject',
        'APPROVING': 'status-approving',
        'PENDING': 'status-pending',
        'WAITING': 'status-pending',
        'INITIATE': 'status-initiate'
      }
      return classMap[result] || 'status-default'
    },
    loadReportDetail() {
      // 如果已经有详情数据，直接使用
      if (this.detail && Object.keys(this.detail).length > 0) {
        if (this.detail.reportId) {
          // 如果有 reportId，调用接口获取详情
          this.loadReportDetailFromApi(this.detail.reportId)
        } else {
          // 如果已经有完整的详情数据，直接使用
          this.reportDetail = this.detail
          // 如果flowId存在且状态不是草稿，加载审批流程
          if (this.detail.flowId && this.reportDetail.status && this.reportDetail.status !== 'DRAFT') {
            this.getApprovalSpet(this.detail.flowId)
          }
        }
      }
    },
    loadReportDetailFromApi(reportId, flowId) {
      console.log(reportId, flowId, 'reportId, flowId')

      if (!reportId) {
        return
      }
      const request = {
        ...api.GET_REPORT_DETAIL,
        params: {
          reportId: reportId
        },
        disableSuccessMsg: true
      }

      this.$request(request)
        .asyncThen((resp) => {
          this.reportDetail = resp.data || resp
          // 保存原始数据（用于编辑模式取消时恢复）
          this.originalReportDetail = JSON.parse(JSON.stringify(this.reportDetail))
          // 如果flowId存在且状态不是草稿，加载审批流程
          if (flowId && this.reportDetail.status && this.reportDetail.status !== 'DRAFT') {
            this.getApprovalSpet(flowId)
          }
        })
        .asyncErrorCatch((err) => {
          console.error('获取报告详情失败:', err)
          this.$message.error('获取报告详情失败，请重试')
        })
    },
    getApprovalSpet(flowId) {
      if (!flowId) {
        return
      }
      const reportId = this.reportDetail.reportId || this.reportDetail.id || this.detail.reportId || this.detail.id
      if (!reportId) {
        return
      }
      const request = {
        ...api.GET_PPROVAL_ALL,
        params: {
          flowId: flowId,
          templateId: reportId // 报告ID作为templateId参数
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          console.log('审批流程数据:', resp)
          const data = resp.data || resp
          // 保存流程详情
          this.progressDetail = {
            explanation: data.explanation || '',
            flowStatus: data.flowStatus || '',
            progressTitle: data.progressTitle || '',
            templateVersion: data.templateVersion || '',
            contentName: data.contentName || ''
          }
          // 保存流程节点
          this.flowNodes = data.flowNodes || []
        })
        .asyncErrorCatch((err) => {
          console.error('获取审批流程数据失败:', err)
          this.flowNodes = []
          this.progressDetail = {}
        })
    },
    handleBack() {
      this.$emit('close')
    },
    handleDownload(reportDetail) {
      const link = document.createElement('a')
      link.href = reportDetail.filePath
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    handleApprove() {
      this.approvalFormData = {
        result: '',
        opinion: ''
      }
      this.approvalDialogVisible = true
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.approvalForm) {
          this.$refs.approvalForm.clearValidate()
        }
      })
    },
    handleApprovalDialogClose() {
      this.approvalDialogVisible = false
      this.approvalFormData = {
        result: '',
        opinion: ''
      }
      // 清除表单验证
      if (this.$refs.approvalForm) {
        this.$refs.approvalForm.clearValidate()
      }
    },
    handleApprovalSubmit() {
      // 验证是否选择了审核结果
      if (!this.approvalFormData.result) {
        this.$message.warning('请选择审核结果（通过或退回）')
        return
      }

      if (!this.detail || !this.detail.flowId) {
        this.$message.error('缺少审批信息')
        return
      }

      // 构建提交数据
      const submitData = {
        flowId: this.detail.flowId,
        userId: getUserId(),
        result: this.approvalFormData.result, // 'PASS' 或 'REJECT'
        opinion: this.approvalFormData.opinion || ''
      }

      this.approvalSubmitting = true
      const request = {
        ...api.START_REPORT_APPROVAL,
        params: submitData,
        disableSuccessMsg: true
      }

      // 保存审批结果，用于判断是否返回
      const approvalResult = this.approvalFormData.result

      this.$request(request)
        .asyncThen((resp) => {
          this.approvalSubmitting = false
          this.handleApprovalDialogClose()
          // 重新加载审批流程
          if (this.detail.flowId) {
            this.getApprovalSpet(this.detail.flowId)
          }
          // 如果审批通过，返回上一级
          if (approvalResult === 'PASS') {
            this.$emit('refresh')
            this.handleBack()
          } else {
            // 如果退回，只刷新流程数据，不返回
          }
        })
        .asyncErrorCatch((err) => {
          console.error('审批提交失败:', err)
          this.approvalSubmitting = false
          this.$message.error('审批提交失败，请重试')
        })
        .finally(() => {
          this.approvalSubmitting = false
        })
    },
    // 对steps数组进行去重，优先保留有approvalTime的记录
    deduplicateSteps(steps) {
      if (!Array.isArray(steps) || steps.length === 0) {
        return []
      }

      // 使用Map来存储已见过的唯一标识和对应的记录
      const seen = new Map()
      const result = []

      steps.forEach(step => {
        // 生成唯一标识：优先使用id，如果没有id则使用多个字段组合
        let uniqueKey = null

        if (step.id) {
          // 如果有id，使用id作为唯一标识
          uniqueKey = `id_${step.id}`
        } else {
          // 如果没有id，使用多个字段组合作为唯一标识
          const userName = step.userName || step.operator || step.username || step.handlerName || step.handler || ''
          const approvalTime = step.approvalTime || step.handleTime || step.createTime || ''
          const stepResult = step.result || step.status || ''
          uniqueKey = `combo_${userName}_${approvalTime}_${stepResult}`
        }

        if (!uniqueKey) {
          return // 跳过无法生成唯一标识的记录
        }

        // 检查是否已存在相同唯一标识的记录
        if (seen.has(uniqueKey)) {
          // 如果已存在，比较两条记录，优先保留有approvalTime的记录
          const existingIndex = seen.get(uniqueKey)
          const existingStep = result[existingIndex]

          const currentHasTime = !!(step.approvalTime || step.handleTime || step.createTime)
          const existingHasTime = !!(existingStep.approvalTime || existingStep.handleTime || existingStep.createTime)

          // 如果当前记录有approvalTime而已存在的没有，则替换
          if (currentHasTime && !existingHasTime) {
            result[existingIndex] = step
          }
          // 如果两条都有或都没有，保留已存在的（第一条）
        } else {
          // 如果这个唯一标识还没有出现过，添加到结果中
          seen.set(uniqueKey, result.length)
          result.push(step)
        }
      })

      // 对所有记录的approvalTime进行格式化
      return result.map(step => {
        const formattedStep = { ...step }
        if (formattedStep.approvalTime) {
          formattedStep.approvalTime = this.formatTime(formattedStep.approvalTime)
        }
        if (formattedStep.handleTime) {
          formattedStep.handleTime = this.formatTime(formattedStep.handleTime)
        }
        if (formattedStep.createTime) {
          formattedStep.createTime = this.formatTime(formattedStep.createTime)
        }
        return formattedStep
      })
    },
    // 发起功能
    handleLaunch() {
      this.launchProcessTitle = this.reportDetail.title || ''
      // 重置审批环节
      this.launchWorkflowSteps = [
        {
          name: '校对',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '审核',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '批准',
          required: true,
          handlers: [],
          options: [],
          loading: false
        }
      ]
      this.launchDialogVisible = true
    },
    // 关闭发起弹窗
    handleLaunchDialogClose() {
      this.launchDialogVisible = false
      this.launchProcessTitle = ''
      // 重置审批环节
      this.launchWorkflowSteps = [
        {
          name: '校对',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '审核',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '批准',
          required: true,
          handlers: [],
          options: [],
          loading: false
        }
      ]
    },
    // 发起提交
    handleLaunchSubmit() {
      // 验证必填环节是否已选择处理人
      const requiredStepsWithoutHandlers = this.launchWorkflowSteps.filter(
        (step) => step.required && (!step.handlers || step.handlers.length === 0)
      )
      if (requiredStepsWithoutHandlers.length > 0) {
        const stepNames = requiredStepsWithoutHandlers.map((step) => step.name).join('、')
        this.$message.warning(`请为必填环节"${stepNames}"选择处理人`)
        return
      }

      if (!this.reportDetail.reportId && !this.reportDetail.id) {
        this.$message.error('缺少报告信息')
        return
      }

      // 流程主题必填
      const processTitle = (this.launchProcessTitle || '').trim()
      if (!processTitle) {
        this.$message.warning('请填写流程主题')
        return
      }

      const reportId = this.reportDetail.reportId || this.reportDetail.id
      if (!reportId) {
        this.$message.error('缺少报告ID')
        return
      }

      // 构建提交数据
      const submitData = {
        reportId: reportId,
        userId: getUserId(),
        processTitle: processTitle,
        proofreadUsers: this.launchWorkflowSteps[0].handlers,
        reviewUsers: this.launchWorkflowSteps[1].handlers,
        countersignUsers: [],
        approveUsers: this.launchWorkflowSteps[2].handlers
      }

      this.launching = true
      const request = {
        ...api.ADD_REPORT,
        params: submitData,
        disableSuccessMsg: true
      }

      this.$request(request)
        .asyncThen((resp) => {
          this.launching = false
          this.handleLaunchDialogClose()
          // 重新加载详情
          this.loadReportDetailFromApi(reportId, this.detail.flowId)
          this.$message({
            type: 'success',
            message: '发起成功'
          })
          // 触发刷新事件
          this.$emit('refresh')
        })
        .asyncErrorCatch((err) => {
          console.error('发起失败:', err)
          this.launching = false
          this.$message.error('发起失败，请重试')
        })
    },
    // 发起远程搜索人员
    handleLaunchRemoteSearch(query, stepIndex) {
      const step = this.launchWorkflowSteps[stepIndex]
      if (!query || query.trim() === '') {
        if (step.handlers && step.handlers.length > 0) {
          const selectedOptions = step.options.filter((opt) => step.handlers.includes(opt.userId))
          step.options = selectedOptions
        } else {
          step.options = []
        }
        return
      }

      step.loading = true
      const trimmedQuery = query.trim()
      const request = {
        ...api.GET_ALLUSERS,
        params: {
          name: trimmedQuery
        },
        disableSuccessMsg: true
      }

      this.$request(request)
        .asyncThen((resp) => {
          const respData = resp && resp.data
          let result = []
          if (Array.isArray(respData)) {
            result = respData
          } else if (respData && Array.isArray(respData.result)) {
            result = respData.result
          } else if (respData && respData.data && Array.isArray(respData.data)) {
            result = respData.data
          }
          const users = result
            .map((user) => ({
              userId: user.userId || user.id,
              username: user.username || user.name,
              userNumber: user.userNumber || user.userId || user.id
            }))
            .filter((user) => user.userId && user.userNumber)
          const existingIds = new Set(step.handlers || [])
          const filteredUsers = users.filter((user) => !existingIds.has(user.userId))
          const selectedOptions = (step.options || []).filter(
            (opt) => opt.userId && step.handlers && step.handlers.includes(opt.userId)
          )
          const optionsMap = new Map()
          selectedOptions.forEach((opt) => {
            if (opt.userNumber) {
              optionsMap.set(opt.userNumber, opt)
            }
          })
          filteredUsers.forEach((user) => {
            if (user.userNumber && !optionsMap.has(user.userNumber)) {
              optionsMap.set(user.userNumber, user)
            }
          })
          step.options = Array.from(optionsMap.values())
          step.loading = false
        })
        .asyncErrorCatch((err) => {
          console.error('搜索人员失败:', err)
          if (step.handlers && step.handlers.length > 0) {
            const selectedOptions = step.options.filter((opt) => step.handlers.includes(opt.userId))
            step.options = selectedOptions
          } else {
            step.options = []
          }
          step.loading = false
        })
    },
    handleLaunchHandlerChange(stepIndex, selectedIds) {
      // 处理人员选择变化
    },
    // 修改功能：进入编辑模式
    handleEdit() {
      // 保存原始数据
      this.originalReportDetail = JSON.parse(JSON.stringify(this.reportDetail))
      // 填充表单数据
      this.editFormData = {
        title: this.reportDetail.title || '',
        manufacturerName: this.reportDetail.manufacturerName || '',
        modelName: this.reportDetail.modelName || '',
        manufacturerAbbreviation: this.reportDetail.manufacturerAbbreviation || '',
        modelAbbreviation: this.reportDetail.modelAbbreviation || '',
        productNumber: this.reportDetail.productNumber || '',
        module: this.reportDetail.module || '',
        plate: this.reportDetail.plate || '',
        platform: this.reportDetail.platform || '',
        series: this.reportDetail.series || '',
        marketSegment: this.reportDetail.marketSegment || '',
        projectName: this.reportDetail.projectName || '',
        projectNumber: this.reportDetail.projectNumber || '',
        explanation: this.reportDetail.explanation || '',
        fileUrl: this.reportDetail.fileUrl || this.reportDetail.filePath || '',
        fileName: this.reportDetail.fileName || ''
      }
      // 如果有文件路径，显示在文件列表中
      if (this.reportDetail.fileUrl || this.reportDetail.filePath) {
        this.fileList = [
          {
            name: this.reportDetail.fileName || '文件',
            url: this.reportDetail.fileUrl || this.reportDetail.filePath
          }
        ]
      } else {
        this.fileList = []
      }
      this.selectedFile = null
      this.isEditMode = true
    },
    // 取消编辑：恢复只读状态
    handleCancelEdit() {
      // 恢复原始数据
      this.reportDetail = JSON.parse(JSON.stringify(this.originalReportDetail))
      // 清空表单数据
      this.editFormData = {
        title: '',
        manufacturerName: '',
        modelName: '',
        manufacturerAbbreviation: '',
        modelAbbreviation: '',
        productNumber: '',
        module: '',
        plate: '',
        platform: '',
        series: '',
        marketSegment: '',
        projectName: '',
        projectNumber: '',
        explanation: '',
        fileUrl: '',
        fileName: ''
      }
      this.fileList = []
      this.selectedFile = null
      this.isEditMode = false
      // 清除表单验证
      if (this.$refs.editForm) {
        this.$refs.editForm.clearValidate()
      }
    },
    // 文件变化
    handleFileChange(file, fileList) {
      const allowedTypes = ['.doc', '.pdf', '.xls', '.xlsx', '.ppt', '.pptx']
      const fileName = file.name.toLowerCase()
      const isValidType = allowedTypes.some((type) => fileName.endsWith(type))

      if (!isValidType) {
        this.$message.error('不支持的文件类型，仅支持 .doc .pdf .xls .xlsx .ppt .pptx')
        this.$refs.upload.handleRemove(file)
        return false
      }

      this.selectedFile = file && file.raw ? file.raw : null
      this.fileList = fileList.slice(-1)
    },
    // 文件移除
    handleFileRemove(file, fileList) {
      this.selectedFile = null
      this.fileList = []
    },
    // 文件上传
    handleFileUpload() {
      if (this.uploading || !this.selectedFile) {
        if (!this.selectedFile) {
          return Promise.resolve(null)
        }
        return Promise.resolve(null)
      }

      const file = this.selectedFile
      const formData = new FormData()
      formData.append('file', file)
      formData.append('createBy', getUserId())

      const request = {
        ...api.TEST_FILE_UPLOAD,
        params: formData,
        disableSuccessMsg: true
      }

      this.uploading = true
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在上传文件，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return this.$upload(request, null, false)
        .then((resp) => {
          console.log('文件上传成功:', resp)
          loadingInstance.close()
          let fileUrl = ''
          if (resp.data && resp) {
            const url = resp.data
            fileUrl = url
            this.editFormData.fileUrl = fileUrl
          }
          return fileUrl
        })
        .catch((err) => {
          console.error('文件上传失败:', err)
          loadingInstance.close()
          this.$message.error('文件上传失败，请重试')
          throw err
        })
        .finally(() => {
          if (loadingInstance) {
            loadingInstance.close()
          }
          this.uploading = false
        })
    },
    // 保存功能
    handleSave() {
      // 表单验证
      if (this.$refs.editForm) {
        this.$refs.editForm.validate((valid) => {
          if (!valid) {
            return false
          }
          this.submitEdit()
        })
      } else {
        this.submitEdit()
      }
    },
    // 提交编辑
    submitEdit() {
      const submitData = async () => {
        // 如果有新文件，先上传文件获取文件路径
        if (this.selectedFile) {
          try {
            const fileUrl = await this.handleFileUpload()
            this.editFormData.fileUrl = fileUrl || ''
            this.editFormData.fileName = this.selectedFile.name
          } catch (err) {
            console.error('文件上传失败:', err)
            this.$message.error('文件上传失败，请重试')
            return
          }
        }

        const reportId = this.reportDetail.reportId || this.reportDetail.id
        if (!reportId) {
          this.$message.error('缺少报告ID')
          return
        }

        const request = {
          ...api.EDIT_REPORT,
          params: {
            reportId: reportId,
            ...this.editFormData,
            createBy: getUserId(),
            userId: getUserId()
          }
        }

        this.saving = true
        this.$request(request)
          .asyncThen((resp) => {
            this.saving = false
            this.isEditMode = false
            // 重新加载详情
            this.loadReportDetailFromApi(reportId, this.detail.flowId)
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            // 触发刷新事件
            this.$emit('refresh')
          })
          .asyncErrorCatch((err) => {
            console.error('保存失败:', err)
            this.saving = false
            this.$message.error('保存失败，请重试')
          })
      }

      submitData()
    }
  }
}
</script>

<style lang="scss" scoped>
.report-detail {
  width: 100%;
  height: 100%;
  background: #fff;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  padding: 0;
  box-sizing: border-box;
  overflow-y: auto;

  .detail-panel {
    width: 100%;
    max-width: 1200px;
    background: #ffffff;
    border-radius: 12px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .detail-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24px 32px 16px 32px;
    border-bottom: 1px solid #ebeef5;

    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .back-button {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #606266;

      ::v-deep .el-icon-arrow-left {
        font-size: 16px;
      }
    }

    .header-info {
      display: flex;
      flex-direction: column;
      gap: 4px;

      .title {
        font-size: 20px;
        font-weight: 600;
        color: #303133;
      }

      .subtitle {
        font-size: 14px;
        color: #909399;
      }
    }
  }

  .detail-content {
    padding: 24px 32px 40px 32px;
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: auto;
    gap: 24px;
  }

  .block-section {
    border-radius: 8px;
    padding: 24px 24px 16px 24px;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 16px;
    }
  }

  .info-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    border: 1px solid #ebeef5;
    border-radius: 4px;
    overflow: hidden;

    .info-item {
      display: flex;
      flex-direction: row;
      border-right: 1px solid #ebeef5;
      border-bottom: 1px solid #ebeef5;

      &:nth-child(2n) {
        border-right: none;
      }

      &:nth-last-child(-n + 2) {
        border-bottom: none;
      }

      .label {
        font-size: 14px;
        color: #303133;
        background: #f5f7fa;
        padding: 12px 16px;
        min-width: 140px;
        width: 140px;
        text-align: right;
        border-right: 1px solid #ebeef5;
        font-weight: 500;
        flex-shrink: 0;
      }

      .value {
        font-size: 14px;
        color: #303133;
        padding: 12px 16px;
        flex: 1;
        word-break: break-word;
      }
    }
  }

  .description-block {
    display: flex;
    gap: 8px;
    font-size: 14px;
    color: #606266;
    margin-top: 16px;

    .label {
      color: #909399;
    }

    .value {
      flex: 1;
      white-space: pre-line;
      word-break: break-word;
    }
  }

  .approval-timeline {
    padding: 20px 0;

    ::v-deep .el-timeline {
      padding-left: 0;

      .el-timeline-item {
        padding-bottom: 24px;

        &:last-child {
          padding-bottom: 0;
        }

        .el-timeline-item__node {
          width: 12px;
          height: 12px;
          left: 0;
          top: 4px;
          border: 2px solid #fff;
          box-shadow: 0 0 0 2px #409eff;
        }

        .el-timeline-item__wrapper {
          top: 0;
          padding-left: 28px;

          .el-timeline-item__content {
            padding-top: 0;
          }
        }
      }
    }
  }

  .timeline-item-content {
    display: flex;
    flex-direction: column;
    gap: 0;

    .node-title {
      font-size: 14px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 8px;
    }

    .node-content {
      background: #f4f7fc;
      border-radius: 4px;
      padding: 12px;
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .node-info {
      display: flex;
      flex-direction: column;
      gap: 4px;
      font-size: 13px;
      color: #606266;
    }

    .node-user {
      color: #303133;
      font-weight: 500;
    }

    .node-time {
      color: #909399;
      font-size: 12px;
      margin-left: 8px;
    }

    .node-status {
      display: inline-block;
      font-size: 13px;
      font-weight: 500;
      border-radius: 2px;
      width: fit-content;

      &.status-initiate,
      &.status-pass,
      &.status-approve {
        color: #67c23a;
        background: transparent;
      }

      &.status-reject {
        color: #f56c6c;
        background: transparent;
      }

      &.status-approving,
      &.status-pending {
        color: #e6a23c;
        background: transparent;
      }

      &.status-default {
        color: #909399;
        background: transparent;
      }
    }

    .node-opinion {
      font-size: 13px;
      color: #000;
      line-height: 1.6;
    }
  }

  .empty-progress {
    text-align: center;
    padding: 40px 20px;
    color: #909399;
    font-size: 14px;

    .empty-text {
      display: inline-block;
    }
  }
}

.report-detail-fade-enter-active,
.report-detail-fade-leave-active {
  transition: opacity 0.2s ease;
}

.report-detail-fade-enter,
.report-detail-fade-leave-to {
  opacity: 0;
}

::v-deep .el-timeline-item__tail {
  left: 7px;
  top: 3px;
}

.dialog-body-wrapper {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.approval-process-title {
  margin-bottom: 20px;

  .description-label {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 8px;

    .required-mark {
      color: #f56c6c;
      margin-left: 4px;
    }
  }
}

.approval-workflow {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 20px;

  .workflow-title {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 8px;
  }

  .workflow-table {
    width: 100%;

    .workflow-table-content {
      width: 100%;
      border-collapse: collapse;
      border: 1px solid #ebeef5;

      thead {
        background: #f5f7fa;

        th {
          padding: 12px 16px;
          text-align: left;
          font-size: 14px;
          font-weight: 600;
          color: #303133;
          border-bottom: 1px solid #ebeef5;

          &.step-name-col {
            width: 120px;
          }

          &.handler-col {
            width: auto;
          }
        }
      }

      tbody {
        .workflow-row {
          &:not(:last-child) {
            border-bottom: 1px solid #ebeef5;
          }

          .step-name-cell {
            padding: 12px 16px;
            vertical-align: middle;

            .step-name {
              font-size: 14px;
              color: #303133;

              .required-mark {
                color: #f56c6c;
                margin-left: 4px;
              }
            }
          }

          .handler-cell {
            padding: 12px 16px;
            vertical-align: middle;

            .handler-select {
              width: 100%;
              min-width: 200px;

              ::v-deep .el-input__inner {
                height: 32px;
                line-height: 32px;
              }

              ::v-deep .el-tag {
                margin: 2px 4px 2px 0;
              }
            }
          }
        }
      }
    }
  }
}

.el-select-dropdown__item {
  display: flex !important;
  justify-content: space-between !important;
  padding-right: 20px !important;
}

.username-text {
  color: #303133 !important;
  display: inline-block;
  text-align: right !important;
}

.user-id-text {
  color: #909399 !important;
  display: inline-block;
  margin-left: 20px;
  text-align: right !important;
}

::v-deep .el-upload-dragger {
  width: 100%;
  height: 180px;
}

::v-deep .el-form-item {
  margin-bottom: 18px;
}
</style>
