<!--
  项目预算记录页面
  包含预算记录列表、预算申请、预算审核等功能
-->
<template>
  <GiPageLayout>
    <GiTable
      row-key="id"
      :data="dataList"
      :columns="tableColumns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 2000 }"
      :pagination="pagination"
      :disabled-tools="['size']"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
      @refresh="search"
    >
      <template #top>
        <GiForm 
          v-model="searchForm" 
          search 
          :columns="queryFormColumns" 
          size="medium" 
          @search="search" 
          @reset="reset"
        />
      </template>
      
      <template #toolbar-left>
        <a-button v-permission="['budget:apply']" type="primary" @click="() => openApplyModal()">
          <template #icon><icon-plus /></template>
          <template #default>预算申请</template>
        </a-button>
      </template>
      
      <template #toolbar-right>
        <a-button v-permission="['budget:export']" @click="exportData">
          <template #icon><icon-download /></template>
          <template #default>导出</template>
        </a-button>
      </template>
      
      <!-- 项目金额 -->
      <template #projectAmount="{ record }">
        <span class="font-medium text-blue-600">{{ record.projectAmount }}万</span>
      </template>
      
      <!-- 申请预算金额 -->
      <template #applyBudgetAmount="{ record }">
        <span class="font-medium text-orange-600">{{ record.applyBudgetAmount }}万</span>
      </template>
      
      <!-- 审核状态 -->
      <template #auditStatus="{ record }">
        <a-tag :color="getStatusColor(record.auditStatus)">
          {{ record.auditStatusLabel }}
        </a-tag>
      </template>
      
      <!-- 操作列 -->
      <template #action="{ record }">
        <a-space>
          <a-link @click="viewDetail(record)">详情</a-link>
          <a-link 
            v-if="record.auditStatus === 'pending'" 
            v-permission="['budget:audit']" 
            @click="openAuditModal(record)"
          >
            审核
          </a-link>
          <a-link 
            v-if="record.auditStatus === 'approved'" 
            v-permission="['budget:apply']" 
            @click="openApplyModal(record.projectId)"
          >
            追加预算
          </a-link>
        </a-space>
      </template>
    </GiTable>

    <!-- 预算申请弹窗 -->
    <BudgetApplyModal
      v-model:visible="applyModalVisible"
      :project-id="selectedProjectId"
      @success="handleApplySuccess"
    />
    
    <!-- 预算审核弹窗 -->
    <BudgetAuditModal
      v-model:visible="auditModalVisible"
      :budget-record="selectedRecord"
      @success="handleAuditSuccess"
    />
    
    <!-- 详情弹窗 -->
    <BudgetDetailModal
      v-model:visible="detailModalVisible"
      :budget-record="selectedRecord"
    />
  </GiPageLayout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { TableColumnData } from '@arco-design/web-vue'
import { 
  listBudgetRecord, 
  exportBudgetRecord,
  type BudgetRecordResp, 
  type BudgetPageQuery 
} from '@/apis/project/budget'

import BudgetApplyModal from './components/BudgetApplyModal.vue'
import BudgetAuditModal from './components/BudgetAuditModal.vue'
import BudgetDetailModal from './components/BudgetDetailModal.vue'

// 搜索表单
let searchForm = reactive<BudgetPageQuery>({
  projectName: '',
  projectCode: '',
  auditStatus: '',
  applicant: '',
  applyTimeStart: '',
  applyTimeEnd: '',
  page: 1,
  size: 10
})

// 查询条件配置
const queryFormColumns = [
  {
    field: 'projectName',
    label: '项目名称',
    type: 'input' as const,
    props: {
      placeholder: '请输入项目名称'
    }
  },
  {
    field: 'projectCode',
    label: '项目编号',
    type: 'input' as const,
    props: {
      placeholder: '请输入项目编号'
    }
  },
  {
    field: 'auditStatus',
    label: '审核状态',
    type: 'select' as const,
    props: {
      placeholder: '请选择审核状态',
      options: [
        { label: '待审核', value: 'pending' },
        { label: '审核通过', value: 'approved' },
        { label: '审核拒绝', value: 'rejected' }
      ]
    }
  },
  {
    field: 'applicant',
    label: '申请人',
    type: 'input' as const,
    props: {
      placeholder: '请输入申请人'
    }
  }
]

// 表格列配置
const tableColumns: TableColumnData[] = [
  { title: '项目名称', dataIndex: 'projectName', width: 150, ellipsis: true, tooltip: true },
  { title: '项目编号', dataIndex: 'projectCode', width: 120 },
  { title: '项目金额(万)', dataIndex: 'projectAmount', slotName: 'projectAmount', width: 120 },
  { title: '项目负责人', dataIndex: 'projectManager', width: 100 },
  { title: '立项日期', dataIndex: 'establishDate', width: 110 },
  { title: '交付日期', dataIndex: 'deliveryDate', width: 110 },
  { title: '客户', dataIndex: 'client', width: 120, ellipsis: true, tooltip: true },
  { title: '备注说明', dataIndex: 'remark', width: 120, ellipsis: true, tooltip: true },
  { title: '申请预算金额(万)', dataIndex: 'applyBudgetAmount', slotName: 'applyBudgetAmount', width: 140 },
  { title: '申请人', dataIndex: 'applicant', width: 100 },
  { title: '申请时间', dataIndex: 'applyTime', width: 160 },
  { title: '审核状态', dataIndex: 'auditStatus', slotName: 'auditStatus', width: 100 },
  { title: '审核说明', dataIndex: 'auditRemark', width: 120, ellipsis: true, tooltip: true },
  { title: '审核人', dataIndex: 'auditor', width: 100 },
  { title: '审核时间', dataIndex: 'auditTime', width: 160 },
  { title: '操作', slotName: 'action', width: 150, fixed: 'right' }
]

// 数据状态
const loading = ref(false)
const dataList = ref<BudgetRecordResp[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true
})

// 搜索和重置
const search = async () => {
  try {
    loading.value = true
    const { data } = await listBudgetRecord(searchForm)
    dataList.value = data.list || []
    pagination.total = data.total || 0
  } catch (error) {
    console.error('查询预算记录失败:', error)
    Message.error('查询预算记录失败')
  } finally {
    loading.value = false
  }
}

const reset = () => {
  Object.assign(searchForm, {
    projectName: '',
    projectCode: '',
    auditStatus: '',
    applicant: '',
    applyTimeStart: '',
    applyTimeEnd: '',
    page: 1,
    size: 10
  })
  pagination.current = 1
  search()
}

// 分页处理
const onPageChange = (page: number) => {
  searchForm.page = page
  pagination.current = page
  search()
}

const onPageSizeChange = (size: number) => {
  searchForm.size = size
  searchForm.page = 1
  pagination.pageSize = size
  pagination.current = 1
  search()
}

// 弹窗状态
const applyModalVisible = ref(false)
const auditModalVisible = ref(false)
const detailModalVisible = ref(false)
const selectedProjectId = ref('')
const selectedRecord = ref<BudgetRecordResp | null>(null)

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    'pending': 'orange',
    'approved': 'green', 
    'rejected': 'red'
  }
  return colorMap[status] || 'gray'
}

// 打开预算申请弹窗
const openApplyModal = (projectId?: string) => {
  selectedProjectId.value = projectId || ''
  applyModalVisible.value = true
}

// 打开预算审核弹窗
const openAuditModal = (record: BudgetRecordResp) => {
  selectedRecord.value = record
  auditModalVisible.value = true
}

// 查看详情
const viewDetail = (record: BudgetRecordResp) => {
  selectedRecord.value = record
  detailModalVisible.value = true
}

// 预算申请成功回调
const handleApplySuccess = () => {
  Message.success('预算申请提交成功')
  search()
}

// 预算审核成功回调
const handleAuditSuccess = () => {
  Message.success('预算审核完成')
  search()
}

// 导出数据
const exportData = async () => {
  try {
    const response = await exportBudgetRecord(searchForm)
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.download = `项目预算记录_${new Date().toLocaleDateString()}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    Message.success('导出成功')
  } catch (error) {
    Message.error('导出失败')
  }
}

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

<style scoped lang="scss">
.font-medium {
  font-weight: 500;
}

.text-blue-600 {
  color: rgb(37, 99, 235);
}

.text-orange-600 {
  color: rgb(234, 88, 12);
}
</style> 