<template>
  <div class="allocation-report">
    <el-card class="report-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon class="title-icon" :size="22"><DocumentAdd /></el-icon>
            <span>上报消耗</span>
          </div>
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>

      <div v-else-if="distribution" class="report-content">
        <!-- 配额信息 -->
        <div class="info-section">
          <h3 class="section-title">配额信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="物资名称">
              <span class="material-name">{{ allocation?.materialName }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="物资类别">
              <el-tag :type="getCategoryTagType(allocation?.category)" size="small">
                {{ allocation?.category }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="单位">
              {{ allocation?.unit }}
            </el-descriptions-item>
            <el-descriptions-item label="目标单位">
              {{ distribution.targetUnitName }}
            </el-descriptions-item>
            <!-- 师团/团级显示分配配额 -->
            <el-descriptions-item v-if="!isBattalionOrBelow" label="分配配额">
              <span class="quota-value">{{ formatNumber(distribution.unitQuota) }} {{ allocation?.unit }}</span>
            </el-descriptions-item>
            <el-descriptions-item :label="isBattalionOrBelow ? '已消耗数量' : '已上报数量'">
              <span :class="['completion-value', totalReportedAmount ? '' : 'no-data']">
                {{ totalReportedAmount ? formatNumber(totalReportedAmount) : '0' }} {{ allocation?.unit }}
              </span>
            </el-descriptions-item>
            <!-- 师团/团级显示剩余配额 -->
            <el-descriptions-item v-if="!isBattalionOrBelow" label="剩余配额">
              <span class="remaining-value">
                {{ formatNumber((distribution.unitQuota || 0) - (distribution.actualCompletion || 0)) }} {{ allocation?.unit }}
              </span>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 上报表单 -->
        <div class="form-section">
          <h3 class="section-title">{{ isBattalionOrBelow ? '本次消耗上报' : '本次消耗上报' }}</h3>
          <el-alert
            type="warning"
            :closable="false"
            show-icon
            style="margin-bottom: 20px"
          >
            <template #title>
              <span>{{ isBattalionOrBelow ? '注意：本次消耗数量将累加到已消耗总数中' : '注意：本次上报数量将累加到已上报总数中' }}</span>
            </template>
          </el-alert>
          <el-form 
            ref="formRef" 
            :model="form" 
            :rules="formRules" 
            label-width="120px"
            @submit.prevent="handleSubmit"
          >
            <!-- 连部显示上报目标选择（暂时注释）
            <el-form-item v-if="isCompanyLevel" label="上报到" prop="reportToLevel">
              <el-radio-group v-model="form.reportToLevel">
                <el-radio value="Battalion">
                  <el-tag type="success" size="small">营部</el-tag>
                  <span class="radio-desc">上报到所属营部</span>
                </el-radio>
                <el-radio value="Regiment">
                  <el-tag type="warning" size="small">团部</el-tag>
                  <span class="radio-desc">直接上报到团部</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            -->

            <el-form-item :label="isBattalionOrBelow ? '本次消耗数量' : '本次上报数量'" prop="actualCompletion">
              <el-input-number
                v-model="form.actualCompletion"
                :min="0"
                :max="isBattalionOrBelow ? undefined : (distribution.unitQuota || 0) - (distribution.actualCompletion || 0)"
                :precision="2"
                :step="1"
                style="width: 300px"
              />
              <span class="unit-hint">{{ allocation?.unit }}</span>
            </el-form-item>

            <!-- 师团/团级显示上报后总数 -->
            <el-form-item v-if="!isBattalionOrBelow" label="上报后总数">
              <div class="total-after-report">
                <span class="total-number">{{ formatNumber((distribution.actualCompletion || 0) + (form.actualCompletion || 0)) }}</span>
                <span class="unit-text">{{ allocation?.unit }}</span>
                <span class="separator">/</span>
                <span class="quota-number">{{ formatNumber(distribution.unitQuota || 0) }}</span>
                <span class="unit-text">{{ allocation?.unit }}</span>
              </div>
            </el-form-item>

            <!-- 师团/团级显示完成率 -->
            <el-form-item v-if="!isBattalionOrBelow" label="完成率">
              <div class="completion-rate">
                <el-progress 
                  :percentage="getCompletionPercentage()" 
                  :status="getProgressStatus()"
                  :stroke-width="20"
                  style="width: 300px"
                />
                <span class="rate-text">{{ getCompletionPercentage() }}%</span>
              </div>
            </el-form-item>

            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="form.remarks"
                type="textarea"
                :rows="4"
                placeholder="请输入备注信息（可选）"
                maxlength="500"
                show-word-limit
                style="width: 500px"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" :loading="submitting" @click="handleSubmit">
                <el-icon><Check /></el-icon>
                {{ isBattalionOrBelow ? '提交消耗' : '提交上报' }}
              </el-button>
              <el-button @click="handleBack">
                <el-icon><Close /></el-icon>
                取消
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 上报历史 -->
        <div class="history-section">
          <h3 class="section-title">上报历史</h3>
          <el-table
            v-if="consumptionReports.length > 0"
            :data="reportsWithRecalculatedCumulative"
            stripe
            :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
          >
            <el-table-column label="上报时间" width="180" align="center">
              <template #default="{ row }">
                <div class="time-cell">
                  <el-icon class="time-icon" :size="14"><Clock /></el-icon>
                  <span>{{ formatDate(row.reportedAt) }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="本次上报" width="120" align="center">
              <template #default="{ row }">
                <span class="reported-amount">+{{ formatNumber(row.reportedAmount) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="累计数量" width="120" align="center">
              <template #default="{ row }">
                <span class="cumulative-amount">{{ formatNumber(row.calculatedCumulativeAmount) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="上报人" width="120" align="center">
              <template #default="{ row }">
                <span>{{ row.reportedByUserName || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="150">
              <template #default="{ row }">
                <span class="remarks-text">{{ row.remarks || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template #default="{ row }">
                <el-button
                  v-if="canRequestChange(row)"
                  type="warning"
                  size="small"
                  link
                  @click="openChangeRequestDialog(row)"
                >
                  申请删改
                </el-button>
                <el-tag v-else-if="row.hasPendingRequest" type="info" size="small">
                  申请中
                </el-tag>
                <span v-else class="no-action">-</span>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-else description="暂无上报记录" :image-size="80" />
        </div>

        <!-- 申请删改对话框 -->
        <el-dialog
          v-model="changeRequestDialogVisible"
          title="申请删改"
          width="500px"
          :close-on-click-modal="false"
        >
          <div v-if="selectedReport" class="change-request-info">
            <el-descriptions :column="1" border size="small">
              <el-descriptions-item label="上报时间">
                {{ formatDate(selectedReport.reportedAt) }}
              </el-descriptions-item>
              <el-descriptions-item label="上报数量">
                {{ formatNumber(selectedReport.reportedAmount) }} {{ allocation?.unit }}
              </el-descriptions-item>
              <el-descriptions-item label="备注">
                {{ selectedReport.remarks || '-' }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <el-form
            ref="changeRequestFormRef"
            :model="changeRequestForm"
            :rules="changeRequestRules"
            label-width="100px"
            style="margin-top: 20px"
          >
            <el-form-item label="申请类型" prop="requestType">
              <el-radio-group v-model="changeRequestForm.requestType" class="change-request-radio-group">
                <el-radio value="Delete">
                  <el-tag type="danger" size="small">删除</el-tag>
                  <span class="radio-desc">申请删除此条记录</span>
                </el-radio>
                <el-radio value="Modify">
                  <el-tag type="warning" size="small">修改</el-tag>
                  <span class="radio-desc">申请修改此条记录</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="申请原因" prop="reason">
              <el-input
                v-model="changeRequestForm.reason"
                type="textarea"
                :rows="4"
                placeholder="请输入申请原因"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="changeRequestDialogVisible = false">取消</el-button>
            <el-button type="primary" :loading="changeRequestSubmitting" @click="submitChangeRequest">
              提交申请
            </el-button>
          </template>
        </el-dialog>
      </div>

      <el-empty v-else description="未找到配额分配信息" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { DocumentAdd, Back, Check, Close, Clock } from '@element-plus/icons-vue'
import { allocationsApi, changeRequestsApi, type ConsumptionReport } from '@/api'
import { useAuthStore } from '@/stores/auth'
import type { MaterialAllocation, AllocationDistribution } from '@/types'

interface ConsumptionReportWithPending extends ConsumptionReport {
  hasPendingRequest?: boolean
  reportedByUnitId?: number
}

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

const loading = ref(false)
const submitting = ref(false)
const allocation = ref<MaterialAllocation | null>(null)
const distribution = ref<AllocationDistribution | null>(null)
const consumptionReports = ref<ConsumptionReportWithPending[]>([])
const formRef = ref<FormInstance>()

// 申请删改相关
const changeRequestDialogVisible = ref(false)
const changeRequestSubmitting = ref(false)
const selectedReport = ref<ConsumptionReportWithPending | null>(null)
const changeRequestFormRef = ref<FormInstance>()
const changeRequestForm = reactive({
  requestType: 'Delete' as 'Delete' | 'Modify',
  reason: ''
})

const changeRequestRules: FormRules = {
  requestType: [
    { required: true, message: '请选择申请类型', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入申请原因', trigger: 'blur' },
    { min: 5, message: '申请原因至少5个字符', trigger: 'blur' }
  ]
}

const form = reactive({
  actualCompletion: 0,
  remarks: '',
  reportToLevel: '' as string // 上报目标级别：Battalion（营部）或 Regiment（团部）
})

// 判断是否为连部级别（Company = 4）
const isCompanyLevel = computed(() => {
  return authStore.organizationalLevelNum === 4
})

// 判断是否为营部及以下级别（Battalion = 3, Company = 4）
const isBattalionOrBelow = computed(() => {
  return authStore.organizationalLevelNum >= 3
})

// 计算本单位和下属单位的上报数之和
// 始终使用consumptionReports求和，因为它已经是经过可见性过滤的记录
// 不再回退到distribution.actualCompletion，因为那是所有单位的总上报数
const totalReportedAmount = computed(() => {
  return consumptionReports.value.reduce((sum, report) => sum + report.reportedAmount, 0)
})

// 重新计算累计数量（基于可见范围内的上报记录）
// 因为数据库中的cumulativeAmount是所有单位的累计，需要根据过滤后的记录重新计算
const reportsWithRecalculatedCumulative = computed(() => {
  // 按时间正序排列计算累计
  const sortedByTimeAsc = [...consumptionReports.value].sort(
    (a, b) => new Date(a.reportedAt).getTime() - new Date(b.reportedAt).getTime()
  )
  
  let cumulative = 0
  const reportsWithCumulative = sortedByTimeAsc.map(report => {
    cumulative += report.reportedAmount
    return { ...report, calculatedCumulativeAmount: cumulative }
  })
  
  // 按时间倒序返回（与原始顺序一致）
  return reportsWithCumulative.reverse()
})

// 根据用户级别动态生成验证规则
const formRules = computed<FormRules>(() => {
  const baseRules: FormRules = {
    actualCompletion: [
      { required: true, message: isBattalionOrBelow.value ? '请输入本次消耗数量' : '请输入本次上报数量', trigger: 'blur' },
      { 
        type: 'number', 
        min: 0.01, 
        message: '数量必须大于0', 
        trigger: 'blur' 
      }
    ]
  }
  
  // 连部需要选择上报目标（暂时注释）
  // if (isCompanyLevel.value) {
  //   baseRules.reportToLevel = [
  //     { required: true, message: '请选择上报目标', trigger: 'change' }
  //   ]
  // }
  
  // 只有师团/团级才需要验证不超过剩余配额
  if (!isBattalionOrBelow.value) {
    baseRules.actualCompletion.push({
      validator: (_rule, value, callback) => {
        const remaining = (distribution.value?.unitQuota || 0) - (distribution.value?.actualCompletion || 0)
        if (value > remaining) {
          callback(new Error(`本次上报数量不能超过剩余配额 ${remaining}`))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    })
  }
  
  return baseRules
})

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

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 getCompletionPercentage(): number {
  if (!distribution.value) return 0
  const total = (distribution.value.actualCompletion || 0) + (form.actualCompletion || 0)
  return Math.round((total / distribution.value.unitQuota) * 100)
}

function getProgressStatus(): string {
  const percentage = getCompletionPercentage()
  if (percentage >= 100) return 'success'
  if (percentage >= 60) return ''
  return 'warning'
}

function handleBack() {
  router.back()
}

async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const newTotal = (distribution.value?.actualCompletion || 0) + form.actualCompletion
    
    // 构建确认信息
    let confirmMessage = ''
    // 连部上报目标选择功能暂时注释
    // if (isCompanyLevel.value) {
    //   const targetName = form.reportToLevel === 'Battalion' ? '营部' : '团部'
    //   confirmMessage = `本次消耗数量：${form.actualCompletion} ${allocation.value?.unit}\n上报目标：${targetName}\n\n确认提交吗？`
    // } else 
    if (isBattalionOrBelow.value) {
      confirmMessage = `本次消耗数量：${form.actualCompletion} ${allocation.value?.unit}\n\n确认提交吗？`
    } else {
      confirmMessage = `本次上报数量：${form.actualCompletion} ${allocation.value?.unit}\n上报后总数：${newTotal} ${allocation.value?.unit}\n\n确认提交吗？`
    }
    
    await ElMessageBox.confirm(
      confirmMessage,
      isBattalionOrBelow.value ? '确认消耗' : '确认上报',
      {
        type: 'warning',
        confirmButtonText: isBattalionOrBelow.value ? '确认消耗' : '确认上报',
        cancelButtonText: '取消'
      }
    )

    submitting.value = true
    
    if (!distribution.value) return
    
    // 构建备注信息（上报目标功能暂时注释）
    let remarks = form.remarks || ''
    // if (isCompanyLevel.value && form.reportToLevel) {
    //   const targetName = form.reportToLevel === 'Battalion' ? '营部' : '团部'
    //   remarks = remarks ? `[上报到${targetName}] ${remarks}` : `[上报到${targetName}]`
    // }
    
    // 累加到已有数量
    await allocationsApi.updateDistribution(distribution.value.id, {
      actualCompletion: newTotal,
      remarks: remarks
    })

    ElMessage.success(isBattalionOrBelow.value ? '消耗提交成功' : '上报成功')
    router.back()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || (isBattalionOrBelow.value ? '消耗提交失败' : '上报失败'))
    }
  } finally {
    submitting.value = false
  }
}

async function loadData() {
  loading.value = true
  try {
    const allocationId = Number(route.params.id)
    const distributionId = Number(route.query.distributionId)

    if (!allocationId || !distributionId) {
      ElMessage.error('参数错误')
      router.back()
      return
    }

    // 加载配额信息(包含分配信息)
    allocation.value = await allocationsApi.getById(allocationId)
    
    // 从配额信息中获取分配信息
    distribution.value = allocation.value.distributions?.find(d => d.id === distributionId) || null

    if (!distribution.value) {
      ElMessage.error('未找到配额分配信息')
      router.back()
      return
    }

    // 不再自动填充已上报数据，每次都是新上报
    form.actualCompletion = 0

    // 加载上报历史记录
    await loadConsumptionReports(distributionId)
  } catch {
    ElMessage.error('加载数据失败')
    router.back()
  } finally {
    loading.value = false
  }
}

async function loadConsumptionReports(distributionId: number) {
  try {
    const reports = await allocationsApi.getConsumptionReports(distributionId)
    // 检查每条记录是否有待处理的申请
    consumptionReports.value = await Promise.all(
      reports.map(async (report) => {
        try {
          const { hasPendingRequest } = await changeRequestsApi.checkPending(report.id)
          return { ...report, hasPendingRequest }
        } catch {
          return { ...report, hasPendingRequest: false }
        }
      })
    )
  } catch {
    console.error('加载上报历史失败')
  }
}

// 判断是否可以申请删改（只有本单位的记录才能申请）
function canRequestChange(report: ConsumptionReportWithPending): boolean {
  // 如果已有待处理的申请，不能再申请
  if (report.hasPendingRequest) return false
  // 只有本单位的记录才能申请删改
  // 通过 reportedByUnitId 判断，如果没有这个字段，则通过 reportedByUserName 判断
  // 这里简化处理：如果记录的上报单位是当前用户的单位，则可以申请
  return report.reportedByUnitId === authStore.unitId
}

// 打开申请删改对话框
function openChangeRequestDialog(report: ConsumptionReportWithPending) {
  selectedReport.value = report
  changeRequestForm.requestType = 'Delete'
  changeRequestForm.reason = ''
  changeRequestDialogVisible.value = true
}

// 提交申请删改
async function submitChangeRequest() {
  if (!changeRequestFormRef.value || !selectedReport.value) return
  
  try {
    await changeRequestFormRef.value.validate()
    
    changeRequestSubmitting.value = true
    
    await changeRequestsApi.create({
      consumptionReportId: selectedReport.value.id,
      requestType: changeRequestForm.requestType,
      reason: changeRequestForm.reason
    })
    
    ElMessage.success('申请已提交，等待上级审批')
    changeRequestDialogVisible.value = false
    
    // 刷新上报历史
    if (distribution.value) {
      await loadConsumptionReports(distribution.value.id)
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '提交申请失败')
  } finally {
    changeRequestSubmitting.value = false
  }
}

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

<style scoped>
.allocation-report {
  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;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

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

.loading-container {
  padding: 20px;
}

.report-content {
  padding: 0;
}

.info-section,
.form-section,
.history-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #409EFF;
}

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

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

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

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

.remaining-value {
  font-weight: 600;
  color: #E6A23C;
  font-size: 14px;
}

.total-after-report {
  display: flex;
  align-items: baseline;
  gap: 6px;
  font-family: 'Arial', sans-serif;
}

.total-number {
  font-size: 24px;
  font-weight: 700;
  color: #67C23A;
}

.quota-number {
  font-size: 18px;
  font-weight: 600;
  color: #909399;
}

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

.separator {
  font-size: 18px;
  color: #909399;
  margin: 0 4px;
}

.unit-hint {
  margin-left: 12px;
  color: #909399;
  font-size: 14px;
}

.completion-rate {
  display: flex;
  align-items: center;
  gap: 16px;
}

.rate-text {
  font-size: 16px;
  font-weight: 600;
  color: #409EFF;
  min-width: 50px;
}

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

:deep(.el-descriptions) {
  margin-top: 0;
}

:deep(.el-descriptions__label) {
  width: 120px;
  background-color: #fafafa;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

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

.time-icon {
  color: #909399;
}

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

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

.remarks-text {
  color: #606266;
  font-size: 13px;
}

.history-section :deep(.el-table) {
  margin-top: 16px;
}

.radio-desc {
  margin-left: 8px;
  color: #909399;
  font-size: 13px;
}

.change-request-radio-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.change-request-radio-group :deep(.el-radio) {
  display: flex;
  align-items: center;
  height: auto;
  padding: 8px 0;
  margin-right: 0;
}

.no-action {
  color: #c0c4cc;
}

.change-request-info {
  margin-bottom: 16px;
}
</style>
