<template>
    <div>
        {{ config?.title || '' }}
    </div>
    <div>
        <el-table :data="formData">
            <el-table-column label="操作" v-if="config?.deleteApi">
                <template #default="{ row }">
                    <el-button @click="handleAdd">+</el-button>
                    <el-button @click="handleDelete(row)">-</el-button>
                </template>
            </el-table-column>
            <el-table-column :label="item.label" v-for="(item, index) in config.tableConfig" :key="index"
                :prop="item[value]">
                <template #default="{ row }">
                    <el-select v-model="row[item.value]" v-if="item.select">
                        <el-option v-for="items in (Array.isArray(item.select) ? item.select : dictData[item.select])"
                            :label="items.name" :value="items.value"></el-option>
                    </el-select>

                    <el-date-picker class="flex-1 !flex" v-model="row[item.value]" clearable value-format="YYYY-MM-DD"
                        placeholder="请选择日期" v-else-if="item.date">
                    </el-date-picker>

                    <el-input v-model="row[item.value]" v-else />
                </template>
            </el-table-column>
            <template #empty>
                <span class="cursor-pointer">暂无数据，点击添加 <el-button @click="handleAdd">+</el-button></span>
            </template>
        </el-table>
    </div>
</template>
<script lang="ts" setup>
import { defineProps } from "vue"
import { useDictData } from '@/hooks/useDictOptions'

/** config参数说明
 * 
 * title: 标题
 * tableConfig: 表格的table-column的每一项
 *  [{
 *    label:表头名称
 *    value:值
 *    select:是否为下拉选择框，不填默认为文本框，为String类型时表示为字典option，为Array类型表示自定义option ，
 *    date:是否为日期选择框 
 *  }] 
 *  deleteApi:删除列表每行所需要的api,不填默认为禁止对列表的添加/除操作
 */
const props = defineProps({
    formData: {
        type: Object,
        require: true
    },
    config: {
        type: Object,
        require: true
    }
})

// 生成字典名称
const dictValue = props.config.tableConfig.map(item => Array.isArray(item.select) ? null : item.select).filter(item => item).join(',')
const { dictData } = useDictData(dictValue)


// 生成table的每一列的初始对象
const list = props.config.tableConfig.map(item => item.value)
const getInitialData = () => {
    return list.reduce((acc, curr) => {
        acc[curr] = '';
        return acc;
    }, {});
}


const handleAdd = () => {
    props.formData.push(getInitialData());
};


const handleDelete = async (row: any) => {
    if (row.id && props?.config?.deleteApi) {
        await props.config.deleteApi({ id: row.id });
    }
    const index = props.formData.indexOf(row);
    props.formData.splice(index, 1);
};


</script>
