<template>
    <div class="manage-container">
        <div class="manage-wrap">
            <div class="manage-header">
                <div class="header-left"></div>
                <div class="header-right">
                    <el-button type="primary" @click="addItem">新增</el-button>
                    <el-button type="primary" @click="exportData">导出</el-button>
                </div>
            </div>
            <div class="manage-content">
                <el-table :data="tableData" style="width: 100%; height: 100%;" empty-text="暂无数据" border>
                    <el-table-column type="index" width="50" />
                    <el-table-column v-for="column in tableColumns" :key="column.prop"
                        :prop="column.prop" :label="column.label"
                    >
                        <template #default="scope">
                            <el-input v-model="scope.row[column.prop]" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="60">
                        <template #default="scope">
                            <el-button link type="danger" size="small" @click="deleteItem(scope.$index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { reactive, ref } from "vue";
    import * as XLSX from "xlsx";
    const tableColumns = reactive([
        {
            prop: "projectName",
            label: "项目名称"
        },
        {
            prop: "tzglzt",
            label: "投资管理主体"
        },
        {
            prop: "jcdw",
            label: "决策单位"
        },
        {
            prop: "xdpfsj",
            label: "下达批复时间"
        },
        {
            prop: "zyx",
            label: "重要性"
        },
        {
            prop: "ssjd",
            label: "实施阶段"
        },
        {
            prop: "pfnr",
            label: "批复内容"
        },
        {
            prop: "pfyjsm",
            label: "批复意见落实情况具体说明"
        },
        {
            prop: "lszxqk",
            label: "落实（执行）情况"
        },
        {
            prop: "zcclxh",
            label: "支撑材料序号"
        },
        {
            prop: "wlsyy",
            label: "未落实原因"
        },
        {
            prop: "xybgzcs",
            label: "下一步工作措施"
        },
        {
            prop: "yjwcsj",
            label: "预计完成时间"
        },
        {
            prop: "zrld",
            label: "责任领导"
        },
        {
            prop: "zrbnmjzrr",
            label: "责任部门及责任人"
        },
        {
            prop: "sfgx",
            label: "是否更新"
        },
        {
            prop: "bz",
            label: "备注"
        }
    ]);
    let tableData = ref([]);
    const addItem = () => {
        tableData.value.push({});
    }
    const deleteItem = (index) => {
        ElMessageBox.confirm("确认删除该项？", "提示",{
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() => {
            tableData.value.splice(index, 1);
        }).catch(() => {});
    };
    const exportData = () => {
        // 1. 创建工作簿
        const wb = XLSX.utils.book_new()
        
        // 2. 准备数据
        let wsData = [["投资项目批复意见落实情况统计表"], []]
        
        // 添加表头
        if (tableColumns && tableColumns.length > 0) {
            const headerRow = tableColumns.map(h => h.label || h)
            wsData.push(headerRow)
        }
        
        // 添加数据行
        tableData.value.forEach(item => {
            if (tableColumns) {
                // 按表头配置提取数据
                const row = tableColumns.map(header => {
                    const value = getNestedValue(item, header.prop || header)
                    return formatCellValue(value, header.formatter)
                })
                wsData.push(row)
            } else {
                // 如果没有表头配置，直接使用对象值
                const row = Object.values(item)
                wsData.push(row)
            }
        })
        
        // 3. 创建工作表
        const ws = XLSX.utils.aoa_to_sheet(wsData)
        
        // 4. 设置列宽（可选）
        if (tableColumns) {
            const colWidths = tableColumns.map(header => ({
                wch: header.width || Math.max(
                    (header.label || header).length,
                    ...tableData.value.map(item => {
                        const value = getNestedValue(item, header.prop || header)
                        return String(value || '').length
                    })
                ) * 2
            }))
            ws['!cols'] = colWidths
        }
        // 合并标题单元格
        ws['!merges'] = [
            XLSX.utils.decode_range('A1:Q1') // 合并第一行的 A-E 列
        ]
        // 5. 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
        
        // 6. 生成 Excel 文件并下载
        XLSX.writeFile(wb, "导出文件.xlsx");
    };
    // 辅助函数：获取嵌套对象的值
    function getNestedValue(obj, path) {
        return path.split('.').reduce((prev, curr) => {
            return prev ? prev[curr] : null
        }, obj)
    }

    // 辅助函数：格式化单元格值
    function formatCellValue(value, formatter) {
        if (formatter && typeof formatter === 'function') {
            return formatter(value)
        }
        return value
    }
</script>

<style lang="less">
    @import "@/styles/manage.less";
</style>