<script lang="ts">
import { defineComponent, createVNode, reactive } from 'vue'
import { Column } from 'vxe-table'
import { uuid } from '@/utils/random'

/** storage 开启时列必须有稳定 field；序号/操作等无 field 列按 title 生成 */
function resolveColumnField(attr: Record<string, any>): string | undefined {
    if (attr.field) return attr.field
    if (attr.prop) return attr.prop
    // checkbox / radio / expand / seq 等类型列由 vxe 内部处理，可不强制 field
    if (attr.type && ['checkbox', 'radio', 'expand', 'html'].includes(attr.type)) {
        return undefined
    }
    if (attr.title != null && attr.title !== '') {
        return `__col_${attr.title}`
    }
    return `col_${uuid()}`
}

export default defineComponent({
    name: 'Column',
    props: {
        attr: {
            type: Object,
            required: true
        }
    },
    setup(props, { slots }) {
        const attr = reactive({ ...props.attr })
        attr['align'] = attr['align'] ? attr['align'] : 'center'
        const field = resolveColumnField(attr)
        if (field) {
            attr.field = field
        }
        attr['column-key'] = attr['column-key'] ? attr['column-key'] : attr.field || attr.prop || uuid()
        return () => {
            return createVNode(Column, attr, slots.default)
        }
    }
})
</script>
