<template>
  <div class="report-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>上报管理</span>
        </div>
      </template>
      
      <el-table :data="reports" style="width: 100%" v-loading="loading">
        <el-table-column prop="category" label="类别" width="120" />
        <el-table-column prop="materialName" label="物资名称" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="unitQuota" label="配额" width="100" />
        <el-table-column prop="actualCompletion" label="实际完成" width="120">
          <template #default="{ row }">
            <span v-if="row.actualCompletion !== null">{{ row.actualCompletion }}</span>
            <el-tag v-else type="warning" size="small">未上报</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="completionRate" label="完成率" width="150">
          <template #default="{ row }">
            <el-progress :percentage="Math.round(row.completionRate * 100)" :status="getProgressStatus(row.completionRate)" />
          </template>
        </el-table-column>
        <el-table-column prop="targetUnitName" label="所属单位" width="150" />
        <el-table-column prop="reportedAt" label="上报时间" width="180">
          <template #default="{ row }">
            {{ row.reportedAt ? formatDate(row.reportedAt) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button 
              v-if="canReport" 
              type="primary" 
              text 
              size="small" 
              @click="handleReport(row)"
            >
              {{ row.actualCompletion !== null ? '修改' : '上报' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        :current-page="pagination.pageNumber"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        class="pagination"
        @update:current-page="handlePageChange"
        @update:page-size="handleSizeChange"
      />
    </el-card>
    
    <!-- Report Dialog -->
    <el-dialog v-model="showReportDialog" title="上报数据" width="500px">
      <el-form ref="formRef" :model="reportForm" :rules="rules" label-width="100px">
        <el-form-item label="物资名称">
          <el-input :value="selectedReport?.materialName" disabled />
        </el-form-item>
        <el-form-item label="配额">
          <el-input :value="selectedReport?.unitQuota" disabled />
        </el-form-item>
        <el-form-item label="实际完成" prop="actualCompletion">
          <el-input-number v-model="reportForm.actualCompletion" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showReportDialog = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmitReport">提交</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 { 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' }]
}

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

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

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

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>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
