<!--
  预算申请弹窗组件
-->
<template>
  <a-modal
    v-model:visible="visible"
    title="预算申请"
    width="1200px"
    :mask-closable="false"
    @before-ok="handleSubmit"
    @cancel="handleCancel"
  >
    <!-- 项目基本信息 -->
    <div class="project-info-section">
      <a-descriptions 
        :column="5" 
        bordered 
        size="small"
        class="project-info"
      >
        <a-descriptions-item label="项目名称">{{ projectInfo?.projectName || '项目一' }}</a-descriptions-item>
        <a-descriptions-item label="项目编号">{{ projectInfo?.projectCode || 'HWPC0001' }}</a-descriptions-item>
        <a-descriptions-item label="项目金额(万)">{{ (projectInfo as any)?.projectAmount || '126.00' }}</a-descriptions-item>
        <a-descriptions-item label="项目负责人">{{ projectInfo?.projectManager || projectInfo?.projectManagerName || '丁曼容' }}</a-descriptions-item>
        <a-descriptions-item label="客户">{{ projectInfo?.client || '義和大学' }}</a-descriptions-item>
        <a-descriptions-item label="交付日期">{{ projectInfo?.endDate || '2025-05-01' }}</a-descriptions-item>
        <a-descriptions-item label="预算总金额(万)">{{ totalBudgetAmount.toFixed(2) }}</a-descriptions-item>
      </a-descriptions>
    </div>

    <!-- 申请预算项 -->
    <div class="budget-items-section">
      <h3 class="section-title">申请预算项</h3>
      
      <a-table
        :data="budgetItems"
        :columns="budgetColumns"
        :pagination="false"
        size="small"
        class="budget-table"
      >
        <template #budgetName="{ record, rowIndex }">
          <a-input 
            v-model="record.budgetName" 
            placeholder="请输入预算名称"
            :style="{ width: '100%' }"
          />
        </template>
        
        <template #budgetType="{ record, rowIndex }">
          <a-select 
            v-model="record.budgetType" 
            placeholder="请选择"
            :style="{ width: '100%' }"
            :options="budgetTypeOptions"
          />
        </template>
        
        <template #budgetAmount="{ record, rowIndex }">
          <a-input-number 
            v-model="record.budgetAmount" 
            placeholder="0.00"
            :precision="2"
            :min="0"
            :style="{ width: '100%' }"
          />
        </template>
        
        <template #budgetDescription="{ record, rowIndex }">
          <a-input 
            v-model="record.budgetDescription" 
            placeholder="--"
            :style="{ width: '100%' }"
          />
        </template>
        
        <template #attachments="{ record, rowIndex }">
          <a-upload
            :file-list="record.attachments || []"
            :show-file-list="false"
            :custom-request="(option) => handleUpload(option, rowIndex)"
          >
            <a-button type="primary" size="small">上传</a-button>
          </a-upload>
          <div v-if="record.attachments?.length" class="attachment-list">
            <a-tag
              v-for="file in record.attachments"
              :key="file.id"
              closable
              size="small"
              @close="removeAttachment(rowIndex, file.id)"
            >
              {{ file.name }}
            </a-tag>
          </div>
        </template>
        
        <template #action="{ record, rowIndex }">
          <a-button 
            type="text" 
            status="danger" 
            size="small"
            @click="removeItem(rowIndex)"
          >
            删除
          </a-button>
        </template>
      </a-table>
      
      <!-- 新增预算项按钮 -->
      <div class="add-item-btn">
        <a-button type="dashed" @click="addBudgetItem">
          <template #icon><icon-plus /></template>
          新增预算项
        </a-button>
      </div>
    </div>

    <!-- 温馨提示 -->
    <div class="tips-section">
      <a-alert 
        type="info" 
        show-icon
        message="手动新填、删除预算项及金额。"
        banner
      />
    </div>

    <template #footer>
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleSubmit">提交申请</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { Message, type TableColumnData } from '@arco-design/web-vue'
import { 
  applyBudget, 
  getBudgetTypes, 
  uploadBudgetAttachment,
  type BudgetItemResp,
  type BudgetApplyReq 
} from '@/apis/project/budget'
import { getProject, type ProjectResp } from '@/apis/project'

interface Props {
  visible: boolean
  projectId?: string
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  projectId: ''
})

const emit = defineEmits<Emits>()

const visible = ref(props.visible)
const projectInfo = ref<ProjectResp | null>(null)
const budgetTypeOptions = ref<Array<{ label: string; value: string }>>([])

// 预算项数据
const budgetItems = ref<BudgetItemResp[]>([
  {
    budgetName: '设备采购',
    budgetType: '采购',
    budgetAmount: 50.00,
    budgetDescription: '--',
    attachments: []
  },
  {
    budgetName: '人工费用',
    budgetType: '人工',
    budgetAmount: 16.00,
    budgetDescription: '--',
    attachments: []
  },
  {
    budgetName: '管理费用',
    budgetType: '管理费',
    budgetAmount: 8.00,
    budgetDescription: '--',
    attachments: []
  },
  {
    budgetName: '',
    budgetType: '',
    budgetAmount: 0,
    budgetDescription: '',
    attachments: []
  }
])

// 表格列配置
const budgetColumns: TableColumnData[] = [
  { 
    title: '预算名称', 
    dataIndex: 'budgetName', 
    slotName: 'budgetName',
    width: 150
  },
  { 
    title: '预算类型', 
    dataIndex: 'budgetType', 
    slotName: 'budgetType',
    width: 120
  },
  { 
    title: '预算金额(万)', 
    dataIndex: 'budgetAmount', 
    slotName: 'budgetAmount',
    width: 130
  },
  { 
    title: '预算说明', 
    dataIndex: 'budgetDescription', 
    slotName: 'budgetDescription',
    width: 150
  },
  { 
    title: '附件', 
    dataIndex: 'attachments', 
    slotName: 'attachments',
    width: 200
  },
  { 
    title: '操作', 
    dataIndex: 'action', 
    slotName: 'action',
    width: 80
  }
]

// 计算预算总金额
const totalBudgetAmount = computed(() => {
  return budgetItems.value.reduce((sum, item) => sum + (item.budgetAmount || 0), 0)
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  visible.value = newVal
  if (newVal) {
    loadProjectInfo()
    loadBudgetTypes()
  }
})

watch(visible, (newVal) => {
  emit('update:visible', newVal)
})

// 加载项目信息
const loadProjectInfo = async () => {
  if (!props.projectId) return
  
  try {
    const { data } = await getProject(props.projectId)
    projectInfo.value = data
  } catch (error) {
    console.error('加载项目信息失败:', error)
  }
}

// 加载预算类型选项
const loadBudgetTypes = async () => {
  try {
    const { data } = await getBudgetTypes()
    budgetTypeOptions.value = data
  } catch (error) {
    console.error('加载预算类型失败:', error)
    // 使用默认选项
    budgetTypeOptions.value = [
      { label: '采购', value: '采购' },
      { label: '人工', value: '人工' },
      { label: '管理费', value: '管理费' },
      { label: '设备', value: '设备' },
      { label: '运输', value: '运输' }
    ]
  }
}

// 新增预算项
const addBudgetItem = () => {
  budgetItems.value.push({
    budgetName: '',
    budgetType: '',
    budgetAmount: 0,
    budgetDescription: '',
    attachments: []
  })
}

// 删除预算项
const removeItem = (index: number) => {
  if (budgetItems.value.length > 1) {
    budgetItems.value.splice(index, 1)
  } else {
    Message.warning('至少保留一个预算项')
  }
}

// 处理文件上传
const handleUpload = async (option: any, rowIndex: number) => {
  try {
    const response = await uploadBudgetAttachment(option.file)
    if (!budgetItems.value[rowIndex].attachments) {
      budgetItems.value[rowIndex].attachments = []
    }
    budgetItems.value[rowIndex].attachments!.push(response.data)
    Message.success('文件上传成功')
  } catch (error) {
    Message.error('文件上传失败')
  }
}

// 删除附件
const removeAttachment = (rowIndex: number, fileId: string) => {
  const attachments = budgetItems.value[rowIndex].attachments || []
  const index = attachments.findIndex(file => file.id === fileId)
  if (index > -1) {
    attachments.splice(index, 1)
  }
}

// 提交申请
const handleSubmit = async () => {
  try {
    // 验证必填项
    const validItems = budgetItems.value.filter(item => 
      item.budgetName && item.budgetType && item.budgetAmount > 0
    )
    
    if (validItems.length === 0) {
      Message.warning('请至少填写一个完整的预算项')
      return false
    }
    
    const applyData: BudgetApplyReq = {
      projectId: props.projectId || '',
      budgetItems: validItems,
      totalAmount: totalBudgetAmount.value
    }
    
    await applyBudget(applyData)
    Message.success('预算申请提交成功')
    emit('success')
    return true
  } catch (error) {
    console.error('提交申请失败:', error)
    Message.error('提交申请失败')
    return false
  }
}

// 取消操作
const handleCancel = () => {
  // 重置表单数据
  budgetItems.value = [
    {
      budgetName: '',
      budgetType: '',
      budgetAmount: 0,
      budgetDescription: '',
      attachments: []
    }
  ]
}
</script>

<style scoped lang="scss">
.project-info-section {
  margin-bottom: 24px;
  
  .project-info {
    background: #fafafa;
  }
}

.budget-items-section {
  margin-bottom: 24px;
  
  .section-title {
    color: #1890ff;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
    padding-left: 8px;
    border-left: 3px solid #1890ff;
  }
  
  .budget-table {
    margin-bottom: 16px;
  }
  
  .add-item-btn {
    text-align: center;
    margin-top: 16px;
  }
  
  .attachment-list {
    margin-top: 8px;
    
    .arco-tag {
      margin-right: 4px;
      margin-bottom: 4px;
    }
  }
}

.tips-section {
  margin-bottom: 16px;
}
</style> 