<script>
import { itemTemp, formItemTemp, formTemplate, propertyMap, formatForm } from './template.js'
import { testData } from './testData'
export default {
    name: 'formatForm',
    render: (h, params) => {

        const formArray = testData
        // 生产form-Item 和 form ， 也就是表单中是所有item,和与这个表单对应的data
        const Factory = (property) => {

            // 表单内容
            const item = JSON.parse(JSON.stringify(itemTemp))
            // console.log(item);
            // formItem内容
            const resultFormItem = JSON.parse(JSON.stringify(formItemTemp))
            // data对应数据的每一项
            const dataItem = {}
            // 1
            Object.keys(property).forEach(proKey => {
                // 如果对应表中存在对应关系，给表单属性赋值
                const targetKey = propertyMap[proKey]
                const targetValue = property[proKey]

                if (targetKey) {
                    if (proKey == 'type') {
                        item[proKey] = targetValue
                        item[targetKey] = 'input'
                    }
                    resultFormItem.children = [item]
                }
                // 不存在对应关系，说明是data中的属性，放在data中组成{key:value}
                else {
                    dataItem[proKey] = targetValue
                    formatForm.push(dataItem)
                }
            });
            return { 'formItem': resultFormItem, itemForm: 'formatForm' }
        }

        // 获取form的子元素数组，所有元素都添加在此数组
        // 遍历源数据，生成目标数据
        const itemResult = formArray.map((li) => {
            const { formItem, itemForm } = Factory(li)
            // data
            formatForm.push(itemForm)
            // 返回form - Item
            return formItem
        })
        formTemplate.children = itemResult
        const resu = renderFactory(formTemplate)

        // 生成dom
        function renderFactory(current) {
            const tag = current.tag
            const property = current.property
            let childrend = current.children

            if (current.children.length != 0) {
                childrend = current.children.map(it => {
                    return renderFactory(it)
                })
            } else {
                childrend = ''
            }

            return h(tag, property, childrend)
        }


        return resu
    }
}
</script>

<style lang="scss" scoped>
@import url(./style.scss);
</style>