<template>
  <el-dialog 
    title="报销申请详情" 
    :visible.sync="visible" 
    :close-on-click-modal="false"
    class="NCC-dialog NCC-dialog_center" 
    width="1200px"
    @close="handleClose"
  >
    <div class="detail-content" v-loading="loading">
      <!-- 表单信息卡片 -->
      <el-card class="info-card" shadow="hover" v-if="formData">
        <div slot="header" class="card-header">
          <i class="el-icon-document"></i>
          <span class="card-title">申请信息</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label class="info-label">申请编号：</label>
              <span class="info-value">{{ formData.id || '无' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label class="info-label">申请人编号：</label>
              <span class="info-value">{{ formData.applicationUserId || '无' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label class="info-label">申请人姓名：</label>
              <span class="info-value">{{ formData.applicationUserName || '无' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label class="info-label">申请门店ID：</label>
              <span class="info-value">{{ formData.applicationStoreId || '无' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label class="info-label">申请时间：</label>
              <span class="info-value">{{ formatDateTime(formData.applicationTime) || '无' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label class="info-label">总金额：</label>
              <span class="info-value amount">{{ formatMoney(formData.amount) || '无' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label class="info-label">审批状态：</label>
              <el-tag 
                :type="getStatusType(formData.approveStatus)"
                size="small"
              >
                {{ formData.approveStatus || '无' }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label class="info-label">购买记录编号：</label>
              <span class="info-value">{{ formData.purchaseRecordsId || '无' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 审批流程卡片 -->
      <el-card class="info-card" shadow="hover" v-if="nodes && nodes.length > 0">
        <div slot="header" class="card-header">
          <i class="el-icon-s-order"></i>
          <span class="card-title">审批流程</span>
        </div>
        <div class="approval-flow">
          <div 
            v-for="(node, index) in nodes" 
            :key="node.nodeId" 
            class="flow-node"
            :class="{
              'node-active': node.nodeOrder === currentNodeOrder,
              'node-completed': node.nodeOrder < currentNodeOrder,
              'node-pending': node.nodeOrder > currentNodeOrder
            }"
          >
            <div class="node-header">
              <div class="node-order">{{ node.nodeOrder }}</div>
              <div class="node-info">
                <div class="node-name">{{ node.nodeName || '无' }}</div>
                <div class="node-type">
                  <el-tag size="mini" :type="node.approvalType === '会签' ? 'success' : 'warning'">
                    {{ node.approvalType || '无' }}
                  </el-tag>
                  <el-tag size="mini" type="info" v-if="node.isRequired === 1">必审</el-tag>
                </div>
              </div>
            </div>
            
            <!-- 审批人列表 -->
            <div class="approvers-list">
              <div class="approvers-label">审批人：</div>
              <div class="approvers-items">
                <el-tag 
                  v-for="approver in node.approvers" 
                  :key="approver.userId"
                  size="small"
                  style="margin-right: 8px; margin-bottom: 4px;"
                >
                  {{ approver.userName || '无' }}
                </el-tag>
              </div>
            </div>

            <!-- 审批记录 -->
            <div class="approval-records" v-if="node.approvalRecords && node.approvalRecords.length > 0">
              <div class="records-label">审批记录：</div>
              <div class="records-list">
                <div 
                  v-for="(record, recordIndex) in node.approvalRecords" 
                  :key="recordIndex"
                  class="record-item"
                >
                  <div class="record-header">
                    <span class="record-approver">{{ record.approverName || '无' }}</span>
                    <el-tag 
                      size="mini" 
                      :type="getRecordType(record.approvalResult)"
                    >
                      {{ record.approvalResult || '无' }}
                    </el-tag>
                  </div>
                  <div class="record-opinion" v-if="record.approvalOpinion">
                    意见：{{ record.approvalOpinion }}
                  </div>
                  <div class="record-time" v-if="record.approvalTime">
                    时间：{{ formatDateTime(record.approvalTime) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 当前审批人信息 -->
      <el-card class="info-card" shadow="hover" v-if="currentApprovers && currentApprovers.length > 0">
        <div slot="header" class="card-header">
          <i class="el-icon-user-solid"></i>
          <span class="card-title">当前审批人</span>
        </div>
        <div class="current-approvers">
          <el-tag 
            v-for="approver in currentApprovers" 
            :key="approver.userId"
            type="warning"
            size="medium"
            style="margin-right: 8px;"
          >
            {{ approver.userName || '无' }}
          </el-tag>
        </div>
      </el-card>

      <!-- 退回原因 -->
      <el-card class="info-card" shadow="hover" v-if="returnedReason">
        <div slot="header" class="card-header">
          <i class="el-icon-warning"></i>
          <span class="card-title">退回原因</span>
        </div>
        <div class="returned-reason">
          {{ returnedReason }}
        </div>
      </el-card>

      <!-- 审批操作区域 -->
      <el-card class="info-card" shadow="hover" v-if="canApprove">
        <div slot="header" class="card-header">
          <i class="el-icon-edit"></i>
          <span class="card-title">审批操作</span>
        </div>
        <el-form :model="approvalForm" label-width="100px" label-position="right">
          <el-form-item label="审批结果" required>
            <el-radio-group v-model="approvalForm.result">
              <el-radio label="通过">通过</el-radio>
              <el-radio label="不通过">不通过</el-radio>
              <el-radio label="退回">退回</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审批意见">
            <el-input 
              v-model="approvalForm.opinion" 
              type="textarea" 
              :rows="4"
              placeholder="请输入审批意见"
            />
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关 闭</el-button>
      <el-button 
        type="primary" 
        @click="handleApprove"
        :loading="approving"
        v-if="canApprove"
      >
        提交审批
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'DetailDialog',
  data() {
    return {
      visible: false,
      loading: false,
      approving: false,
      formData: null,
      nodes: [],
      currentApprovers: [],
      currentNodeOrder: 0,
      approvalStatus: '',
      returnedReason: null,
      approvalForm: {
        result: '通过',
        opinion: ''
      }
    }
  },
  computed: {
    canApprove() {
      // 判断是否可以审批：状态为"审批中"且当前用户是当前审批人
      if (this.approvalStatus !== '审批中') {
        return false
      }
      // 这里可以根据实际登录用户信息判断
      // 暂时返回true，实际应该判断当前登录用户是否在currentApprovers中
      return true
    }
  },
  methods: {
    init(id) {
      this.visible = true
      this.loading = true
      this.formData = null
      this.nodes = []
      this.currentApprovers = []
      this.currentNodeOrder = 0
      this.approvalStatus = ''
      this.returnedReason = null
      this.approvalForm = {
        result: '通过',
        opinion: ''
      }
      this.getDetail(id)
    },

    async getDetail(id) {
      try {
        const response = await request({
          url: `/api/Extend/LqReimbursementApplication/${id}`,
          method: 'GET'
        })

        if (response.code === 200 && response.data) {
          this.formData = response.data.form || null
          this.nodes = response.data.nodes || []
          this.currentApprovers = response.data.currentApprovers || []
          this.currentNodeOrder = response.data.currentNodeOrder || 0
          this.approvalStatus = response.data.approvalStatus || ''
          this.returnedReason = response.data.returnedReason || null
        } else {
          this.$message.error(response.msg || '获取详情失败')
        }
      } catch (error) {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败')
      } finally {
        this.loading = false
      }
    },

    async handleApprove() {
      if (!this.approvalForm.result) {
        this.$message.warning('请选择审批结果')
        return
      }

      this.approving = true
      try {
        const response = await request({
          url: `/api/Extend/LqReimbursementApplication/${this.formData.id}/Actions/Approve`,
          method: 'POST',
          data: {
            result: this.approvalForm.result,
            opinion: this.approvalForm.opinion || ''
          }
        })

        if (response.code === 200) {
          this.$message.success('审批成功')
          this.visible = false
          this.$emit('refresh')
        } else {
          this.$message.error(response.msg || '审批失败')
        }
      } catch (error) {
        console.error('审批失败:', error)
        this.$message.error('审批失败')
      } finally {
        this.approving = false
      }
    },

    handleClose() {
      this.visible = false
      this.formData = null
      this.nodes = []
      this.currentApprovers = []
      this.currentNodeOrder = 0
      this.approvalStatus = ''
      this.returnedReason = null
      this.approvalForm = {
        result: '通过',
        opinion: ''
      }
    },

    formatMoney(amount) {
      if (!amount) return '无'
      return `¥${Number(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })}`
    },

    formatDateTime(dateTime) {
      if (!dateTime) return '无'
      // 如果是时间戳（数字），需要转换
      if (typeof dateTime === 'number') {
        const date = new Date(dateTime)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }
      // 如果是字符串，直接返回
      const date = new Date(dateTime)
      if (isNaN(date.getTime())) return dateTime
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    getStatusType(status) {
      const statusMap = {
        '待审批': 'info',
        '审批中': 'warning',
        '已通过': 'success',
        '未通过': 'danger',
        '已退回': 'warning'
      }
      return statusMap[status] || ''
    },

    getRecordType(result) {
      const typeMap = {
        '待审批': 'info',
        '通过': 'success',
        '不通过': 'danger',
        '退回': 'warning'
      }
      return typeMap[result] || ''
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.info-card {
  margin-bottom: 20px;

  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #303133;

    i {
      font-size: 18px;
      color: #409EFF;
    }
  }

  .info-item {
    margin-bottom: 16px;
    display: flex;
    align-items: center;

    .info-label {
      min-width: 120px;
      color: #606266;
      font-weight: 500;
    }

    .info-value {
      color: #303133;
      flex: 1;

      &.amount {
        color: #F56C6C;
        font-weight: 600;
        font-size: 16px;
      }
    }
  }
}

.approval-flow {
  .flow-node {
    margin-bottom: 24px;
    padding: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    background: #fafafa;
    transition: all 0.3s;

    &.node-active {
      border-color: #409EFF;
      background: #ecf5ff;
    }

    &.node-completed {
      border-color: #67C23A;
      background: #f0f9ff;
    }

    &.node-pending {
      border-color: #e4e7ed;
      background: #fafafa;
      opacity: 0.6;
    }

    .node-header {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      .node-order {
        width: 32px;
        height: 32px;
        line-height: 32px;
        text-align: center;
        background: #409EFF;
        color: #fff;
        border-radius: 50%;
        font-weight: 600;
        margin-right: 12px;
      }

      .node-info {
        flex: 1;

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

        .node-type {
          display: flex;
          gap: 8px;
        }
      }
    }

    .approvers-list {
      margin-bottom: 12px;
      display: flex;
      align-items: flex-start;

      .approvers-label {
        min-width: 80px;
        color: #606266;
        font-weight: 500;
      }

      .approvers-items {
        flex: 1;
      }
    }

    .approval-records {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid #e4e7ed;

      .records-label {
        color: #606266;
        font-weight: 500;
        margin-bottom: 8px;
      }

      .records-list {
        .record-item {
          padding: 8px;
          margin-bottom: 8px;
          background: #fff;
          border-radius: 4px;
          border-left: 3px solid #409EFF;

          .record-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 4px;

            .record-approver {
              font-weight: 500;
              color: #303133;
            }
          }

          .record-opinion {
            color: #606266;
            font-size: 14px;
            margin-bottom: 4px;
          }

          .record-time {
            color: #909399;
            font-size: 12px;
          }
        }
      }
    }
  }
}

.current-approvers {
  padding: 12px;
  background: #fff3cd;
  border-radius: 4px;
}

.returned-reason {
  padding: 12px;
  background: #fef0f0;
  border-radius: 4px;
  color: #F56C6C;
  line-height: 1.6;
}
</style>

