<template>
  <div class="operation-logs-container">
    <!-- 日志筛选区域 -->
    <div class="filter-section">
      <el-form :model="filters" inline label-width="80px">
        <el-form-item label="操作类型">
          <el-select
            v-model="filters.operationType"
            placeholder="请选择"
            clearable
            style="width: 150px;"
          >
            <el-option label="全部" value="" />
            <el-option label="创建" value="CREATE" />
            <el-option label="扫描" value="SCAN" />
            <el-option label="出库" value="OUTBOUND" />
            <el-option label="撤销" value="UNDO" />
            <el-option label="确认" value="CONFIRM" />
            <el-option label="暂停" value="PAUSE" />
            <el-option label="恢复" value="RESUME" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="操作员">
          <el-input
            v-model="filters.operatorName"
            placeholder="输入操作员姓名"
            clearable
            style="width: 150px;"
          />
        </el-form-item>
        
        <el-form-item label="出库单号">
          <el-input
            v-model="filters.orderNo"
            placeholder="输入出库单号"
            clearable
            style="width: 200px;"
          />
        </el-form-item>
        
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="filters.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 380px;"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button @click="exportLogs">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 日志列表 -->
    <div class="logs-section">
      <el-table
        :data="filteredLogs"
        stripe
        v-loading="loading"
        height="calc(100vh - 240px)"
      >
        <el-table-column type="expand" width="50">
          <template #default="{ row }">
            <div class="log-details">
              <el-descriptions :column="2" border size="small">
                <el-descriptions-item label="操作详情" span="2">
                  <pre>{{ JSON.stringify(row.details || {}, null, 2) }}</pre>
                </el-descriptions-item>
                <el-descriptions-item label="设备信息">
                  {{ row.deviceInfo || '--' }}
                </el-descriptions-item>
                <el-descriptions-item label="IP地址">
                  {{ row.ipAddress || '--' }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="操作时间" width="160" sortable>
          <template #default="{ row }">
            <div class="timestamp">
              {{ formatDateTime(row.createdAt) }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getOperationTypeTag(row.operationType)" size="small">
              {{ getOperationTypeText(row.operationType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="orderNo" label="出库单号" width="180">
          <template #default="{ row }">
            <span v-if="row.orderNo" class="order-no">
              {{ row.orderNo }}
            </span>
            <span v-else class="no-data">--</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="operatorName" label="操作员" width="120" />
        
        <el-table-column prop="operationDesc" label="操作描述">
          <template #default="{ row }">
            <div class="operation-desc">
              {{ row.operationDesc }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="结果" width="100">
          <template #default="{ row }">
            <el-icon 
              v-if="row.success !== false" 
              color="#67c23a"
              :size="18"
            >
              <SuccessFilled />
            </el-icon>
            <el-icon v-else color="#f56c6c" :size="18">
              <CircleCloseFilled />
            </el-icon>
          </template>
        </el-table-column>
        
        <el-table-column label="用时" width="100" align="right">
          <template #default="{ row }">
            <span v-if="row.duration !== undefined">
              {{ row.duration }}ms
            </span>
            <span v-else class="no-data">--</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页器 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[20, 50, 100, 200]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Download,
  SuccessFilled,
  CircleCloseFilled
} from '@element-plus/icons-vue'

const props = defineProps({
  logs: {
    type: Array,
    default: () => []
  }
})

// 响应式数据
const filters = ref({
  operationType: '',
  operatorName: '',
  orderNo: '',
  dateRange: []
})

const pagination = ref({
  currentPage: 1,
  pageSize: 50,
  total: 0
})

const loading = ref(false)

// 模拟更多日志数据
const mockLogs = ref([
  {
    id: '1',
    orderId: '1',
    orderNo: 'OUT-20231227-001',
    operatorId: 'OP001',
    operatorName: '张三',
    operationType: 'SCAN',
    operationDesc: '扫描批次 BATCH-202312-001，出库50个不锈钢螺丝',
    ipAddress: '192.168.1.100',
    deviceInfo: 'Chrome/120.0.0.0',
    createdAt: '2023-12-27 10:30:15',
    success: true,
    duration: 320,
    details: {
      batchNo: 'BATCH-202312-001',
      quantity: 50,
      materialName: '不锈钢螺丝',
      unit: '个'
    }
  },
  {
    id: '2',
    orderId: '1',
    orderNo: 'OUT-20231227-001',
    operatorId: 'OP001',
    operatorName: '张三',
    operationType: 'UNDO',
    operationDesc: '撤销批次 BATCH-202312-001 的出库操作',
    ipAddress: '192.168.1.100',
    deviceInfo: 'Chrome/120.0.0.0',
    createdAt: '2023-12-27 10:32:45',
    success: true,
    duration: 280,
    details: {
      batchNo: 'BATCH-202312-001',
      quantity: 50
    }
  }
])

// 计算属性
const allLogs = computed(() => {
  return [...props.logs, ...mockLogs.value].sort((a, b) => {
    return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
  })
})

const filteredLogs = computed(() => {
  let result = [...allLogs.value]
  
  // 按操作类型过滤
  if (filters.value.operationType) {
    result = result.filter(log => 
      log.operationType === filters.value.operationType
    )
  }
  
  // 按操作员过滤
  if (filters.value.operatorName) {
    result = result.filter(log => 
      log.operatorName.toLowerCase().includes(filters.value.operatorName.toLowerCase())
    )
  }
  
  // 按订单号过滤
  if (filters.value.orderNo) {
    result = result.filter(log => 
      log.orderNo?.toLowerCase().includes(filters.value.orderNo.toLowerCase())
    )
  }
  
  // 按时间范围过滤
  if (filters.value.dateRange?.length === 2) {
    const [start, end] = filters.value.dateRange
    const startTime = new Date(start).getTime()
    const endTime = new Date(end).getTime()
    
    result = result.filter(log => {
      const logTime = new Date(log.createdAt).getTime()
      return logTime >= startTime && logTime <= endTime
    })
  }
  
  // 更新分页总数
  pagination.value.total = result.length
  
  // 分页处理
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return result.slice(start, end)
})

// 方法
const handleSearch = () => {
  pagination.value.currentPage = 1
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const handleReset = () => {
  filters.value = {
    operationType: '',
    operatorName: '',
    orderNo: '',
    dateRange: []
  }
  pagination.value.currentPage = 1
  handleSearch()
}

const exportLogs = () => {
  ElMessage.success('导出功能开发中...')
  // 实际项目中这里可以实现CSV/Excel导出
}

const handleSizeChange = (size) => {
  pagination.value.pageSize = size
}

const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
}

const getOperationTypeTag = (type) => {
  const map = {
    'CREATE': 'primary',
    'SCAN': 'success',
    'OUTBOUND': 'warning',
    'UNDO': 'danger',
    'CONFIRM': 'success',
    'PAUSE': 'info',
    'RESUME': 'warning'
  }
  return map[type] || 'info'
}

const getOperationTypeText = (type) => {
  const map = {
    'CREATE': '创建',
    'SCAN': '扫描',
    'OUTBOUND': '出库',
    'UNDO': '撤销',
    'CONFIRM': '确认',
    'PAUSE': '暂停',
    'RESUME': '恢复'
  }
  return map[type] || type
}

const formatDateTime = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.operation-logs-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.filter-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

.logs-section {
  flex: 1;
  overflow: hidden;
}

.log-details {
  padding: 15px;
  background: #f8fafc;
  border-radius: 4px;
  margin: 5px 0;
}

.log-details pre {
  margin: 0;
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #333;
  background: white;
  padding: 10px;
  border-radius: 4px;
  overflow: auto;
  max-height: 200px;
}

.timestamp {
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 12px;
  color: #606266;
}

.order-no {
  font-family: 'Monaco', 'Consolas', monospace;
  font-weight: 500;
  color: #409eff;
}

.no-data {
  color: #909399;
  font-style: italic;
}

.operation-desc {
  line-height: 1.4;
  color: #303133;
}

.pagination-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-descriptions__body) {
  background: white;
}
</style>