<template>
  <transition name="approval-progress-fade">
    <div v-if="visible" class="approval-progress-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">
            <el-button v-if="fromTodo" @click="handleReturn">
              退回
            </el-button>
            <el-button v-if="fromTodo && canResend" :loading="resending" @click="handleResend">
              直送
            </el-button>
            <el-button v-if="fromTodo" type="primary" @click="handleSubmit">
              提交
            </el-button>
          </div>
        </div>
        <div class="detail-content">
          <section class="block-section">
            <div class="section-title">
              基础信息
            </div>
            <div class="info-grid">
              <!-- 流程主题单独一行 -->
              <div class="info-item-full">
                <span class="label">流程主题</span>
                <div v-if="!isEditingProcessTitle" class="value process-title-value-wrapper">
                  {{ showTopDetail.processTitle || '--' }}
                  <i
                    class="el-icon-edit process-title-edit-icon"
                    @click="handleEditProcessTitle"
                  ></i>
                </div>
                <div v-else class="process-title-input-wrapper">
                  <el-input
                    v-model="editingProcessTitle"
                    placeholder="请输入流程主题"
                    maxlength="100"
                    show-word-limit
                    class="process-title-input"
                  >
                    <template slot="suffix">
                      <i class="el-icon-check process-title-icon" @click="handleSaveProcessTitle"></i>
                      <i class="el-icon-close process-title-icon" @click="handleCancelProcessTitle"></i>
                    </template>
                  </el-input>
                </div>
              </div>
              <!-- 其他信息一行两个 -->
              <div class="info-row">
                <div class="info-item">
                  <span class="label">创建人</span>
                  <span class="value">{{ showTopDetail.createBy || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">创建时间</span>
                  <span class="value">{{
                    formatTime(showTopDetail.createTime) || '--'
                  }}</span>
                </div>
              </div>
              <div class="info-row">
                <div class="info-item">
                  <span class="label">当前环节</span>
                  <span class="value">{{ showTopDetail.currentNode || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">当前处理人</span>
                  <span class="value">{{ showTopDetail.currentProcessor || '--' }}</span>
                </div>
              </div>
            </div>
          </section>

          <section class="block-section">
            <div class="section-title">
              审批内容
            </div>
            <el-table :data="changeTable || []" border class="change-table">
              <el-table-column label="序号" type="index" width="60" />
              <el-table-column
                prop="subsystemName"
                label="子系统"
                min-width="120"
                show-overflow-tooltip
              />
              <el-table-column
                prop="parameterType"
                label="类型"
                min-width="120"
                show-overflow-tooltip
              />
              <el-table-column
                prop="partsName"
                label="零部件名称"
                min-width="140"
                show-overflow-tooltip
              />
              <el-table-column
                prop="parameterName"
                label="参数名称"
                min-width="140"
                show-overflow-tooltip
              />
              <el-table-column prop="unit" label="单位" min-width="80" show-overflow-tooltip />
              <el-table-column prop="remarks" label="备注" min-width="120" show-overflow-tooltip />
              <el-table-column prop="modifyDetails" label="变动说明" min-width="160">
                <template slot-scope="scope">
                  <span class="modify-details-text">
                    {{ scope.row.modifyDetails || '--' }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              v-if="changeTableTotal > 0"
              class="pagination-wrapper"
              :current-page="changeTablePageNumber"
              :page-size="changeTablePageSize"
              :total="changeTableTotal"
              layout="total, prev, pager, next, jumper"
              @current-change="handlePageChange"
            />
            <div v-if="progressDetail.description" class="description-block">
              <span class="label">说明：</span>
              <span class="value">{{ detailOption }}</span>
            </div>
          </section>

          <section 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="approvalDialogTitle"
        :visible.sync="approvalDialogVisible"
        width="600px"
        :close-on-click-modal="false"
        append-to-body
        @close="handleApprovalDialogClose"
      >
        <el-form
          ref="approvalForm"
          style="margin-top: 10px;"
          :model="approvalFormData"
          :rules="approvalFormRules"
          label-width="100px"
        >
          <el-form-item
            :label="approvalActionType === 'reject' ? '拒绝意见:' : '提交意见:'"
            prop="opinion"
          >
            <el-input
              v-model="approvalFormData.opinion"
              type="textarea"
              :rows="2"
              :placeholder="approvalActionType === 'reject' ? '请输入拒绝意见' : '请输入提交意见'"
            />
          </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>

      <!-- 退回节点选择弹窗 -->
      <el-dialog
        title="选择退回节点"
        :visible.sync="returnNodeDialogVisible"
        width="500px"
        :close-on-click-modal="false"
        append-to-body
        @close="handleReturnNodeDialogClose"
      >
        <div class="return-node-dialog-content">
          <div v-if="returnableNodes.length === 0" class="empty-hint">
            暂无可退回的节点
          </div>
          <el-radio-group
            v-else
            v-model="selectedReturnNode"
            class="return-node-list"
            @change="handleReturnNodeChange"
          >
            <el-radio
              v-for="node in returnableNodes"
              :key="node"
              :label="node"
              class="return-node-item"
            >
              <!-- <div class="node-info">
                <span class="node-title">{{ node }}</span>
              </div> -->
            </el-radio>
          </el-radio-group>
          <!-- 当选择"编制"节点时，显示意见输入框 -->
          <div v-if="selectedReturnNode === '编制'" class="return-opinion-section">
            <div class="opinion-label">
              退回意见:
            </div>
            <el-input
              v-model="returnOpinion"
              type="textarea"
              :rows="3"
              placeholder="请输入退回意见"
            />
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleReturnNodeDialogClose">
            取消
          </el-button>
          <el-button
            type="primary"
            :loading="returnSubmitting"
            :disabled="!selectedReturnNode"
            @click="handleReturnSubmit"
          >
            确定
          </el-button>
        </div>
      </el-dialog>
    </div>
  </transition>
</template>

<script>
import api from '@/api'
import { getUserId } from '@/utils'
export default {
  name: 'ApprovalProgressDetail',
  props: {
    detail: {
      type: Object,
      default: () => ({})
    },
    visible: {
      type: Boolean,
      default: true
    },
    fromTodo: {
      type: Boolean,
      default: false
    },
    createBy: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      changeTable: [],
      showTopDetail: {
        processTitle: '',
        createBy: '',
        createTime: '',
        currentNode: '',
        currentProcessor: ''
      },
      returnableNodes: [],
      progress: [], // 保留用于兼容
      flowNodes: [], // 审批流程节点数据
      progressDetailData: {}, // 审批流程详情数据
      detailOption: '',
      canResend: false,
      flowStatus: '',
      changeTableTotal: 0,
      changeTablePageNumber: 1,
      changeTablePageSize: 10,
      approvalDialogVisible: false,
      approvalActionType: '', // 'reject' 或 'submit'
      approvalDialogTitle: '审核',
      approvalFormData: {
        result: '',
        opinion: ''
      },
      approvalSubmitting: false,
      approvalFormRules: {
        // 意见改为非必填
      },
      // 退回节点选择相关
      returnNodeDialogVisible: false,
      selectedReturnNode: '',
      returnSubmitting: false,
      returnOpinion: '', // 退回意见（仅在选择编制节点时使用）
      resending: false, // 直送提交loading状态
      isEditingProcessTitle: false, // 是否正在编辑流程主题
      editingProcessTitle: '' // 正在编辑的流程主题值
    }
  },
  computed: {
    progressDetail() {
      // 优先使用从接口获取的数据，如果没有则使用默认值
      if (this.progressDetailData && Object.keys(this.progressDetailData).length > 0) {
        return {
          progressTitle: this.progressDetailData.progressTitle || '',
          contentName: this.progressDetailData.contentName || '',
          templateVersion: this.progressDetailData.templateVersion || '',
          explanation: this.progressDetailData.explanation || '',
          description:
            this.progressDetailData.explanation || this.progressDetailData.description || ''
        }
      }
      const defaultDetail = {
        approvalNumber: '',
        modelName: '',
        applicant: '',
        department: '',
        submitTime: '',
        description: '',
        changeTable: [],
        createBy: '',
        creationDate: '',
        progress: []
      }
      return Object.assign(defaultDetail, this.detail || {})
    },
    // 发起审批节点
    initiateNode() {
      if (!this.detail || !this.detail.createBy) {
        return null
      }
      return {
        userName: this.detail.createBy,
        createTime: this.detail.createdTime || this.detail.createTime,
        status: 'INITIATE',
        result: 'INITIATE'
      }
    },
    // 合并所有节点为时间线数据
    timelineNodes() {
      const nodes = []

      // 添加发起审批节点（无论 result 是什么都显示为已完成 PASS）
      // if (this.initiateNode) {
      //   nodes.push({
      //     title: '提交申请',
      //     userName: this.detail.createBy || this.detail.username || '--',
      //     operateTime: this.detail.createdTime || this.detail.createTime || '',
      //     result: 'PASS', // 发起审批节点无论 result 是什么都显示为已完成
      //     status: 'PASS',
      //     opinion: null
      //   })
      // }

      // 使用 flowNodes 数据构建审批流程节点
      if (this.flowNodes && this.flowNodes.length > 0) {
        // 按照接口返回的顺序，不进行排序
        const processedNodes = [...this.flowNodes]

        // 找到第一个"待审批"节点，将其改为"审批中"（跟是否有REJECT没关系）
        const stayIndex = processedNodes.findIndex((node) => node.result === '待审批')
        if (stayIndex !== -1) {
          processedNodes[stayIndex] = {
            ...processedNodes[stayIndex],
            result: 'APPROVING'
          }
        }

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

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

          // 处理审批意见：如果有 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
    },
    // 判断是否可以审批（只有从todo页面进入的才返回true）
    canApprove() {
      // 只有从todo页面进入的才返回true，其他情况都返回false
      return this.fromTodo
    },
    // 当前环节
    currentNode() {
      if (this.flowNodes && this.flowNodes.length > 0) {
        // 找到第一个"待审批"或"审批中"的节点
        const approvingNode = this.flowNodes.find(
          (node) => node.result === '待审批' || node.result === 'APPROVING'
        )
        if (approvingNode) {
          return approvingNode.node || '--'
        }
        // 如果都已完成，返回最后一个节点
        const lastNode = this.flowNodes[this.flowNodes.length - 1]
        return lastNode ? lastNode.node || '--' : '--'
      }
      return '--'
    },
    // 当前处理人
    currentProcessor() {
      if (this.flowNodes && this.flowNodes.length > 0) {
        // 找到第一个"待审批"或"审批中"的节点
        const approvingNode = this.flowNodes.find(
          (node) => node.result === '待审批' || node.result === 'APPROVING'
        )
        if (approvingNode) {
          // 优先使用待处理人，如果没有则使用已处理人
          return approvingNode.undoUserName || approvingNode.todoUserName || '--'
        }
      }
      return '--'
    }
  },
  mounted() {
    this.getCanResend()
    this.getApprovalChange()
    this.getApprovalSpet()
  },
  methods: {
    getCanResend() {
      if (!this.detail || !this.detail.flowId) {
        this.canResend = false
        return
      }
      const request = {
        ...api.GET_CAN_RESEND_APPROVAL,
        params: {
          flowId: this.detail.flowId
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          this.canResend = resp.data || false
        })
        .asyncErrorCatch((err) => {
          console.error('获取可重新发起审批权限失败:', err)
          this.canResend = false
        })
    },
    setStatusText(result) {
      const statusMap = {
        PASS: '通过',
        REJECT: '驳回',
        REFUSE: '驳回',
        APPROVE: '批准',
        APPROVING: '审批中',
        PENDING: '待处理',
        WAITING: '待处理',
        INITIATE: '发起审批',
        RETURN: '退回'
      }
      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' || result === 'RETURN') {
        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: 'status-return'
      }
      return classMap[result] || 'status-default'
    },
    getApprovalSpet() {
      if (!this.detail || !this.detail.flowId) {
        return
      }
      const request = {
        ...api.GET_PPROVAL_ALL,
        params: {
          flowId: this.detail.flowId,
          templateId: this.detail.templateId
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          console.log('审批流程数据:', resp)
          const data = resp.data || resp
          // 如果 flowStatus 是 REJECTED，强制设置当前环节为"草稿"，当前处理人为创建人
          const flowStatus = data.flowStatus || ''
          const createBy = data.createBy || ''
          this.showTopDetail = {
            processTitle: data.progressTitle || '',
            createBy: createBy,
            createTime: data.createTime || '',
            currentNode: flowStatus === 'REJECTED' ? '编制' : (data.currentNode || ''),
            currentProcessor: flowStatus === 'REJECTED' ? createBy : (data.processor || '')
          }
          // 保存流程状态
          this.flowStatus = flowStatus
          // 保存流程详情
          this.progressDetailData = {
            explanation: data.explanation || '',
            flowStatus: data.flowStatus || '',
            progressTitle: data.progressTitle || '',
            templateVersion: data.templateVersion || '',
            contentName: data.contentName || ''
          }
          // 处理说明信息
          this.detailOption = data.explanation || data.description || ''
          // 保存流程节点
          this.flowNodes = data.flowNodes || []
        })
        .asyncErrorCatch((err) => {
          console.error('获取审批流程数据失败:', err)
          this.flowNodes = []
          this.progressDetailData = {}
        })
    },
    getApprovalChange() {
      const request = {
        ...api.GET_APPROVAL_CHANGE,
        params: {
          flowId: this.detail.flowId,
          templateId: this.detail.templateId,
          pageNumber: this.changeTablePageNumber,
          pageSize: this.changeTablePageSize
        },
        disableSuccessMsg: true
      }
      this.$request(request).asyncThen((resp) => {
        console.log(resp)
        this.changeTable = resp.data.result
        this.changeTableTotal = resp.data.count
      })
    },
    handleBack() {
      this.$emit('close')
    },
    handlePageChange(page) {
      this.changeTablePageNumber = page
      this.getApprovalChange()
    },
    changeTypeClass(type) {
      if (type === 'create') return 'change-create'
      if (type === 'delete') return 'change-delete'
      if (type === 'update') return 'change-update'
      return 'change-default'
    },
    // 对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
      })
    },
    handleReject() {
      this.approvalActionType = 'reject'
      this.approvalDialogTitle = '拒绝'
      this.approvalFormData = {
        result: 'REJECT',
        opinion: '拒绝' // 默认值为"拒绝"
      }
      this.approvalDialogVisible = true
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.approvalForm) {
          this.$refs.approvalForm.clearValidate()
        }
      })
    },
    // 处理退回按钮点击
    handleReturn() {
      const request = {
        ...api.GET_CAN_RETURN_NODE,
        params: {
          flowId: this.detail.flowId
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          console.log(resp)
          // 在列表最前面添加"编制"节点作为默认选项
          const nodes = Array.isArray(resp.data) ? resp.data : []
          this.returnableNodes = ['编制', ...nodes]
        })
        .asyncErrorCatch((err) => {
          console.error('获取退回节点失败:', err)
          // 即使获取失败，也添加"编制"节点
          this.returnableNodes = ['编制']
        })
      this.selectedReturnNode = ''
      this.returnOpinion = ''
      this.returnNodeDialogVisible = true
    },
    // 关闭退回节点选择弹窗
    handleReturnNodeDialogClose() {
      this.returnNodeDialogVisible = false
      this.selectedReturnNode = ''
      this.returnOpinion = ''
    },
    // 处理退回节点选择变化
    handleReturnNodeChange() {
      // 如果不是"编制"节点，清空意见
      if (this.selectedReturnNode !== '编制') {
        this.returnOpinion = ''
      }
    },
    // 提交退回操作
    handleReturnSubmit() {
      if (!this.selectedReturnNode) {
        this.$message.warning('请选择要退回的节点')
        return
      }

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

      this.returnSubmitting = true

      // 如果选择的是"编制"节点，调用拒绝接口
      if (this.selectedReturnNode === '编制') {
        const submitData = {
          flowId: this.detail.flowId,
          userId: getUserId(),
          result: 'REJECT',
          opinion: this.returnOpinion || '' // 意见非必填，可以为空
        }

        const request = {
          ...api.HANDLE_APPROVAL,
          params: submitData,
          disableSuccessMsg: true
        }

        this.$request(request)
          .asyncThen((resp) => {
            this.handleReturnNodeDialogClose()
            // 重新加载审批流程和变更数据
            this.getApprovalSpet()
            this.getApprovalChange()
            // 通知父组件刷新数据
            this.$message({
              message: '拒绝成功',
              type: 'success'
            })
            this.$emit('refresh')
            this.returnSubmitting = false
          })
          .asyncErrorCatch((err) => {
            console.error('拒绝失败:', err)
            this.$message({
              message: err.message || '拒绝失败，请重试',
              type: 'error'
            })
            this.returnSubmitting = false
          })
          .finally(() => {
            this.returnSubmitting = false
          })
      } else {
        // 其他节点，调用退回接口
        // 获取流程发起人
        const createUserId = this.detail.createdById || ''
        if (!createUserId) {
          this.$message.error('无法获取流程发起人信息')
          this.returnSubmitting = false
          return
        }

        // 获取当前处理人
        const processUserId = getUserId()

        // 构建提交数据
        const submitData = {
          flowId: this.detail.flowId,
          nodeName: this.selectedReturnNode,
          createUserId: createUserId,
          processUserId: processUserId
        }

        const request = {
          ...api.RETURN_MODEL_APPROVAL,
          params: submitData,
          disableSuccessMsg: true
        }

        this.$request(request)
          .asyncThen((resp) => {
            this.handleReturnNodeDialogClose()
            // 重新加载审批流程和变更数据
            this.getApprovalSpet()
            this.getApprovalChange()
            // 通知父组件刷新数据
            this.$message({
              message: '退回成功',
              type: 'success'
            })
            this.$emit('refresh')
            this.returnSubmitting = false
          })
          .asyncErrorCatch((err) => {
            console.error('退回失败:', err)
            this.$message({
              message: err.message || '退回失败，请重试',
              type: 'error'
            })
            this.returnSubmitting = false
          })
          .finally(() => {
            this.returnSubmitting = false
          })
      }
    },
    handleSubmit() {
      this.approvalActionType = 'submit'
      this.approvalDialogTitle = '提交'
      this.approvalFormData = {
        result: 'PASS',
        opinion: '同意' // 默认值为"同意"
      }
      this.approvalDialogVisible = true
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.approvalForm) {
          this.$refs.approvalForm.clearValidate()
        }
      })
    },
    handleApprovalDialogClose() {
      this.approvalDialogVisible = false
      this.approvalActionType = ''
      this.approvalDialogTitle = '审核'
      this.approvalFormData = {
        result: '',
        opinion: ''
      }
      // 清除表单验证
      if (this.$refs.approvalForm) {
        this.$refs.approvalForm.clearValidate()
      }
    },
    handleApprovalSubmit() {
      // 表单验证
      this.$refs.approvalForm.validate((valid) => {
        if (!valid) {
          return false
        }

        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.HANDLE_APPROVAL,
          params: submitData,
          disableSuccessMsg: true
        }

        this.$request(request)
          .asyncThen((resp) => {
            this.handleApprovalDialogClose()
            // 重新加载审批流程和变更数据
            this.getApprovalSpet()
            this.getApprovalChange()
            // 通知父组件刷新数据
            this.$message({
              message: '审批提交成功',
              type: 'success'
            })
            this.$emit('refresh')
            this.approvalSubmitting = false
          })
          .asyncErrorCatch((err) => {
            console.error('审批提交失败:', err)
            this.$message({
              message: '审批提交失败，请重试',
              type: 'error'
            })
            this.approvalSubmitting = false
          })
          .finally(() => {
            this.approvalSubmitting = false
          })
      })
    },
    // 处理直送按钮点击
    handleResend() {
      if (!this.detail || !this.detail.templateId) {
        this.$message.error('缺少模板ID，无法执行直送操作')
        return
      }

      this.$confirm('确定要执行直送操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.resending = true
          const request = {
            ...api.RESTART_MODEL_APPROVAL,
            params: {
              templateId: this.detail.templateId,
              userId: getUserId()
            },
            disableSuccessMsg: true
          }

          this.$request(request)
            .asyncThen((resp) => {
              // 重新加载审批流程和变更数据
              this.getApprovalSpet()
              this.getApprovalChange()
              // 通知父组件刷新数据
              this.$message({
                message: '直送成功',
                type: 'success'
              })
              this.$emit('refresh')
              this.resending = false
            })
            .asyncErrorCatch((err) => {
              console.error('直送失败:', err)
              this.$message({
                message: err.message || '直送失败，请重试',
                type: 'error'
              })
              this.resending = false
            })
            .finally(() => {
              this.resending = false
            })
        })
        .catch(() => {
          // 取消操作
        })
    },
    // 开始编辑流程主题
    handleEditProcessTitle() {
      this.isEditingProcessTitle = true
      this.editingProcessTitle = this.showTopDetail.processTitle || ''
    },
    // 取消编辑流程主题
    handleCancelProcessTitle() {
      this.isEditingProcessTitle = false
      this.editingProcessTitle = ''
    },
    // 保存流程主题
    handleSaveProcessTitle() {
      if (!this.detail || !this.detail.flowId) {
        this.$message.error('缺少流程ID，无法保存')
        return
      }

      const newTitle = (this.editingProcessTitle || '').trim()
      if (!newTitle) {
        this.$message.warning('流程主题不能为空')
        return
      }

      this.$confirm(`确认修改主题为${newTitle}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const request = {
            ...api.EDIT_APPROVAL_PROCESS_TITLE,
            params: {
              flowId: this.detail.flowId,
              title: newTitle
            },
            disableSuccessMsg: true
          }

          this.$request(request)
            .asyncThen((resp) => {
              this.showTopDetail.processTitle = newTitle
              this.isEditingProcessTitle = false
              this.editingProcessTitle = ''
              this.$message({
                message: '修改成功',
                type: 'success'
              })
            })
            .asyncErrorCatch((err) => {
              console.error('修改流程主题失败:', err)
              this.$message({
                message: err.message || '修改失败，请重试',
                type: 'error'
              })
            })
        })
        .catch(() => {
          // 取消操作
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.approval-progress-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 {
    .label {
      font-size: 16px;
      color: #909399;
    }

    .value {
      font-size: 16px;
      color: #303133;
      font-weight: 500;
    }

    .info-item-full {
      display: flex;
      gap: 16px 24px;
      margin-bottom: 16px;
      .label {
        min-width: 100px;
      }
      .value {
        flex: 1;
      }

      .process-title-value-wrapper {
        display: flex;
        align-items: center;
        gap: 8px;

        .process-title-edit-icon {
          cursor: pointer;
          color: #909399;
          font-size: 14px;
          transition: color 0.3s;
          flex-shrink: 0;

          &:hover {
            color: #409eff;
          }
        }
      }

      .process-title-input-wrapper {
        flex: 1;

        .process-title-input {
          ::v-deep .el-input__suffix {
            display: flex;
            align-items: center;
            gap: 8px;
            padding-right: 8px;

            .process-title-icon {
              cursor: pointer;
              font-size: 16px;
              transition: color 0.3s;

              &.el-icon-check {
                color: #67c23a;

                &:hover {
                  color: #529b2e;
                }
              }

              &.el-icon-close {
                color: #909399;

                &:hover {
                  color: #606266;
                }
              }
            }
          }
        }
      }
    }

    .info-row {
      display: flex;
      gap: 16px 24px;
      margin-bottom: 16px;

      .info-item {
        flex: 1;
        display: flex;
        gap: 16px 24px;
        .label {
          min-width: 100px;
        }
      }
    }

    .theme-info-item {
      display: flex;
      gap: 16px 24px;
      margin-bottom: 16px;
      .value {
        flex: 1;
      }
    }

    .remain-info {
      display: flex;
      gap: 16px 24px;

      .info-item {
        flex: 1;
        display: flex;
        gap: 16px 24px;
      }
    }
  }

  .change-table {
    width: 100%;
    margin-bottom: 16px;

    ::v-deep .el-table__header-wrapper th {
      background: #f0f2f5;
      color: #606266;
      font-weight: 500;
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
    margin-bottom: 16px;
  }

  .modify-details-text {
    white-space: pre-line;
    word-break: break-word;
  }

  .change-tag {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    line-height: 1;
    background: #f4f4f5;
    color: #909399;
  }

  .change-create {
    background: #f0f9eb;
    color: #67c23a;
  }

  .change-update {
    background: #ecf5ff;
    color: #409eff;
  }

  .change-delete {
    background: #fef0f0;
    color: #f56c6c;
  }

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

    .label {
      color: #909399;
    }
  }

  .approval-timeline {
    padding: 20px 5px;
    max-height: 450px;
    overflow-y: auto;

    ::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;
      }

      &.status-return {
        color: #409eff;
        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;
    }
  }

  .return-node-dialog-content {
    padding: 10px 0;

    .empty-hint {
      text-align: center;
      padding: 40px 0;
      color: #909399;
      font-size: 14px;
    }

    .return-node-list {
      display: flex;
      flex-direction: column;
      gap: 12px;
      max-height: 300px;
      overflow-y: auto;
      margin-bottom: 16px;

      .return-node-item {
        display: flex;
        align-items: center;
        padding: 12px;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        transition: all 0.3s;

        &:hover {
          border-color: #409eff;
          background: #ecf5ff;
        }

        .node-info {
          display: flex;
          flex-direction: column;
          gap: 4px;
          margin-left: 8px;

          .node-title {
            font-size: 14px;
            font-weight: 500;
            color: #303133;
          }

          .node-user {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }

  }
}
.return-opinion-section {
      margin-top: 16px !important;
      border-top: 1px solid #ebeef5;

      .opinion-label {
        margin-bottom: 5px !important;
        margin-top: 5px !important;
        font-size: 14px;
        color: #606266;
        font-weight: 500;
      }
    }
.approval-progress-fade-enter-active,
.approval-progress-fade-leave-active {
  transition: opacity 0.2s ease;
}

.approval-progress-fade-enter,
.approval-progress-fade-leave-to {
  opacity: 0;
}

::v-deep .el-timeline-item__tail {
  left: 7px;
  top: 3px;
}
::v-deep .el-button {
  line-height: 0.85 !important;
}
</style>
