<template>
  <div class="request-page">
    <el-card class="form-card" shadow="never">
      <div slot="header" class="card-header">
        <span>出差详情</span>
        <div class="actions">
          <el-button size="mini" icon="el-icon-arrow-left" @click="$router.back()">返回</el-button>
          <el-button size="mini" icon="el-icon-refresh" @click="loadDetail">刷新</el-button>
        </div>
      </div>

      <div class="form-summary" v-loading="loading">
        <div class="summary-left">
          <div class="summary-title">{{ travel.travelType || '出差申请' }}</div>
          <div class="summary-sub">申请编号：{{ travel.bizId || '-' }} · 状态：<el-tag size="mini" :type="statusType(travel.status)">{{ statusText(travel.status) }}</el-tag></div>
        </div>
        <div class="summary-right">
          <div class="summary-item">
            <div class="k">申请人</div>
            <div class="v">{{ applicantText }}</div>
          </div>
          <div class="summary-item">
            <div class="k">目的地</div>
            <div class="v">{{ travel.destination || '-' }}</div>
          </div>
        </div>
      </div>

      <!-- 出差时间与行程 -->
      <div class="block-title">出差时间与行程</div>
      <el-card class="inner-card" shadow="never">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="开始时间">
            <span class="date-time">{{ formatDate(travel.startTime) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="结束时间">
            <span class="date-time">{{ formatDate(travel.endTime) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="出差类型">{{ travel.travelType || '-' }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ applicantText }}</el-descriptions-item>
          <el-descriptions-item label="目的地" :span="2">
            <span class="destination-text">{{ travel.destination || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="出差事由" :span="2">
            <div class="reason-content">{{ travel.reason || '未填写' }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 费用与收款信息 -->
      <div class="block-title">费用与收款信息</div>
      <el-card class="inner-card" shadow="never">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="预估费用">
            <span class="cost-text">{{ travel.estimatedCost != null ? '¥' + travel.estimatedCost : '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="收款人">{{ travel.payeeName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="开户行">{{ travel.bankName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="银行账号">{{ travel.bankAccount || '-' }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <div class="block-title">交通/住宿/行程附件</div>
      <el-card class="inner-card" shadow="never" v-loading="attachmentLoading">
        <div v-if="attachmentList.length > 0" class="attachment-list">
          <div v-for="file in attachmentList" :key="file.ossId" class="attachment-item">
            <div class="file-info">
              <i class="el-icon-document file-icon"></i>
              <div class="file-details">
                <div class="file-name">{{ file.originalName || file.fileName || `文件${file.ossId}` }}</div>
                <div class="file-meta">
                  <span v-if="file.fileSize">{{ formatFileSize(file.fileSize) }}</span>
                  <span v-if="file.createTime" class="file-time">{{ formatDate(file.createTime) }}</span>
                </div>
              </div>
            </div>
            <div class="file-actions">
              <el-button size="mini" type="text" @click="previewFile(file)">预览</el-button>
              <el-button size="mini" type="text" @click="downloadFile(file.ossId)">下载</el-button>
            </div>
          </div>
        </div>
        <div v-else class="empty">暂无附件</div>
      </el-card>

      <!-- 流程状态 -->
      <div class="block-title">回执附件</div>
      <el-card class="inner-card" shadow="never" v-loading="receiptAttachmentLoading">
        <div v-if="receiptAttachmentList.length > 0" class="attachment-list">
          <div v-for="file in receiptAttachmentList" :key="file.ossId" class="attachment-item">
            <div class="file-info">
              <i class="el-icon-document file-icon"></i>
              <div class="file-details">
                <div class="file-name">{{ file.originalName || file.fileName || `文件${file.ossId}` }}</div>
                <div class="file-meta">
                  <span v-if="file.fileSize">{{ formatFileSize(file.fileSize) }}</span>
                  <span v-if="file.createTime" class="file-time">{{ formatDate(file.createTime) }}</span>
                </div>
              </div>
            </div>
            <div class="file-actions">
              <el-button size="mini" type="text" @click="previewFile(file)">预览</el-button>
              <el-button size="mini" type="text" @click="downloadFile(file.ossId)">下载</el-button>
            </div>
          </div>
        </div>
        <div v-else class="empty">暂无回执附件</div>
      </el-card>

      <!-- 流程状态 -->
      <!-- <div class="block-title">流程状态</div>
      <el-card class="inner-card" shadow="never" v-loading="actionLoading">
        <div v-if="flowInstance" class="flow-status">
          <div class="status-item">
            <div class="status-label">流程状态</div>
            <div class="status-value">
              <el-tag :type="statusType(flowInstance.status)" size="small">
                {{ statusText(flowInstance.status) }}
              </el-tag>
            </div>
          </div>
          <div v-if="currentNode" class="status-item">
            <div class="status-label">当前节点</div>
            <div class="status-value">{{ currentNode.nodeName || currentNode.nodeId || '未知节点' }}</div>
          </div>
          <div v-if="currentTask" class="status-item">
            <div class="status-label">当前审批人</div>
            <div class="status-value">
              <el-tag type="warning" size="small">{{ currentTask.assigneeUserName || currentTask.assigneeUserId || '待分配' }}</el-tag>
            </div>
          </div>
        </div>
        <div v-else class="empty">暂无流程信息</div>
      </el-card> -->

      <div class="block-title">流转历史</div>
      <el-card class="inner-card" shadow="never" v-loading="actionLoading">
        <el-timeline v-if="actionList.length">
          <el-timeline-item
            v-for="(a, idx) in actionList"
            :key="idx"
            :timestamp="formatDate(a.createTime)"
            :type="actionType(a.action)"
          >
            <div class="timeline-row">
              <div class="t-main">
                <span class="t-action">{{ actionText(a.action) }}</span>
                <span class="t-user">· 办理人：{{ a.actionUserId || '-' }}</span>
              </div>
              <div class="t-remark" v-if="a.remark">{{ a.remark }}</div>
            </div>
          </el-timeline-item>
        </el-timeline>
        <div v-else class="empty">暂无流转记录</div>
      </el-card>

      <div class="block-title">审批操作</div>
      <el-card class="inner-card" shadow="never">
        <div class="hint-text">系统将自动识别你在该单据上的“当前待办任务”。若你不是当前办理人，将不会显示办理按钮。</div>
        <div v-if="currentTask" class="btn-row">
          <el-input v-model="actionRemark" type="textarea" :rows="3" placeholder="填写审批意见（可选）" />
          <div class="btn-row mt10">
            <el-button type="success" :loading="actionSubmitting" @click="submitTaskAction('approve')">通过</el-button>
            <el-button type="danger" :loading="actionSubmitting" @click="submitTaskAction('reject')">驳回</el-button>
            <el-button :loading="actionSubmitting" @click="submitTaskAction('withdraw')">撤回</el-button>
          </div>
        </div>
        <div v-else class="empty">当前无待办任务（可能已处理完成，或你不是当前审批人）</div>
      </el-card>

    </el-card>
  </div>
</template>

<script>
import {
  getTravelReq,
  listFlowAction,
  getTodoTaskByBiz,
  approveFlowTask,
  rejectFlowTask,
  withdrawFlowTask,
  listEmployee
} from '@/api/hrm'
import { queryInstanceByBiz, getFlowInstance, listFlowNode } from '@/api/hrm/flow'
import { listByIds } from '@/api/system/oss'

export default {
  name: 'TravelDetail',
  props: {
    bizId: { type: [String, Number], default: null },
    embedded: { type: Boolean, default: false }
  },
  name: 'HrmTravelDetail',
  data() {
    return {
      travel: {},
      employees: [],
      loading: false,
      actionLoading: false,
      actionList: [],
      currentTask: null,
      actionRemark: '',
      actionSubmitting: false,
      attachmentList: [],
      attachmentLoading: false,
      receiptAttachmentList: [],
      receiptAttachmentLoading: false,
      flowInstance: null, // 流程实例信息
      flowNodes: [], // 流程节点列表
      currentNode: null // 当前节点信息
    }
  },
  computed: {
    currentBizId() {
      return this.bizId || this.$route?.params?.bizId || this.$route?.query?.bizId || this.$route?.params?.id
    },
    applicantText() {
      const empId = this.travel.empId
      const emp = this.employees.find(e => String(e.empId) === String(empId))
      if (emp) {
        const name = emp.empName || emp.nickName || emp.userName || ''
        const no = emp.empNo ? ` · ${emp.empNo}` : ''
        const dept = emp.deptName ? ` · ${emp.deptName}` : ''
        return `${name || '员工'}${no}${dept}`.trim()
      }
      return empId ? `员工ID:${empId}` : '-'
    }
  },
  created() {
    this.loadEmployees()
    this.loadDetail()
  },
  methods: {
    loadEmployees() {
      listEmployee({ pageNum: 1, pageSize: 1000 }).then(res => {
        this.employees = res.rows || res.data || []
      })
    },
    statusText(status) {
      const map = { pending: '审批中', draft: '草稿', approved: '已通过', rejected: '已驳回', canceled: '已撤销' }
      return map[status] || status || '-'
    },
    statusType(status) {
      const map = { pending: 'warning', draft: 'info', approved: 'success', rejected: 'danger', canceled: 'info' }
      return map[status] || 'info'
    },
    formatDate(val) {
      if (!val) return '-'
      const d = new Date(val)
      const p = n => (n < 10 ? `0${n}` : n)
      return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
    },
    actionText(action) {
      const map = { submit: '提交', approve: '通过', reject: '驳回', withdraw: '撤回', cancel: '撤销' }
      return map[action] || action || '-'
    },
    actionType(action) {
      const map = { submit: 'primary', approve: 'success', reject: 'danger', withdraw: 'info', cancel: 'info' }
      return map[action] || 'info'
    },
    async loadDetail() {
      const bizId = this.currentBizId
      if (!bizId) {
        this.$message.warning('缺少bizId')
        return
      }
      this.loading = true
      try {
        const res = await getTravelReq(bizId)
        this.travel = res.data || {}
        // 加载流程实例信息
        await this.loadFlowInstance()
        this.loadActionsByInstId(this.travel.instId)
        await this.loadCurrentTask()
        this.loadAttachments()
        this.loadReceiptAttachments()
      } finally {
        this.loading = false
      }
    },
    async loadFlowInstance() {
      if (!this.travel.instId) {
        // 如果没有instId，尝试通过bizType和bizId查询
        try {
          const res = await queryInstanceByBiz('travel', this.currentBizId)
          const instances = res.data || []
          if (instances.length > 0) {
            this.flowInstance = instances[0]
            this.travel.instId = instances[0].instId
            // 加载流程节点信息
            await this.loadFlowNodes()
            // 根据当前节点ID查找节点信息
            if (this.flowInstance.currentNodeId) {
              this.currentNode = this.flowNodes.find(n => n.nodeId === this.flowInstance.currentNodeId) || null
            }
          }
        } catch (e) {
          console.error('加载流程实例失败:', e)
        }
      } else {
        // 如果有instId，直接加载
        try {
          const res = await getFlowInstance(this.travel.instId)
          this.flowInstance = res.data || null
          // 加载流程节点信息
          await this.loadFlowNodes()
          // 根据当前节点ID查找节点信息
          if (this.flowInstance && this.flowInstance.currentNodeId) {
            this.currentNode = this.flowNodes.find(n => n.nodeId === this.flowInstance.currentNodeId) || null
          }
        } catch (e) {
          console.error('加载流程实例失败:', e)
        }
      }
    },
    async loadFlowNodes() {
      if (!this.flowInstance || !this.flowInstance.tplId) {
        this.flowNodes = []
        return
      }
      try {
        const res = await listFlowNode({ tplId: this.flowInstance.tplId, pageNum: 1, pageSize: 500 })
        this.flowNodes = res.rows || res.data || []
      } catch (e) {
        console.error('加载流程节点失败:', e)
        this.flowNodes = []
      }
    },
    async loadAttachments() {
      // 申请附件：accessoryApplyIds
      const fileIds = this.travel.accessoryApplyIds
      if (!fileIds) {
        this.attachmentList = []
        return
      }
      const ids = String(fileIds).split(',').map(id => id.trim()).filter(Boolean)
      if (ids.length === 0) {
        this.attachmentList = []
        return
      }
      this.attachmentLoading = true
      try {
        const res = await listByIds(ids)
        this.attachmentList = res.data || []
      } catch (e) {
        this.$message.error('加载申请附件失败：' + (e.message || '未知错误'))
        this.attachmentList = []
      } finally {
        this.attachmentLoading = false
      }
    },
    async loadReceiptAttachments() {
      // 回执附件：accessoryReceiptIds
      const fileIds = this.travel.accessoryReceiptIds
      if (!fileIds) {
        this.receiptAttachmentList = []
        return
      }
      const ids = String(fileIds).split(',').map(id => id.trim()).filter(Boolean)
      if (ids.length === 0) {
        this.receiptAttachmentList = []
        return
      }
      this.receiptAttachmentLoading = true
      try {
        const res = await listByIds(ids)
        this.receiptAttachmentList = res.data || []
      } catch (e) {
        this.$message.error('加载回执附件失败：' + (e.message || '未知错误'))
        this.receiptAttachmentList = []
      } finally {
        this.receiptAttachmentLoading = false
      }
    },
    formatFileSize(bytes) {
      if (!bytes) return '-'
      const units = ['B', 'KB', 'MB', 'GB']
      let size = Number(bytes)
      let unitIndex = 0
      while (size >= 1024 && unitIndex < units.length - 1) {
        size /= 1024
        unitIndex++
      }
      return `${size.toFixed(2)} ${units[unitIndex]}`
    },
    previewFile(file) {
      if (file.url) {
        window.open(file.url, '_blank')
      } else {
        this.$message.warning('文件URL不存在')
      }
    },
    downloadFile(ossId) {
      window.open(`/system/oss/download/${ossId}`, '_blank')
    },
    loadActionsByInstId(instId) {
      if (!instId) {
        this.actionList = []
        return
      }
      this.actionLoading = true
      listFlowAction({ instId, pageNum: 1, pageSize: 200 })
        .then(res => {
          this.actionList = res.rows || res.data || []
        })
        .finally(() => {
          this.actionLoading = false
        })
    },
    async loadCurrentTask() {
      try {
        const res = await getTodoTaskByBiz('travel', this.currentBizId)
        this.currentTask = res?.data || null
      } catch (e) {
        this.currentTask = null
      }
    },
    submitTaskAction(type) {
      if (!this.currentTask || !this.currentTask.taskId) return
      this.actionSubmitting = true
      const payload = { remark: this.actionRemark }
      const apiMap = { approve: approveFlowTask, reject: rejectFlowTask, withdraw: withdrawFlowTask }
      apiMap[type](this.currentTask.taskId, payload)
        .then(() => {
          this.$message.success('操作成功')
          this.loadDetail()
        })
        .finally(() => {
          this.actionSubmitting = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.request-page {
  padding: 16px 20px 32px;
  background: #f8f9fb;
}
.form-card {
  max-width: 980px;
  margin: 0 auto;
  border: 1px solid #d7d9df;
  border-radius: 12px;
  background: #ffffff;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 700;
  color: #2b2f36;
}
.actions {
  display: flex;
  gap: 8px;
}
.block-title {
  margin: 12px 0 8px;
  padding-left: 10px;
  font-weight: 700;
  color: #2f3440;
  border-left: 3px solid #9aa3b2;
}
.hint-text {
  margin: 6px 0 10px;
  font-size: 12px;
  color: #8a8f99;
}
.form-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  padding: 12px 12px;
  margin-bottom: 12px;
  border: 1px solid #e6e8ed;
  border-radius: 10px;
  background: linear-gradient(180deg, #ffffff 0%, #fbfcfe 100%);
}
.summary-title {
  font-size: 16px;
  font-weight: 800;
  color: #2b2f36;
}
.summary-sub {
  margin-top: 4px;
  font-size: 12px;
  color: #8a8f99;
}
.summary-right {
  display: flex;
  gap: 16px;
}
.summary-item .k {
  font-size: 12px;
  color: #8a8f99;
}
.summary-item .v {
  margin-top: 2px;
  font-weight: 700;
  color: #2b2f36;
}
.inner-card {
  border: 1px solid #e6e8ed;
}
.empty {
  color: #a0a3ad;
  font-size: 13px;
  padding: 10px 4px;
}
.timeline-row .t-main {
  font-weight: 600;
  color: #2b2f36;
}
.timeline-row .t-remark {
  margin-top: 4px;
  color: #606266;
  font-size: 13px;
}
.btn-row {
  display: flex;
  gap: 10px;
}
.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  border: 1px solid #e6e8ed;
  border-radius: 8px;
  background: #fafbfc;
}
.file-info {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}
.file-icon {
  font-size: 24px;
  color: #9aa3b2;
}
.file-details {
  flex: 1;
}
.file-name {
  font-weight: 600;
  color: #2b2f36;
  margin-bottom: 4px;
}
.file-meta {
  font-size: 12px;
  color: #8a8f99;
  display: flex;
  gap: 12px;
}
.date-time {
  font-weight: 600;
  color: #2b2f36;
}
.destination-text {
  font-weight: 600;
  color: #2b2f36;
  font-size: 14px;
}
.cost-text {
  font-weight: 700;
  color: #e6a23c;
  font-size: 16px;
}
.reason-content {
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  color: #2b2f36;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}
.info-section {
  padding: 12px;
  border: 1px solid #e6e8ed;
  border-radius: 8px;
  background: #fafbfc;
}
.info-label {
  font-size: 13px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 6px;
}
.info-label i {
  color: #9aa3b2;
}
.info-content {
  min-height: 40px;
}
.info-text {
  color: #2b2f36;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}
.info-placeholder {
  color: #c0c4cc;
  font-size: 12px;
  font-style: italic;
}
.remark-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e6e8ed;
}
.remark-label {
  font-size: 13px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 8px;
}
.remark-content {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  color: #2b2f36;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}
.file-time {
  margin-left: 8px;
}
.file-actions {
  display: flex;
  gap: 8px;
}
.flow-status {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.status-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  border: 1px solid #e6e8ed;
  border-radius: 6px;
  background: #fafbfc;
}
.status-label {
  font-size: 13px;
  font-weight: 600;
  color: #606266;
  min-width: 80px;
}
.status-value {
  flex: 1;
  color: #2b2f36;
  font-weight: 500;
}
@media (max-width: 1200px) {
  .summary-right {
    display: none;
  }
}
</style>

