<template>
  <div class="report-list">
    <el-card class="report-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon class="title-icon" :size="22"><DataAnalysis /></el-icon>
            <span>上报管理</span>
          </div>
          <div class="header-stats">
            <el-tag type="info" effect="plain">
              共 {{ pagination.total }} 条记录
            </el-tag>
          </div>
        </div>
      </template>

      <!-- 统计卡片 -->
      <div class="stats-row">
        <div class="stat-card">
          <div class="stat-icon total">
            <el-icon :size="24"><Box /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ pagination.total }}</div>
            <div class="stat-label">总配额数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon reported">
            <el-icon :size="24"><CircleCheck /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ reportedCount }}</div>
            <div class="stat-label">已上报</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon pending">
            <el-icon :size="24"><Clock /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ pendingCount }}</div>
            <div class="stat-label">待上报</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon rate">
            <el-icon :size="24"><TrendCharts /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ averageCompletionRate }}%</div>
            <div class="stat-label">平均完成率</div>
          </div>
        </div>
      </div>

      <el-table 
        :data="reports" 
        style="width: 100%" 
        v-loading="loading"
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
      >
        <el-table-column prop="category" label="类别" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getCategoryTagType(row.category)" size="small">
              {{ row.category }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="materialName" label="物资名称" min-width="150">
          <template #default="{ row }">
            <span class="material-name">{{ row.materialName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="unitQuota" label="配额" width="100" align="right">
          <template #default="{ row }">
            <span class="quota-value">{{ formatNumber(row.unitQuota) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="actualCompletion" label="实际完成" width="120" align="right">
          <template #default="{ row }">
            <span v-if="row.actualCompletion !== null" class="completion-value">
              {{ formatNumber(row.actualCompletion) }}
            </span>
            <el-tag v-else type="warning" size="small" effect="light">未上报</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="completionRate" label="完成率" width="160" align="center">
          <template #default="{ row }">
            <div class="progress-cell">
              <el-progress 
                :percentage="Math.round(row.completionRate * 100)" 
                :status="getProgressStatus(row.completionRate)"
                :stroke-width="8"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="targetUnitName" label="所属单位" width="140" align="center">
          <template #default="{ row }">
            <span class="unit-name">{{ row.targetUnitName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="reportedAt" label="上报时间" width="170" align="center">
          <template #default="{ row }">
            <div v-if="row.reportedAt" class="time-cell">
              <el-icon class="time-icon"><Clock /></el-icon>
              <span>{{ formatDate(row.reportedAt) }}</span>
            </div>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="canReport" 
              :type="row.actualCompletion !== null ? 'warning' : 'primary'" 
              size="small"
              @click="handleReport(row)"
            >
              <el-icon class="btn-icon"><Edit /></el-icon>
              {{ row.actualCompletion !== null ? '修改' : '上报' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.pageNumber"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- Report Dialog -->
    <el-dialog 
      v-model="showReportDialog" 
      :title="selectedReport?.actualCompletion !== null ? '修改上报数据' : '上报数据'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="reportForm" :rules="rules" label-width="100px">
        <el-form-item label="物资类别">
          <el-tag :type="getCategoryTagType(selectedReport?.category)">
            {{ selectedReport?.category }}
          </el-tag>
        </el-form-item>
        <el-form-item label="物资名称">
          <span class="dialog-value">{{ selectedReport?.materialName }}</span>
        </el-form-item>
        <el-form-item label="配额">
          <span class="dialog-value">{{ formatNumber(selectedReport?.unitQuota || 0) }} {{ selectedReport?.unit }}</span>
        </el-form-item>
        <el-form-item label="当前完成" v-if="selectedReport?.actualCompletion !== null">
          <span class="dialog-value highlight">{{ formatNumber(selectedReport?.actualCompletion || 0) }} {{ selectedReport?.unit }}</span>
        </el-form-item>
        <el-divider />
        <el-form-item label="实际完成" prop="actualCompletion">
          <el-input-number 
            v-model="reportForm.actualCompletion" 
            :min="0" 
            :max="selectedReport?.unitQuota"
            :precision="2" 
            :step="1"
            style="width: 200px" 
          />
          <span class="unit-hint">{{ selectedReport?.unit }}</span>
        </el-form-item>
        <el-form-item label="完成进度">
          <el-progress 
            :percentage="getFormCompletionRate()" 
            :status="getProgressStatus(getFormCompletionRate() / 100)"
            :stroke-width="12"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showReportDialog = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmitReport">
          <el-icon class="btn-icon"><Check /></el-icon>
          确认提交
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { DataAnalysis, Box, CircleCheck, Clock, TrendCharts, Edit, Check } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { reportsApi } from '@/api'
import type { ReportData } from '@/types'
import { OrganizationalLevel } from '@/types'

const authStore = useAuthStore()

const reports = ref<ReportData[]>([])
const loading = ref(false)
const showReportDialog = ref(false)
const saving = ref(false)
const selectedReport = ref<ReportData | null>(null)
const formRef = ref<FormInstance>()

const pagination = reactive({
  pageNumber: 1,
  pageSize: 10,
  total: 0
})

const reportForm = reactive({
  actualCompletion: 0
})

const rules: FormRules = {
  actualCompletion: [
    { required: true, message: '请输入实际完成数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '数量不能为负数', trigger: 'blur' }
  ]
}

// 统计数据
const reportedCount = computed(() => reports.value.filter(r => r.actualCompletion !== null).length)
const pendingCount = computed(() => reports.value.filter(r => r.actualCompletion === null).length)
const averageCompletionRate = computed(() => {
  if (reports.value.length === 0) return 0
  const total = reports.value.reduce((sum, r) => sum + (r.completionRate || 0), 0)
  return Math.round(total / reports.value.length * 100)
})

// Company level users can only view, not report
const canReport = computed(() => {
  return authStore.user?.organizationalLevel !== OrganizationalLevel.Company
})

function formatNumber(num: number): string {
  return num?.toLocaleString('zh-CN') ?? '0'
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleString('zh-CN')
}

function getCategoryTagType(category?: string): string {
  switch (category) {
    case '弹药': return 'danger'
    case '装备': return 'warning'
    case '物资': return 'success'
    case '器材': return 'info'
    default: return 'info'
  }
}

function getProgressStatus(rate: number): string {
  if (rate >= 1) return 'success'
  if (rate >= 0.6) return ''
  return 'warning'
}

function getFormCompletionRate(): number {
  if (!selectedReport.value?.unitQuota) return 0
  return Math.round((reportForm.actualCompletion / selectedReport.value.unitQuota) * 100)
}

function handlePageChange(page: number) {
  pagination.pageNumber = page
  loadReports()
}

function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.pageNumber = 1
  loadReports()
}

async function loadReports() {
  loading.value = true
  try {
    const response = await reportsApi.getAll({
      pageNumber: pagination.pageNumber,
      pageSize: pagination.pageSize
    })
    reports.value = response.items
    pagination.total = response.totalCount
  } catch {
    ElMessage.error('加载上报列表失败')
  } finally {
    loading.value = false
  }
}

function handleReport(report: ReportData) {
  selectedReport.value = report
  reportForm.actualCompletion = report.actualCompletion ?? 0
  showReportDialog.value = true
}

async function handleSubmitReport() {
  if (!formRef.value || !selectedReport.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    saving.value = true
    try {
      await reportsApi.submit({
        distributionId: selectedReport.value!.distributionId,
        actualCompletion: reportForm.actualCompletion
      })
      ElMessage.success('上报成功')
      showReportDialog.value = false
      await loadReports()
    } catch {
      ElMessage.error('上报失败')
    } finally {
      saving.value = false
    }
  })
}

onMounted(() => {
  loadReports()
})
</script>

<style scoped>
.report-list {
  padding: 0;
}

.report-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

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

.title-icon {
  color: #409eff;
}

/* 统计卡片 */
.stats-row {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: linear-gradient(135deg, #f5f7fa 0%, #fff 100%);
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.stat-icon.total {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
}

.stat-icon.reported {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
}

.stat-icon.pending {
  background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
}

.stat-icon.rate {
  background: linear-gradient(135deg, #909399 0%, #a6a9ad 100%);
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stat-label {
  font-size: 13px;
  color: #909399;
  margin-top: 2px;
}

/* 表格样式 */
.material-name {
  font-weight: 500;
  color: #303133;
}

.quota-value {
  font-weight: 500;
  color: #606266;
}

.completion-value {
  font-weight: 600;
  color: #67c23a;
}

.unit-name {
  color: #606266;
}

.progress-cell {
  padding: 0 8px;
}

.time-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  color: #909399;
  font-size: 13px;
}

.time-icon {
  font-size: 14px;
}

.no-data {
  color: #c0c4cc;
}

.btn-icon {
  margin-right: 4px;
}

/* 分页 */
.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 弹窗样式 */
.dialog-value {
  font-weight: 500;
  color: #303133;
}

.dialog-value.highlight {
  color: #409eff;
}

.unit-hint {
  margin-left: 8px;
  color: #909399;
}
</style>
