<template>
  <div class="allocation-form">
    <el-card>
      <template #header>
        <span>{{ isEdit ? '编辑配额' : '创建配额' }}</span>
      </template>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" v-loading="loading">
        <el-form-item label="物资类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择物资类别" style="width: 100%">
            <el-option
              v-for="cat in categories"
              :key="cat.id"
              :label="cat.name"
              :value="cat.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物资名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物资名称" />
        </el-form-item>
        <el-form-item label="计量单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入计量单位" />
        </el-form-item>
        <el-form-item label="总配额" prop="totalQuota">
          <el-input-number v-model="form.totalQuota" :min="0" :precision="2" />
        </el-form-item>
        
        <el-divider content-position="left">配额分配</el-divider>
        
        <el-form-item label="分配明细">
          <div class="distribution-section">
            <div class="distribution-list">
              <div v-for="(dist, index) in form.distributions" :key="index" class="distribution-item">
                <el-select v-model="dist.targetUnitId" placeholder="选择目标单位" style="width: 200px">
                  <el-option
                    v-for="unit in subordinateUnits"
                    :key="unit.id"
                    :label="unit.name"
                    :value="unit.id"
                  />
                </el-select>
                <el-input-number v-model="dist.unitQuota" :min="0" :precision="2" placeholder="配额" />
                <el-button type="danger" :icon="Delete" circle @click="removeDistribution(index)" />
              </div>
            </div>
            <div class="distribution-actions">
              <el-button type="primary" text @click="addDistribution">
                <el-icon><Plus /></el-icon>
                添加分配
              </el-button>
              <span class="quota-info">已分配: {{ distributedTotal }}</span>
              <span class="quota-info" :class="{ 'over-quota': distributedTotal > form.totalQuota }">
                剩余: {{ (form.totalQuota - distributedTotal).toFixed(2) }}
              </span>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :loading="saving" @click="handleSubmit">保存</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { allocationsApi, organizationsApi, materialCategoriesApi } from '@/api'
import { useAuthStore } from '@/stores/auth'
import type { OrganizationalUnit, DistributionRequest } from '@/types'
import type { MaterialCategory } from '@/api/materialCategories'

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

const isEdit = computed(() => !!route.params.id)
const formRef = ref<FormInstance>()
const loading = ref(false)
const saving = ref(false)
const subordinateUnits = ref<OrganizationalUnit[]>([])
const categories = ref<MaterialCategory[]>([])

const form = reactive({
  category: '',
  materialName: '',
  unit: '',
  totalQuota: 0,
  distributions: [] as DistributionRequest[]
})

const rules: FormRules = {
  category: [{ required: true, message: '请输入物资类别', trigger: 'blur' }],
  materialName: [{ required: true, message: '请输入物资名称', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入计量单位', trigger: 'blur' }],
  totalQuota: [{ required: true, message: '请输入总配额', trigger: 'blur' }]
}

const distributedTotal = computed(() => {
  return form.distributions.reduce((sum, d) => sum + (d.unitQuota || 0), 0)
})

function addDistribution() {
  form.distributions.push({ targetUnitId: 0, unitQuota: 0 })
}

function removeDistribution(index: number) {
  form.distributions.splice(index, 1)
}

async function loadSubordinateUnits() {
  if (!authStore.user) return
  try {
    subordinateUnits.value = await organizationsApi.getAllocationUnits(authStore.user.organizationalUnitId)
  } catch {
    ElMessage.error('加载可分配单位失败')
  }
}

async function loadCategories() {
  try {
    categories.value = await materialCategoriesApi.getAll(true) // 只加载启用的类别
  } catch {
    ElMessage.error('加载物资类别失败')
  }
}

async function loadAllocation() {
  if (!isEdit.value) return
  
  loading.value = true
  try {
    const allocation = await allocationsApi.getById(Number(route.params.id))
    form.category = allocation.category
    form.materialName = allocation.materialName
    form.unit = allocation.unit
    form.totalQuota = allocation.totalQuota
    form.distributions = allocation.distributions.map(d => ({
      targetUnitId: d.targetUnitId,
      unitQuota: d.unitQuota
    }))
  } catch {
    ElMessage.error('加载配额信息失败')
  } finally {
    loading.value = false
  }
}

async function handleSubmit() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    if (distributedTotal.value > form.totalQuota) {
      ElMessage.error('分配配额总和不能超过总配额')
      return
    }
    
    if (distributedTotal.value < form.totalQuota) {
      ElMessage.error('有配额未分配，无法提交')
      return
    }
    
    saving.value = true
    try {
      if (isEdit.value) {
        await allocationsApi.update(Number(route.params.id), {
          category: form.category,
          materialName: form.materialName,
          unit: form.unit,
          totalQuota: form.totalQuota,
          distributions: form.distributions.filter(d => d.targetUnitId > 0)
        })
        ElMessage.success('更新成功')
      } else {
        await allocationsApi.create({
          category: form.category,
          materialName: form.materialName,
          unit: form.unit,
          totalQuota: form.totalQuota,
          distributions: form.distributions.filter(d => d.targetUnitId > 0)
        })
        ElMessage.success('创建成功')
      }
      router.push('/allocations')
    } catch {
      ElMessage.error('操作失败')
    } finally {
      saving.value = false
    }
  })
}

onMounted(() => {
  loadSubordinateUnits()
  loadCategories()
  loadAllocation()
})
</script>

<style scoped>
.distribution-section {
  width: 100%;
}

.distribution-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 12px;
}

.distribution-item {
  display: flex;
  gap: 12px;
  align-items: center;
}

.distribution-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.quota-info {
  color: #606266;
  font-size: 14px;
}

.over-quota {
  color: #F56C6C;
  font-weight: bold;
}
</style>
