<template>
    <div class="procurementPlan">
        <el-row :gutter="20">
            <el-col :span="13">
                <el-card>
                    <div style="display: flex;align-items: center;height: 120px;justify-content: space-around;">
                        <div class="img">
                            <img src="/assets/caigou.png" alt="">
                        </div>
                        <div class="item">
                            <div class="text">
                                待审批计划
                            </div>
                            <div class="count" style="color: rgba(255, 178, 30, 1);">
                                12
                            </div>
                        </div>
                        <div class="item">
                            <div class="text">
                                已批准计划
                            </div>
                            <div class="count" style="color: rgba(67, 101, 220, 1);">
                                28
                            </div>
                        </div>
                        <div class="item">
                            <div class="text">
                                采购中计划
                            </div>
                            <div class="count" style="color: rgba(113, 214, 213, 1);">
                                15
                            </div>
                        </div>
                        <div class="item">
                            <div class="text">
                                已完成计划
                            </div>
                            <div class="count" style="color: rgba(0, 184, 122, 1);">
                                86
                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="11">
                <el-card>
                    <div style="display: flex;align-items: center;height: 120px;justify-content: space-around;">
                        <div class="img">
                            <img src="/assets/qian.jpg" alt="">
                        </div>
                        <div class="item">
                            <div class="text">
                                本年度已采购金额
                            </div>
                            <div class="count" style="color: rgba(255, 153, 0, 1);">
                                520,000.00
                            </div>
                        </div>
                        <div class="item">
                            <div class="text">
                                本年度采购预算金额
                            </div>
                            <div class="count" style="color: rgba(67, 101, 220, 1);">
                                3,000,000.00
                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-row style="margin-top: 20px;">
            <el-col :span="24">
                <el-card style="border-radius: 10px;">
                    <div class="content">
                        <div class="tabs">
                            <el-button type="success">导出</el-button>
                            <el-button type="primary" @click="isNewProcurementDialogVisible = true">新建采购申请单</el-button>
                        </div>

                        <!-- 标签页导航 -->
                        <div class="tabs">
                            <el-badge :value="pendingCount" type="warning">
                                <el-button :type="activeTab === 'pending' ? 'primary' : ''"
                                    @click="changeTab('pending')">待审批</el-button>
                            </el-badge>
                            <el-badge :value="purchasingCount" type="info">
                                <el-button :type="activeTab === 'purchasing' ? 'primary' : ''"
                                    @click="changeTab('purchasing')">采购中</el-button>
                            </el-badge>
                            <el-badge :value="rejectedCount" type="danger">
                                <el-button :type="activeTab === 'rejected' ? 'primary' : ''"
                                    @click="changeTab('rejected')">
                                    未通过
                                </el-button>
                            </el-badge>
                            <el-badge :value="approvedCount" type="primary">
                                <el-button :type="activeTab === 'approved' ? 'primary' : ''"
                                    @click="changeTab('approved')">已通过</el-button>
                            </el-badge>
                            <el-badge :value="completedCount" type="success">
                                <el-button :type="activeTab === 'completed' ? 'primary' : ''"
                                    @click="changeTab('completed')">已完成</el-button>
                            </el-badge>
                        </div>
                        <!-- 表格 -->
                         <el-table :data="filteredTableData" border style="width: 100%;margin-top: 15px;">
                            <el-table-column type="selection" width="55" align="center" />
                            <el-table-column prop="planNumber" label="计划编号" align="center" />
                            <el-table-column prop="planName" label="计划名称" align="center" />
                            <el-table-column prop="equipmentType" label="设备类型" align="center" />
                            <el-table-column prop="requestDept" label="申请部门" align="center" />
                            <el-table-column prop="applicant" label="申请人" align="center" />
                            <el-table-column prop="requestDate" label="申请日期" align="center" />
                            <el-table-column prop="estimatedAmount" label="预计金额" align="center" />
                            <el-table-column label="状态" align="center">
                                <template #default="scope">
                                    <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" fixed="right" width="80" align="center">
                                <template #default="scope">
                                    <el-button type="text" @click="handleView(scope.row)">查看</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <!-- 分页 -->
                        <div class="pagination-section">
                            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                                :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                                layout="total, sizes, prev, pager, next, jumper" :total="total" background />
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-dialog v-model="isNewProcurementDialogVisible" title="新建采购申请单" width="60%" :close-on-click-modal="false">
            <div class="new-procurement-form">
                <!-- 基础信息 -->
                <div class="form-section">
                    <h3>基础信息</h3>
                    <!-- 输入框行 -->
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="计划名称">
                                <el-input v-model="newProcurementForm.planName" placeholder="请填写" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="合同名称">
                                <el-input v-model="newProcurementForm.contractName" placeholder="请填写" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- 下拉框行 -->
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="合同类型">
                                <el-select v-model="newProcurementForm.contractType" placeholder="请选择">
                                    <el-option v-for="option in wz_contract_type" :key="option.value" :label="option.label" :value="option.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="采购类型">
                                <el-select v-model="newProcurementForm.procurementType" placeholder="请选择">
                                    <el-option v-for="option in wz_purchase_type" :key="option.value" :label="option.label" :value="option.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="仓库地址">
                                <el-select v-model="newProcurementForm.contractAddress" placeholder="请选择">
                                    <el-option v-for="option in contractAddressOptions" :key="option.value" :label="option.label" :value="option.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>

                <!-- 供应商信息 -->
                <div class="form-section">
                    <h3>供应商信息</h3>
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item label="供应商单位">
                                <el-select v-model="newProcurementForm.supplierUnit" placeholder="请选择">
                                    <el-option v-for="option in supplierUnitOptions" :key="option.value" :label="option.label" :value="option.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="送货时间">
                                <el-date-picker
                                    v-model="newProcurementForm.deliveryTime"
                                    type="date"
                                    placeholder="请选择送货日期"
                                    value-format="YYYY-MM-DD"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>

                <!-- 产品信息 -->
                <div class="form-section">
                    <h3>产品信息</h3>
                    <el-table :data="newProcurementForm.products" border style="width: 100%">
                        <el-table-column prop="productName" label="产品名称">
                            <template #default="scope">
                                <el-input v-model="scope.row.productName" placeholder="请填写" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="productModel" label="产品型号">
                            <template #default="scope">
                                <el-input v-model="scope.row.productModel" placeholder="请填写" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="productPrice" label="产品单价">
                            <template #default="scope">
                                <el-input v-model="scope.row.productPrice" placeholder="请填写" type="number" @change="calculateTotalPrice(scope.row)" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="purchaseQuantity" label="购买数量">
                            <template #default="scope">
                                <el-input v-model="scope.row.purchaseQuantity" placeholder="请填写" type="number" @change="calculateTotalPrice(scope.row)" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="unit" label="单位">
                            <template #default="scope">
                                <el-input v-model="scope.row.unit" placeholder="请填写" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="totalPrice" label="合计" :formatter="calculateTotalPrice">
                            <template #default="scope">
                                <span>{{ calculateTotalPrice(scope.row) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" fixed="right" width="80">
                            <template #default="scope">
                                <el-button type="text" @click="removeProduct(scope.$index)"
                                    :disabled="newProcurementForm.products.length <= 1">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button type="primary" size="small" @click="addProduct" style="margin-top: 10px">添加产品</el-button>
                </div>

                <!-- 合同条款 -->
                <div class="form-section">
                    <h3>合同条款</h3>
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item label="付款条件">
                                <el-select v-model="newProcurementForm.paymentTerms" placeholder="请选择">
                                    <el-option label="请选择" value="" />
                                    <el-option v-for="option in wz_payment_terms" :key="option.value" :label="option.label" :value="option.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="发票开具方式">
                                <el-select v-model="newProcurementForm.settlementMethod" placeholder="请选择">
                                    <el-option label="请选择" value="" />
                                    <el-option v-for="option in wz_invoicing_way" :key="option.value" :label="option.label" :value="option.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>

                <!-- 附件上传 -->
                <div class="form-section">
                    <h3>附件上传</h3>
                    <div class="upload-section">
                        <el-upload class="upload-demo" action="" :on-preview="handlePreview" :on-remove="handleRemove"
                            :before-remove="beforeRemove" multiple :limit="5" :on-exceed="handleExceed"
                            :file-list="newProcurementForm.fileList" list-type="text">
                            <el-button type="primary" :icon="Upload">上传文件</el-button>
                            <template #tip>
                                <div class="el-upload__tip">
                                    请将文件拖到此处，或点击上传<br>
                                    最多上传5个文件，单个文件大小不超过20M
                                </div>
                            </template>
                        </el-upload>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancelNewProcurement">取消</el-button>
                    <el-button @click="saveDraft">保存草稿</el-button>
                    <el-button type="primary" @click="submitProcurement">提交申请</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<style sc oped lang="scss">
.procurementPlan {
    background-color: #F2F8FC;
    padding: 20px;
}

.img {
    img {
        display: block;
        width: 80px;
        height: 80px;
    }
}

.item {
    text-align: center;

    .text {
        font-size: 14px;
    }

    .count {
        font-size: 25px;
        font-weight: 600;
        text-align: left;
        margin-top: 10px;
    }
}

.tabs {
    display: flex;
    gap: 10px;
    padding: 10px 0;
}

.content {
    padding: 10px 0;
}

/* 分页区域样式 */
.pagination-section {
    background-color: #fff;
    border-radius: 8px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 15px;
    padding: 10px 0;
}

.pagination-controls .el-pagination {
    margin: 0;
}

.pagination-controls .el-pagination button {
    min-width: 32px;
    height: 32px;
    line-height: 32px;
    border-radius: 4px;
}

.pagination-controls .el-pagination .el-pager li {
    min-width: 32px;
    height: 32px;
    line-height: 32px;
    border-radius: 4px;
}

.pagination-controls .el-pagination .el-pager li.active {
    background-color: #409eff;
    color: #fff;
}
</style>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { Upload } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useProcurementDraftStore } from '@/store/modules/procurementDraft';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wz_invoicing_way,wz_payment_terms,wz_purchase_type,wz_contract_type} = toRefs<any>(proxy?.useDict('wz_invoicing_way','wz_payment_terms','wz_purchase_type','wz_contract_type'));

const router = useRouter();
// 新建采购申请单对话框是否可见
const isNewProcurementDialogVisible = ref(false);

// 当前激活的标签页
const activeTab = ref('pending');

// 计算各状态的数量
const pendingCount = computed(() => {
    return tableData.value.filter(item => item.status === '待审批').length;
});

const purchasingCount = computed(() => {
    return tableData.value.filter(item => item.status === '采购中').length;
});

const rejectedCount = computed(() => {
    return tableData.value.filter(item => item.status === '未通过').length;
});

const approvedCount = computed(() => {
    return tableData.value.filter(item => item.status === '已通过').length;
});

const completedCount = computed(() => {
    return tableData.value.filter(item => item.status === '已完成').length;
});
// 下拉框选项数据
const contractAddressOptions = [
    { label: '主仓库', value: 'main' },
    { label: '一号仓库', value: 'warehouse1' },
    { label: '二号仓库', value: 'warehouse2' },
    { label: '三号仓库', value: 'warehouse3' },
    { label: '车间仓库', value: 'workshop' }
];

const supplierUnitOptions = [
    { label: '供应商A', value: 'supplierA' },
    { label: '供应商B', value: 'supplierB' },
    { label: '供应商C', value: 'supplierC' },
    { label: '供应商D', value: 'supplierD' },
    { label: '供应商E', value: 'supplierE' }
];







// 新建采购申请单表单数据
const newProcurementForm = reactive({
    planName: '',
    contractName: '',
    contractType: '',
    procurementType: '',
    contractAddress: '',
    supplierUnit: '',
    deliveryTime: '',
    paymentTerms: '',
    settlementMethod: '',
    products: [{
        productName: '',
        productModel: '',
        productPrice: '',
        purchaseQuantity: '',
        unit: ''
    }],
    fileList: []
});
// 表格数据
const tableData = ref([
    {
        planNumber: 'PLAN-2023-0615-001',
        planName: 'Q2风电轴承采购计划',
        equipmentType: '风电设备',
        requestDept: '运维部',
        applicant: '王主管',
        requestDate: '2023-06-15 10:30',
        estimatedAmount: '300,000.00',
        status: '待审批'
    },
    {
        planNumber: 'PLAN-2023-0615-002',
        planName: '发电机维修备件采购',
        equipmentType: '发电设备',
        requestDept: '维修部',
        applicant: '李工程师',
        requestDate: '2023-06-16 09:15',
        estimatedAmount: '150,000.00',
        status: '待审批'
    },
    {
        planNumber: 'PLAN-2023-0615-003',
        planName: 'Q2润滑油采购计划',
        equipmentType: '通用设备',
        requestDept: '运维部',
        applicant: '张助理',
        requestDate: '2023-06-17 14:20',
        estimatedAmount: '50,000.00',
        status: '待审批'
    },
    {
        planNumber: 'PLAN-2023-0614-004',
        planName: '液压系统配件采购',
        equipmentType: '液压设备',
        requestDept: '工程部',
        applicant: '赵经理',
        requestDate: '2023-06-14 11:45',
        estimatedAmount: '220,000.00',
        status: '采购中'
    },
    {
        planNumber: 'PLAN-2023-0613-005',
        planName: '控制面板更新采购',
        equipmentType: '电气设备',
        requestDept: '电气部',
        applicant: '陈工程师',
        requestDate: '2023-06-13 16:10',
        estimatedAmount: '180,000.00',
        status: '采购中'
    },
    {
        planNumber: 'PLAN-2023-0612-006',
        planName: '安全防护装备采购',
        equipmentType: '安全设备',
        requestDept: '安全部',
        applicant: '孙主管',
        requestDate: '2023-06-12 08:50',
        estimatedAmount: '80,000.00',
        status: '未通过'
    },
    {
        planNumber: 'PLAN-2023-0611-007',
        planName: '水泵维修配件采购',
        equipmentType: '水处理设备',
        requestDept: '水处理部',
        applicant: '周工程师',
        requestDate: '2023-06-11 13:30',
        estimatedAmount: '60,000.00',
        status: '已通过'
    },
    {
        planNumber: 'PLAN-2023-0610-008',
        planName: '风机叶片检测设备采购',
        equipmentType: '检测设备',
        requestDept: '质检部',
        applicant: '吴经理',
        requestDate: '2023-06-10 10:20',
        estimatedAmount: '450,000.00',
        status: '已通过'
    },
    {
        planNumber: 'PLAN-2023-0609-009',
        planName: '仓库货架更新采购',
        equipmentType: '仓储设备',
        requestDept: '仓储部',
        applicant: '郑主管',
        requestDate: '2023-06-09 15:40',
        estimatedAmount: '90,000.00',
        status: '已完成'
    },
    {
        planNumber: 'PLAN-2023-0608-010',
        planName: '办公设备更新采购',
        equipmentType: '办公设备',
        requestDept: '行政部',
        applicant: '冯助理',
        requestDate: '2023-06-08 11:10',
        estimatedAmount: '120,000.00',
        status: '已完成'
    },
    {
        planNumber: 'PLAN-2023-0607-011',
        planName: '消防设备年检采购',
        equipmentType: '消防设备',
        requestDept: '安全部',
        applicant: '蒋经理',
        requestDate: '2023-06-07 09:30',
        estimatedAmount: '40,000.00',
        status: '已完成'
    },
    {
        planNumber: 'PLAN-2023-0606-012',
        planName: '网络设备升级采购',
        equipmentType: 'IT设备',
        requestDept: 'IT部',
        applicant: '沈工程师',
        requestDate: '2023-06-06 14:50',
        estimatedAmount: '160,000.00',
        status: '已完成'
    }
]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = computed(() => filteredTableData.value.length);

// 状态映射关系
const statusMap = {
    pending: '待审批',
    purchasing: '采购中',
    rejected: '未通过',
    approved: '已通过',
    completed: '已完成'
};

// 根据activeTab筛选后的数据
const filteredTableData = computed(() => {
    if (activeTab.value === 'all') {
        return tableData.value;
    }
    return tableData.value.filter(item => item.status === statusMap[activeTab.value]);
});

// 切换标签页
const changeTab = (tab) => {
    activeTab.value = tab;
    currentPage.value = 1; // 切换标签页时重置到第一页
};

// 获取状态标签类型
const getStatusTagType = (status) => {
    switch (status) {
        case '待审批':
            return 'warning';
        case '采购中':
            return 'info';
        case '未通过':
            return 'danger';
        case '已通过':
            return 'primary';
        case '已完成':
            return 'success';
        default:
            return '';
    }
};

// 查看详情
const handleView = (row) => {
    console.log('查看采购计划详情:', row);
    router.push({
        path: '/materialManagement/planDetails',
        query: {
            planNumber: row.planNumber
        }
    });
    // 这里可以实现查看详情的逻辑，比如打开详情弹窗或跳转到详情页
};

// 分页大小变化
const handleSizeChange = (size) => {
    pageSize.value = size;
    currentPage.value = 1;
};

// 当前页码变化
const handleCurrentChange = (current) => {
    currentPage.value = current;
};

// 计算产品总价
const calculateTotalPrice = (row) => {
    if (!row.productPrice || !row.purchaseQuantity) {
        return '0.00';
    }
    const price = parseFloat(row.productPrice);
    const quantity = parseInt(row.purchaseQuantity);
    if (isNaN(price) || isNaN(quantity)) {
        return '0.00';
    }
    return (price * quantity).toFixed(2);
};

// 添加产品
const addProduct = () => {
    newProcurementForm.products.push({
        productName: '',
        productModel: '',
        productPrice: '',
        purchaseQuantity: '',
        unit: ''
    });
};

// 删除产品
const removeProduct = (index) => {
    if (newProcurementForm.products.length <= 1) {
        ElMessage({ message: '至少保留一个产品信息', type: 'warning' });
        return;
    }
    newProcurementForm.products.splice(index, 1);
};

// 重置新建采购申请表单
const resetNewProcurementForm = () => {
    newProcurementForm.planName = '';
    newProcurementForm.contractName = '';
    newProcurementForm.contractType = '';
    newProcurementForm.procurementType = '';
    newProcurementForm.contractAddress = '';
    newProcurementForm.supplierUnit = '';
    newProcurementForm.deliveryTime = '';
    newProcurementForm.paymentTerms = '';
    newProcurementForm.settlementMethod = '';
    newProcurementForm.products = [{
        productName: '',
        productModel: '',
        productPrice: '',
        purchaseQuantity: '',
        unit: ''
    }];
    newProcurementForm.fileList = [];
};

// 取消新建采购申请
const cancelNewProcurement = () => {
    // 检查是否有未保存的内容
    const hasContent = Object.values(newProcurementForm).some(value => {
        if (Array.isArray(value)) {
            return value.length > 0 && 
                   value.some(item => 
                       typeof item === 'object' && 
                       Object.values(item).some(v => v)
                   );
        }
        return !!value;
    });
    
    if (hasContent) {
        ElMessageBox.confirm('表单内容尚未保存，确定要关闭吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            resetNewProcurementForm();
            isNewProcurementDialogVisible.value = false;
        });
    } else {
        resetNewProcurementForm();
        isNewProcurementDialogVisible.value = false;
    }
};

// 草稿校验函数
const validateDraft = () => {
    // 草稿只需要计划名称作为必填项
    if (!newProcurementForm.planName.trim()) {
        ElMessage({ message: '请填写计划名称', type: 'error' });
        return false;
    }
    
    // 检查已填写的产品信息的有效性
    for (let i = 0; i < newProcurementForm.products.length; i++) {
        const product = newProcurementForm.products[i];
        if (product.productName && !product.productModel) {
            ElMessage({ message: `第${i + 1}行产品：填写了产品名称，请也填写产品型号`, type: 'warning' });
        }
        if (product.productPrice && parseFloat(product.productPrice) <= 0) {
            ElMessage({ message: `第${i + 1}行产品：产品单价应大于0`, type: 'warning' });
        }
        if (product.purchaseQuantity && parseInt(product.purchaseQuantity) <= 0) {
            ElMessage({ message: `第${i + 1}行产品：购买数量应大于0`, type: 'warning' });
        }
    }
    
    return true;
};

// 保存草稿
const saveDraft = () => {
    // 验证草稿
    if (!validateDraft()) {
        return;
    }
    
    // 使用pinia store保存草稿
    const draftStore = useProcurementDraftStore();
    const savedDraft = draftStore.saveDraft(newProcurementForm.planName, newProcurementForm);
    
    console.log('保存草稿:', {
        draftNumber: savedDraft.draftNumber,
        saveTime: savedDraft.saveTime,
        content: savedDraft.content
    });
    
    ElMessage({ message: `草稿已成功保存（编号：${savedDraft.draftNumber}），您可以在草稿箱中查看`, type: 'success' });
};

// 表单校验函数
const validateForm = () => {
    // 基础信息校验
    if (!newProcurementForm.planName.trim()) {
        ElMessage({ message: '请填写计划名称', type: 'error' });
        return false;
    }
    
    if (!newProcurementForm.contractName.trim()) {
        ElMessage({ message: '请填写合同名称', type: 'error' });
        return false;
    }
    
    if (!newProcurementForm.contractType) {
        ElMessage({ message: '请选择合同类型', type: 'error' });
        return false;
    }
    
    if (!newProcurementForm.procurementType) {
        ElMessage({ message: '请选择采购类型', type: 'error' });
        return false;
    }
    
    if (!newProcurementForm.contractAddress) {
        ElMessage({ message: '请选择仓库地址', type: 'error' });
        return false;
    }
    
    if (!newProcurementForm.supplierUnit) {
        ElMessage({ message: '请选择供应商单位', type: 'error' });
        return false;
    }
    
    // 产品信息校验
    const hasValidProduct = newProcurementForm.products.some(product => {
        return product.productName && 
               product.productModel && 
               product.productPrice && parseFloat(product.productPrice) > 0 && 
               product.purchaseQuantity && parseInt(product.purchaseQuantity) > 0 && 
               product.unit;
    });
    
    if (!hasValidProduct) {
        ElMessage({ message: '请至少填写一个有效的产品信息', type: 'error' });
        return false;
    }
    
    // 检查每个产品的有效性
    for (let i = 0; i < newProcurementForm.products.length; i++) {
        const product = newProcurementForm.products[i];
        if (product.productName || product.productModel || product.productPrice || product.purchaseQuantity || product.unit) {
            if (!product.productName) {
                ElMessage({ message: `第${i + 1}行产品：请填写产品名称`, type: 'error' });
                return false;
            }
            if (!product.productModel) {
                ElMessage({ message: `第${i + 1}行产品：请填写产品型号`, type: 'error' });
                return false;
            }
            if (!product.productPrice) {
                ElMessage({ message: `第${i + 1}行产品：请填写产品单价`, type: 'error' });
                return false;
            }
            if (parseFloat(product.productPrice) <= 0) {
                ElMessage({ message: `第${i + 1}行产品：产品单价必须大于0`, type: 'error' });
                return false;
            }
            if (!product.purchaseQuantity) {
                ElMessage({ message: `第${i + 1}行产品：请填写购买数量`, type: 'error' });
                return false;
            }
            if (parseInt(product.purchaseQuantity) <= 0) {
                ElMessage({ message: `第${i + 1}行产品：购买数量必须大于0`, type: 'error' });
                return false;
            }
            if (!product.unit) {
                ElMessage({ message: `第${i + 1}行产品：请填写单位`, type: 'error' });
                return false;
            }
        }
    }
    
    return true;
};

// 提交申请
const submitProcurement = () => {
    // 表单验证
    if (!validateForm()) {
        return;
    }
    
    // 确认提交
    ElMessageBox.confirm('确定要提交采购申请单吗？提交后将进入审批流程，不可撤销。', '确认提交', {
        confirmButtonText: '确认提交',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        // 计算总金额
        const totalAmount = newProcurementForm.products.reduce((sum, product) => {
            const price = parseFloat(product.productPrice) || 0;
            const quantity = parseInt(product.purchaseQuantity) || 0;
            return sum + (price * quantity);
        }, 0);
        
        // 生成计划编号
        const today = new Date();
        const dateStr = today.getFullYear() + '-' + 
                       String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                       String(today.getDate()).padStart(2, '0');
        const randomNum = Math.floor(100 + Math.random() * 900);
        const planNumber = `PLAN-${dateStr}-${randomNum}`;
        
        // 模拟提交数据
        const newPlan = {
            planNumber: planNumber,
            planName: newProcurementForm.planName,
            equipmentType: newProcurementForm.procurementType,
            requestDept: '当前部门',
            applicant: '当前用户',
            requestDate: new Date().toLocaleString(),
            estimatedAmount: totalAmount.toFixed(2),
            status: '待审批'
        };
        
        // 添加到表格数据中
        tableData.value.unshift(newPlan);
        
        ElMessage({ message: '采购申请单已成功提交，等待审批！', type: 'success' });
        
        // 关闭对话框并重置表单
        resetNewProcurementForm();
        isNewProcurementDialogVisible.value = false;
    }).catch(() => {
        // 用户取消了提交
    });
};

// 文件上传相关方法
const handlePreview = (uploadFile) => {
    console.log('预览文件:', uploadFile);
    ElMessage({ message: '文件预览功能待实现', type: 'info' });
};

const handleRemove = (uploadFile, uploadFiles) => {
    console.log('删除文件:', uploadFile);
    // 从fileList中移除文件
    const index = newProcurementForm.fileList.findIndex(file => file.uid === uploadFile.uid);
    if (index !== -1) {
        newProcurementForm.fileList.splice(index, 1);
        ElMessage({ message: `文件 "${uploadFile.name}" 已移除`, type: 'success' });
    }
};

const beforeRemove = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(`确定要删除文件 "${uploadFile.name}" 吗？`, '确认删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    });
};

const handleExceed = (files, uploadFiles) => {
    ElMessage({ message: '最多只能上传5个文件，已自动过滤多余文件', type: 'warning' });
};
</script>