<template>
  <div class="allocation-list">
    <el-card class="list-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon class="title-icon" :size="22"><Box /></el-icon>
            <span>物资配额管理</span>
          </div>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索物资名称"
              clearable
              style="width: 180px; margin-right: 12px"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="categoryFilter" placeholder="类别筛选" clearable style="width: 120px; margin-right: 12px">
              <el-option label="弹药" value="弹药" />
              <el-option label="装备" value="装备" />
              <el-option label="物资" value="物资" />
              <el-option label="器材" value="器材" />
            </el-select>
            <el-button v-if="authStore.canCreateAllocations" @click="$router.push('/allocations/categories')">
              <el-icon><Setting /></el-icon>
              类别管理
            </el-button>
            <el-button v-if="authStore.canCreateAllocations" type="primary" @click="$router.push('/allocations/create')">
              <el-icon><Plus /></el-icon>
              创建配额
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="filteredAllocations" 
        style="width: 100%" 
        v-loading="loading"
        stripe
        highlight-current-row
        :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)" effect="plain" 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">
          <template #default="{ row }">
            <span class="unit-text">{{ row.unit }}</span>
          </template>
        </el-table-column>
        <!-- 师团级显示总配额,团级显示本单位配额,营部及以下隐藏配额 -->
        <el-table-column v-if="authStore.canCreateAllocations" prop="totalQuota" label="总配额" width="120" align="center">
          <template #default="{ row }">
            <span class="quota-value">{{ formatNumber(row.totalQuota) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-else-if="authStore.organizationalLevelNum === 2" prop="unitQuota" label="配额" width="100" align="center">
          <template #default="{ row }">
            <div class="quota-cell">
              <span class="quota-number">{{ formatNumber(getMyUnitQuota(row)) }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 师团级显示总消耗,团级显示消耗情况(含总数和百分比),营部及以下只显示上报数量 -->
        <el-table-column v-if="authStore.canCreateAllocations" label="总消耗" width="120" align="center">
          <template #default="{ row }">
            <span class="consumed-value">{{ formatNumber(getTotalActualCompletion(row)) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="authStore.canCreateAllocations" label="分配情况" width="100" align="center">
          <template #default="{ row }">
            <span class="dist-count">{{ row.distributions?.length || 0 }} 个单位</span>
          </template>
        </el-table-column>
        <el-table-column v-else-if="authStore.organizationalLevelNum === 2" label="消耗情况" width="200" align="center">
          <template #default="{ row }">
            <div class="consumption-cell">
              <div class="consumption-numbers">
                <span class="completion-num">{{ formatNumber(getMyActualCompletion(row)) }}</span>
                <span class="separator">/</span>
                <span class="quota-num">{{ formatNumber(getMyUnitQuota(row)) }}</span>
              </div>
              <el-progress 
                :percentage="getMyCompletionPercentage(row)" 
                :stroke-width="8"
                :status="getProgressStatus(getMyCompletionPercentage(row) / 100)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column v-else label="已消耗" width="120" align="center">
          <template #default="{ row }">
            <div class="report-cell">
              <span class="report-number">{{ formatNumber(getMyActualCompletion(row)) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="authStore.canCreateAllocations" prop="createdByUnitName" label="创建单位" width="120" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="160" align="center">
          <template #default="{ row }">
            <span class="time-cell">{{ formatDate(row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tooltip content="查看分配" placement="top">
                <el-button type="primary" link size="small" @click="handleViewDistribution(row)">
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip v-if="authStore.canCreateAllocations" content="编辑" placement="top">
                <el-button type="warning" link size="small" @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip v-if="authStore.canCreateAllocations" content="删除" placement="top">
                <el-button type="danger" link size="small" @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </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>
    
    <!-- Distribution Dialog -->
    <el-dialog 
      v-model="showDistributionDialog" 
      :title="`配额分配详情 - ${selectedAllocation?.materialName || ''}`" 
      width="1000px"
      :close-on-click-modal="false"
    >
      <div class="distribution-summary">
        <el-row :gutter="24">
          <el-col :span="6">
            <div class="summary-item">
              <div class="summary-label">物资类别</div>
              <div class="summary-value">
                <el-tag :type="getCategoryTagType(selectedAllocation?.category || '')" size="large" effect="plain">
                  {{ selectedAllocation?.category }}
                </el-tag>
              </div>
            </div>
          </el-col>
          <!-- 师团级显示总配额、总消耗、总进度 -->
          <template v-if="authStore.canCreateAllocations">
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">总配额</div>
                <div class="summary-value highlight">
                  <span class="number">{{ formatNumber(selectedAllocation?.totalQuota || 0) }}</span>
                  <span class="unit">{{ selectedAllocation?.unit }}</span>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">总消耗</div>
                <div class="summary-value consumed">
                  <span class="number">{{ formatNumber(getTotalConsumed()) }}</span>
                  <span class="unit">{{ selectedAllocation?.unit }}</span>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">总进度</div>
                <div class="summary-value progress-value">
                  <el-progress 
                    type="circle" 
                    :percentage="getTotalProgressPercentage()" 
                    :width="45"
                    :stroke-width="5"
                    :color="getProgressColor(getTotalProgressPercentage())"
                    :show-text="false"
                  />
                  <span class="progress-text">{{ getTotalProgressPercentage() }}%</span>
                </div>
              </div>
            </el-col>
          </template>
          <!-- 团级显示本单位配额、总消耗 -->
          <template v-else-if="authStore.organizationalLevelNum === 2">
            <el-col :span="9">
              <div class="summary-item">
                <div class="summary-label">本单位配额</div>
                <div class="summary-value highlight">
                  <span class="number">{{ formatNumber(getTotalDistributed()) }}</span>
                  <span class="unit">{{ selectedAllocation?.unit }}</span>
                </div>
              </div>
            </el-col>
            <el-col :span="9">
              <div class="summary-item">
                <div class="summary-label">总消耗</div>
                <div class="summary-value consumed">
                  <span class="number">{{ formatNumber(getTotalConsumed()) }}</span>
                  <span class="unit">{{ selectedAllocation?.unit }}</span>
                </div>
              </div>
            </el-col>
          </template>
          <!-- 营部及以下只显示物资类别和总消耗，并增加上报消耗按钮 -->
          <template v-else>
            <el-col :span="8">
              <div class="summary-item">
                <div class="summary-label">总消耗</div>
                <div class="summary-value consumed">
                  <span class="number">{{ formatNumber(getTotalConsumed()) }}</span>
                  <span class="unit">{{ selectedAllocation?.unit }}</span>
                </div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="summary-item action-item">
                <div class="summary-label">操作</div>
                <div class="summary-value">
                  <el-button type="primary" @click="handleReportFromSummary">
                    上报消耗
                  </el-button>
                </div>
              </div>
            </el-col>
          </template>
        </el-row>
      </div>
      
      <!-- 师部账号：时间范围筛选 -->
      <div v-if="authStore.canCreateAllocations" class="period-filter">
        <span class="filter-label">查看时间范围：</span>
        <el-radio-group v-model="selectedPeriod" size="small" @change="handlePeriodChange">
          <el-radio-button value="week">本周</el-radio-button>
          <el-radio-button value="month">本月</el-radio-button>
          <el-radio-button value="halfYear">半年</el-radio-button>
          <el-radio-button value="year">年度</el-radio-button>
          <el-radio-button value="all">全部</el-radio-button>
        </el-radio-group>
      </div>
      
      <!-- 师团级和团级显示分配列表，营部及以下隐藏 -->
      <el-table 
        v-if="authStore.organizationalLevelNum <= 2"
        :data="filteredDistributions" 
        v-loading="loadingStats"
        style="width: 100%"
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold', fontSize: '14px' }"
        :row-style="{ height: '60px' }"
      >
        <el-table-column prop="targetUnitName" label="目标单位" min-width="150">
          <template #default="{ row }">
            <div class="unit-cell">
              <el-icon class="unit-icon" :size="16"><OfficeBuilding /></el-icon>
              <span class="unit-name">{{ row.targetUnitName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="unitQuota" label="分配配额" width="120" align="center">
          <template #default="{ row }">
            <div class="quota-cell-dialog">
              <span class="quota-number-dialog">{{ formatNumber(row.unitQuota) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="actualCompletion" label="实际完成" width="120" align="center">
          <template #default="{ row }">
            <div class="completion-cell">
              <span v-if="row.actualCompletion" class="completion-number">{{ formatNumber(row.actualCompletion) }}</span>
              <el-tag v-else type="info" size="small" effect="plain">未上报</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="completionRate" label="完成率" width="180" align="center">
          <template #default="{ row }">
            <div class="progress-cell-dialog">
              <el-progress 
                :percentage="Math.round(row.completionRate * 100)" 
                :status="getProgressStatus(row.completionRate)"
                :stroke-width="10"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="reportedAt" label="上报时间" width="150" align="center">
          <template #default="{ row }">
            <div class="time-cell-dialog">
              <el-icon v-if="row.reportedAt" class="time-icon" :size="14"><Clock /></el-icon>
              <span>{{ row.reportedAt ? formatDate(row.reportedAt) : '-' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.actualCompletion"
              type="warning" 
              size="small"
              plain
              @click="handleViewReports(row)"
            >
              上报记录
            </el-button>
            <el-button 
              v-if="canReportConsumption(row)" 
              type="primary" 
              size="small"
              @click="handleReportConsumption(row)"
            >
              上报消耗
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- Consumption Reports Dialog -->
    <el-dialog
      v-model="showReportsDialog"
      :title="`上报记录 - ${selectedDistribution?.targetUnitName || ''}`"
      width="900px"
      :close-on-click-modal="false"
    >
      <div class="reports-summary">
        <el-row :gutter="16">
          <el-col :span="6">
            <div class="report-stat">
              <div class="stat-label">分配配额</div>
              <div class="stat-value highlight">{{ formatNumber(selectedDistribution?.unitQuota || 0) }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="report-stat">
              <div class="stat-label">{{ reportsPeriod === 'all' ? '累计消耗' : '期间消耗' }}</div>
              <div class="stat-value consumed">{{ formatNumber(getReportsTotalConsumed()) }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="report-stat">
              <div class="stat-label">上报单位数</div>
              <div class="stat-value">{{ unitSummaries.length }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="report-stat">
              <div class="stat-label">上报次数</div>
              <div class="stat-value">{{ consumptionReports.length }}</div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 师部账号：时间范围筛选 -->
      <div v-if="authStore.canCreateAllocations" class="period-filter">
        <span class="filter-label">查看时间范围：</span>
        <el-radio-group v-model="reportsPeriod" size="small" @change="handleReportsPeriodChange">
          <el-radio-button value="week">本周</el-radio-button>
          <el-radio-button value="month">本月</el-radio-button>
          <el-radio-button value="halfYear">半年</el-radio-button>
          <el-radio-button value="year">年度</el-radio-button>
          <el-radio-button value="all">全部</el-radio-button>
        </el-radio-group>
      </div>

      <el-tabs v-model="reportsTabActive" class="reports-tabs">
        <el-tab-pane label="按单位汇总" name="summary">
          <el-table
            :data="unitSummaries"
            style="width: 100%"
            v-loading="loadingReports"
            stripe
            :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
          >
            <el-table-column prop="unitName" label="单位名称" min-width="150">
              <template #default="{ row }">
                <div class="unit-cell">
                  <el-icon class="unit-icon"><OfficeBuilding /></el-icon>
                  <span class="unit-name">{{ row.unitName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="unitLevel" label="单位级别" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getUnitLevelTagType(row.unitLevel)" size="small">
                  {{ getUnitLevelText(row.unitLevel) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="totalReported" label="上报总量" width="120" align="right">
              <template #default="{ row }">
                <span class="total-reported">{{ formatNumber(row.totalReported) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="reportCount" label="上报次数" width="100" align="center">
              <template #default="{ row }">
                <el-tag type="info" size="small">{{ row.reportCount }} 次</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastReportedAt" label="最后上报时间" width="170" align="center">
              <template #default="{ row }">
                <span class="time-cell">{{ row.lastReportedAt ? formatDate(row.lastReportedAt) : '-' }}</span>
              </template>
            </el-table-column>
          </el-table>
          <template v-if="unitSummaries.length === 0 && !loadingReports">
            <el-empty description="暂无上报数据" />
          </template>
        </el-tab-pane>

        <el-tab-pane label="上报明细" name="detail">
          <el-table
            :data="consumptionReports"
            style="width: 100%"
            v-loading="loadingReports"
            stripe
            :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
          >
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="reportedAmount" label="本次上报" width="120" align="center">
              <template #default="{ row }">
                <span class="report-amount">+{{ formatNumber(row.reportedAmount) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="cumulativeAmount" label="累计数量" width="120" align="center">
              <template #default="{ row }">
                <span class="cumulative-amount">{{ formatNumber(row.cumulativeAmount) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="reportedByUserName" label="上报人" min-width="120">
              <template #default="{ row }">
                <span>{{ row.reportedByUserName || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="reportedAt" label="上报时间" width="160" align="center">
              <template #default="{ row }">
                <span class="time-cell">{{ formatDate(row.reportedAt) }}</span>
              </template>
            </el-table-column>
          </el-table>
          <template v-if="consumptionReports.length === 0 && !loadingReports">
            <el-empty description="暂无上报记录" />
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, View, Edit, Delete, Box, Setting, OfficeBuilding, Clock } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { allocationsApi, type UnitReportSummary, type UnitConsumptionStat } from '@/api'
import type { MaterialAllocation, AllocationDistribution } from '@/types'

const router = useRouter()
const authStore = useAuthStore()

const allocations = ref<MaterialAllocation[]>([])
const distributions = ref<AllocationDistribution[]>([])
const consumptionReports = ref<any[]>([])
const unitSummaries = ref<UnitReportSummary[]>([])
const consumptionStats = ref<UnitConsumptionStat[]>([])
const reportsTabActive = ref('summary')
const loading = ref(false)
const loadingReports = ref(false)
const loadingStats = ref(false)
const showDistributionDialog = ref(false)
const showReportsDialog = ref(false)
const searchKeyword = ref('')
const categoryFilter = ref('')
const selectedAllocation = ref<MaterialAllocation | null>(null)
const selectedDistribution = ref<AllocationDistribution | null>(null)
const selectedPeriod = ref('all')
const reportsPeriod = ref('all')

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

const filteredAllocations = computed(() => {
  let result = allocations.value
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(a => a.materialName.toLowerCase().includes(keyword))
  }
  if (categoryFilter.value) {
    result = result.filter(a => a.category === categoryFilter.value)
  }
  return result
})

function formatDate(dateStr: string): string {
  if (!dateStr) return '-'
  // 移除时间字符串末尾的Z（UTC标识），直接当作本地时间处理
  const cleanDateStr = dateStr.replace('Z', '').replace(/\+.*$/, '').replace(/-\d{2}:\d{2}$/, '')
  const date = new Date(cleanDateStr)
  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')
  return `${year}/${month}/${day} ${hours}:${minutes}`
}

function formatNumber(num: number): string {
  return num.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 getProgressColor(percentage: number): string {
  if (percentage >= 100) return '#67c23a' // 绿色
  if (percentage >= 60) return '#409eff'  // 蓝色
  return '#e6a23c' // 橙色
}

function getUnitLevelTagType(level: string): string {
  switch (level) {
    case 'Division': return 'danger'
    case 'Regiment': return 'warning'
    case 'Battalion': return 'success'
    case 'Company': return 'info'
    default: return 'info'
  }
}

function getUnitLevelText(level: string): string {
  switch (level) {
    case 'Division': return '师团'
    case 'Regiment': return '团'
    case 'Battalion': return '营'
    case 'Company': return '连'
    default: return level
  }
}

function getDistributionPercentage(allocation: MaterialAllocation): number {
  if (!allocation.distributions || allocation.distributions.length === 0) return 0
  const distributed = allocation.distributions.reduce((sum, d) => sum + (d.unitQuota || 0), 0)
  return Math.round((distributed / allocation.totalQuota) * 100)
}

function getTotalActualCompletion(allocation: MaterialAllocation): number {
  if (!allocation.distributions || allocation.distributions.length === 0) return 0
  return allocation.distributions.reduce((sum, d) => sum + (d.actualCompletion || 0), 0)
}

function getMyUnitQuota(allocation: MaterialAllocation): number {
  if (!authStore.user || !allocation.distributions) return 0
  // 先查找分配给当前单位的配额
  let myDistribution = allocation.distributions.find(d => d.targetUnitId === authStore.user?.organizationalUnitId)
  // 如果没有，则取第一个分配记录（上级单位的配额）
  if (!myDistribution && allocation.distributions.length > 0) {
    myDistribution = allocation.distributions[0]
  }
  return myDistribution?.unitQuota || 0
}

function getMyActualCompletion(allocation: MaterialAllocation): number {
  // 营部及以下级别使用后端计算的可见范围内的上报总和
  if (authStore.organizationalLevelNum >= 3 && (allocation as any).visibleActualCompletion !== undefined) {
    return (allocation as any).visibleActualCompletion || 0
  }
  
  if (!authStore.user || !allocation.distributions) return 0
  // 先查找分配给当前单位的配额
  let myDistribution = allocation.distributions.find(d => d.targetUnitId === authStore.user?.organizationalUnitId)
  // 如果没有，则取第一个分配记录（上级单位的配额）
  if (!myDistribution && allocation.distributions.length > 0) {
    myDistribution = allocation.distributions[0]
  }
  return myDistribution?.actualCompletion || 0
}

function getMyCompletionPercentage(allocation: MaterialAllocation): number {
  const quota = getMyUnitQuota(allocation)
  if (quota === 0) return 0
  const completion = getMyActualCompletion(allocation)
  return Math.round((completion / quota) * 100)
}

function getTotalDistributed(): number {
  return distributions.value.reduce((sum, d) => sum + (d.unitQuota || 0), 0)
}

function getTotalConsumed(): number {
  // 如果有按时间范围筛选的统计数据，使用统计数据
  if (authStore.canCreateAllocations && selectedPeriod.value !== 'all' && consumptionStats.value.length > 0) {
    return consumptionStats.value.reduce((sum: number, s) => sum + s.totalConsumed, 0)
  }
  // 营部及以下级别使用后端计算的可见范围内的上报总和
  if (authStore.organizationalLevelNum >= 3 && selectedAllocation.value) {
    return (selectedAllocation.value as any).visibleActualCompletion || 0
  }
  // 师部账号：使用 selectedAllocation 中的 distributions 数据
  if (selectedAllocation.value?.distributions) {
    return selectedAllocation.value.distributions.reduce((sum, d) => sum + (d.actualCompletion || 0), 0)
  }
  return distributions.value.reduce((sum, d) => sum + (d.actualCompletion || 0), 0)
}

function getTotalProgressPercentage(): number {
  if (!selectedAllocation.value || !selectedAllocation.value.totalQuota) return 0
  const consumed = getTotalConsumed()
  const percentage = Math.round((consumed / selectedAllocation.value.totalQuota) * 100)
  return percentage
}

// 根据时间范围筛选后的分配数据
const filteredDistributions = computed(() => {
  if (!authStore.canCreateAllocations || selectedPeriod.value === 'all') {
    return distributions.value
  }
  // 使用统计数据更新分配记录的消耗数据
  return distributions.value.map(d => {
    const stat = consumptionStats.value.find((s: UnitConsumptionStat) => s.unitId === d.targetUnitId)
    if (stat) {
      return {
        ...d,
        actualCompletion: stat.totalConsumed,
        completionRate: stat.completionRate
      }
    }
    return { ...d, actualCompletion: 0, completionRate: 0 }
  })
})

async function handlePeriodChange() {
  if (!selectedAllocation.value || selectedPeriod.value === 'all') {
    consumptionStats.value = []
    return
  }
  
  loadingStats.value = true
  try {
    const response = await allocationsApi.getConsumptionStats(selectedAllocation.value.id, selectedPeriod.value)
    consumptionStats.value = response.unitStats
  } catch (error) {
    console.error('加载消耗统计失败', error)
    ElMessage.error('加载消耗统计失败')
    consumptionStats.value = []
  } finally {
    loadingStats.value = false
  }
}

function canReportConsumption(distribution: AllocationDistribution): boolean {
  if (!authStore.user) return false
  // 如果分配目标是当前用户所属单位，则可以上报消耗
  if (distribution.targetUnitId === authStore.user.organizationalUnitId) return true
  // 营部及以下账号可以上报所属团的配额
  if (authStore.organizationalLevelNum >= 3) return true
  return false
}

function handleReportConsumption(distribution: AllocationDistribution) {
  if (!selectedAllocation.value) return
  router.push({
    path: `/allocations/${selectedAllocation.value.id}/report`,
    query: {
      distributionId: distribution.id,
      targetUnitId: distribution.targetUnitId
    }
  })
}

function handleReportFromSummary() {
  if (!selectedAllocation.value) return
  // 获取第一个分配记录（营部及以下账号看到的是上级单位的配额）
  const distribution = distributions.value[0] || selectedAllocation.value.distributions?.[0]
  if (distribution) {
    router.push({
      path: `/allocations/${selectedAllocation.value.id}/report`,
      query: {
        distributionId: distribution.id,
        targetUnitId: distribution.targetUnitId
      }
    })
  }
}

async function handleViewReports(distribution: AllocationDistribution) {
  selectedDistribution.value = distribution
  showReportsDialog.value = true
  reportsTabActive.value = 'summary'
  reportsPeriod.value = 'all'
  loadingReports.value = true
  try {
    // 同时加载汇总数据和明细数据
    const [reports, summaries] = await Promise.all([
      allocationsApi.getConsumptionReports(distribution.id),
      allocationsApi.getReportSummaryByUnit(distribution.id)
    ])
    consumptionReports.value = reports
    unitSummaries.value = summaries
  } catch (error) {
    console.error('加载上报记录失败', error)
    ElMessage.error('加载上报记录失败')
    consumptionReports.value = []
    unitSummaries.value = []
  } finally {
    loadingReports.value = false
  }
}

// 计算上报记录的总消耗
function getReportsTotalConsumed(): number {
  return unitSummaries.value.reduce((sum, s) => sum + s.totalReported, 0)
}

// 上报记录时间范围筛选变化
async function handleReportsPeriodChange() {
  if (!selectedDistribution.value) return
  
  loadingReports.value = true
  try {
    const period = reportsPeriod.value === 'all' ? undefined : reportsPeriod.value
    const summaries = await allocationsApi.getReportSummaryByUnit(selectedDistribution.value.id, period)
    unitSummaries.value = summaries
  } catch (error) {
    console.error('加载上报记录失败', error)
    ElMessage.error('加载上报记录失败')
  } finally {
    loadingReports.value = false
  }
}

function handleSearch() {
  pagination.pageNumber = 1
}

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

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

async function loadAllocations() {
  loading.value = true
  try {
    const response = await allocationsApi.getAll({
      pageNumber: pagination.pageNumber,
      pageSize: pagination.pageSize
    })
    allocations.value = response.items
    pagination.total = response.totalCount
  } catch {
    ElMessage.error('加载配额列表失败')
  } finally {
    loading.value = false
  }
}

async function handleViewDistribution(allocation: MaterialAllocation) {
  selectedAllocation.value = allocation
  selectedPeriod.value = 'all'
  consumptionStats.value = []
  // 对于非师团级账号，只显示本单位及下级单位的分配记录
  if (authStore.canCreateAllocations) {
    // 师团级显示所有分配
    distributions.value = allocation.distributions || []
  } else {
    // 团部及以下只显示本单位的分配（不显示上级单位）
    const myUnitId = authStore.user?.organizationalUnitId
    distributions.value = (allocation.distributions || []).filter(d => d.targetUnitId === myUnitId)
  }
  showDistributionDialog.value = true
}

function handleEdit(allocation: MaterialAllocation) {
  router.push(`/allocations/${allocation.id}/edit`)
}

async function handleDelete(allocation: MaterialAllocation) {
  try {
    await ElMessageBox.confirm(
      `确定要删除物资配额 "${allocation.materialName}" 吗？此操作不可恢复。`, 
      '确认删除', 
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--danger'
      }
    )
    await allocationsApi.delete(allocation.id)
    ElMessage.success('删除成功')
    await loadAllocations()
  } catch {
    // User cancelled or error
  }
}

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

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

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

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

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

.title-icon {
  margin-right: 8px;
  color: #409EFF;
}

.header-actions {
  display: flex;
  align-items: center;
}

.material-name {
  font-weight: 500;
  color: #303133;
}

.unit-text {
  color: #909399;
  font-size: 13px;
}

.quota-value {
  font-weight: 600;
  color: #409EFF;
  font-size: 14px;
}

.consumed-value {
  font-weight: 600;
  color: #67C23A;
  font-size: 14px;
}

.quota-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 8px 0;
}

.quota-number {
  font-size: 18px;
  font-weight: 700;
  color: #409EFF;
  font-family: 'Arial', sans-serif;
}

.distribution-info {
  display: flex;
  align-items: center;
  justify-content: center;
}

.dist-count {
  font-size: 12px;
  color: #606266;
}

.period-filter {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 6px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-right: 12px;
}

.consumption-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
}

.consumption-numbers {
  display: flex;
  align-items: baseline;
  gap: 4px;
  font-family: 'Arial', sans-serif;
}

.completion-num {
  font-size: 16px;
  font-weight: 700;
  color: #67C23A;
}

.separator {
  font-size: 14px;
  color: #909399;
  margin: 0 2px;
}

.quota-num {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
}

.report-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 8px 0;
}

.report-number {
  font-size: 18px;
  font-weight: 700;
  color: #67C23A;
  font-family: 'Arial', sans-serif;
}

.time-cell {
  font-size: 13px;
  color: #909399;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 4px;
}

.action-buttons .el-button {
  padding: 4px 8px;
}

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

/* Distribution Dialog Styles */
.distribution-summary {
  background: linear-gradient(135deg, #f5f7fa 0%, #e8eef5 100%);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.summary-item {
  text-align: center;
  padding: 12px;
  background: white;
  border-radius: 8px;
  transition: transform 0.2s;
  height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.summary-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.summary-item.action-item .summary-value {
  margin-top: 8px;
}

.summary-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 12px;
  font-weight: 500;
}

.summary-value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: baseline;
  justify-content: center;
  gap: 4px;
}

.summary-value.progress-value {
  align-items: center;
  gap: 12px;
}

.progress-text {
  font-size: 22px;
  font-weight: bold;
  color: #303133;
}

.summary-value .number {
  font-size: 24px;
  font-weight: 700;
  font-family: 'Arial', sans-serif;
}

.summary-value .unit {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.summary-value.highlight .number {
  color: #409EFF;
}

.summary-value.allocated .number {
  color: #67C23A;
}

.summary-value.consumed .number {
  color: #F56C6C;
}

.summary-value.units .number {
  color: #E6A23C;
}

.unit-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.unit-icon {
  color: #409EFF;
}

.unit-name {
  font-weight: 500;
  color: #303133;
}

.quota-cell-dialog {
  display: flex;
  justify-content: center;
  align-items: center;
}

.quota-number-dialog {
  font-size: 16px;
  font-weight: 700;
  color: #409EFF;
  font-family: 'Arial', sans-serif;
}

.completion-cell {
  display: flex;
  justify-content: center;
  align-items: center;
}

.completion-number {
  font-size: 16px;
  font-weight: 700;
  color: #67C23A;
  font-family: 'Arial', sans-serif;
}

.progress-cell-dialog {
  padding: 0 12px;
}

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

.time-icon {
  color: #909399;
}

.completion-value {
  font-weight: 500;
  color: #67C23A;
}

.completion-value.no-data {
  color: #C0C4CC;
  font-weight: normal;
}

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

:deep(.el-table .el-table__row) {
  transition: background-color 0.2s;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #ecf5ff !important;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 20px 24px;
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.consumption-cell .el-progress) {
  width: 100%;
  max-width: 140px;
}

:deep(.consumption-cell .el-progress__text) {
  font-size: 13px !important;
  font-weight: 600;
}

:deep(.progress-cell-dialog .el-progress__text) {
  font-size: 14px !important;
  font-weight: 600;
}

/* Reports Dialog Styles */
.reports-summary {
  background: linear-gradient(135deg, #f5f7fa 0%, #e8eef5 100%);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.report-stat {
  text-align: center;
  padding: 12px;
  background: white;
  border-radius: 6px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  font-family: 'Arial', sans-serif;
}

.stat-value.highlight {
  color: #409EFF;
}

.stat-value.consumed {
  color: #F56C6C;
}

.report-amount {
  font-weight: 600;
  color: #67C23A;
}

.cumulative-amount {
  font-weight: 600;
  color: #409EFF;
}
</style>
