<template>
    <div class="design-form-item">
        <view class="design-form-item__body">
            <slot />
        </view>
        <slot name="error">
            <text
                v-if="!!message && errorType === 'message'"
                class="design-form-item__message"
                :style="{
                    marginLeft: 272 + 'rpx'
                }"
            >
                {{ message }}
            </text>
        </slot>
    </div>
</template>

<script lang="ts">
import { FORM_KEY } from '@/config/symbol'
import {
    ComponentInternalInstance,
    ComponentPublicInstance,
    defineComponent,
    getCurrentInstance,
    inject,
    onMounted,
    ref
} from 'vue'

export default defineComponent({
    name: 'desin-form-item',
    props: {
        prop: {
            type: String,
            default: ''
        }
    },
    setup(props) {
        const parent = inject(FORM_KEY) as ComponentPublicInstance
        const instance = getCurrentInstance() as ComponentInternalInstance

        const message = ref('')
        const errorType = ref('message')

        // 获取父组件实例
        const getParentInstance = (name = 'design-form') => {
            let parent = instance.proxy?.$parent
            let parentName = parent?.$options.name
            while (parentName !== name) {
                parent = parent?.$parent
                if (!parent) return false
                parentName = parent.$options.name
            }
            return parent
        }
        // 绑定子组件实例
        const bindRelation = () => {
            if (!parent) return
            // #ifndef H5
            let obj1 = Object.assign(parent.$data, {
                ...props,
                showMessage
            })
            // #endif
            // #ifdef H5
            let obj1 = parent
            // #endif

            const children = [...parent.children, { ...instance.proxy }]

            parent.children = children
        }
        // 显示错误信息
        const showMessage = (error: string, type: string) => {
            errorType.value = type
            message.value = error
        }

        onMounted(() => {
            bindRelation()
            getParentInstance()
        })

        return {
            parent,
            bindRelation,
            message,
            errorType,
            showMessage
        }
    }
})
</script>

<style lang="scss" scoped>
.design-form-item {
    display: flex;
    flex-direction: column;
    &__message {
        margin-top: 12rpx;
        font-size: 12px;
        line-height: 12px;
        color: $red-1;
    }
}
</style>
