import ProFormCard from './ProFormCard'
// import { setFormItemStyle } from '@/utils/util'

export default {
    name: 'ProFormGrid',
    props: {
        bodyStyle: Object,
        colNum: {
            type: [Number, String],
            default: () => 3
        },
        header: Object,
        sidebarId: {             //侧边栏跳转id
            type: String,
            default: ''
        },
        visiableReadOnly: {
            type: Boolean,
            default: false
        }
    },
    provide () {
        return {
            pageIsReadOnly: this.pageIsReadOnly,
        }
    },
    inject: {
        pageIsReadOnly: {
            default: false
        },
        formReadData: {
            default: () => { }
        },
        readRefFieldInfo: {
            default: () => { }
        }
    },
    data () {
        return {
            formReadDataWrapper: this.formReadData
        }
    },

    mounted () {
        // this.beforeFormatFormData()
        // setFormItemStyle()
    },
    methods: {
        //card布局头部插槽渲染函数
        cardHeaderSlot () {
            let leftContent = null
            let rightContent = null
            let slotContent = null
            if (this.$slots.header) {
                slotContent = <template slot='header'>{this.$slots.header()}</template>
            } else {
                //左侧title
                if (this.header?.title) {
                    let type = typeof this.header.title
                    if (type === "function") {
                        leftContent = this.header.title()
                    } else {
                        leftContent = <span>{this.header.title}</span>
                    }
                }
                //右侧内容
                if (this.header?.rightContent) {
                    let type = typeof this.header.rightContent
                    if (type === "function") {
                        rightContent = <div style={{ float: 'right', marginTop: '-8px', }}>{this.header.rightContent()}</div>
                    } else {
                        rightContent = <div style={{ float: 'right', }}>{this.header.rightContent}</div>
                    }
                }
                if (leftContent != null || rightContent != null) {
                    slotContent = <template slot='header'>
                        {leftContent}
                        {rightContent}
                    </template >
                }
            }
            return slotContent
        },

        beforeFormatFormData () {
            const that = this
            if (!that.pageIsReadOnly) {
                return false
            }
            if (that.readRefFieldInfo) {
                let convertData = {}
                try {
                    for (let key in that.readRefFieldInfo) {
                        let beforeVal = that.formReadDataWrapper[key]
                        if (beforeVal) {
                            if (typeof beforeVal === 'string') {
                                beforeVal = JSON.parse(beforeVal)
                            }
                            let afterVal = that.formReadDataWrapper[that.readRefFieldInfo[key]]
                            if (afterVal) {
                                let beforeKeyFilterList = Object.keys(beforeVal).filter(item => !beforeVal[item])
                                beforeKeyFilterList = beforeKeyFilterList.filter(item => afterVal[item])
                                beforeKeyFilterList.forEach(item => Reflect.deleteProperty(beforeVal, item))
                                if (!convertData[that.readRefFieldInfo[key]]) {
                                    convertData[that.readRefFieldInfo[key]] = {}
                                }
                                convertData[that.readRefFieldInfo[key]] = { ...convertData[that.readRefFieldInfo[key]], ...afterVal, ...beforeVal }
                            } else {
                                convertData[that.readRefFieldInfo[key]] = { ...convertData[that.readRefFieldInfo[key]], ...beforeVal }
                            }
                        }
                    }
                } catch (e) {
                    console.error('formReadOnly error :', e, ' location in beforeFormatFormData')
                }
                if (convertData) {
                    this.formReadDataWrapper = { ...that.formReadDataWrapper, ...convertData }
                }
            }
        },

        pageIsReadRender (item, formItemProps, show) {
            const that = this
            let readValue = that.formReadDataWrapper[formItemProps.prop]
            let readText = that.formReadDataWrapper[formItemProps.prop + 'Zh']
            let expression = item.data?.model?.expression
            let readIgnores = item?.data?.attrs?.readIgnore?.split(',') || item?.componentOptions?.propsData?.readIgnore?.split(',')
            let readRefField = item?.data?.attrs?.readRefField || item.componentOptions?.propsData?.readRefField
            if (!readValue && expression && expression.indexOf('.') > -1) {
                let index = 0
                if (expression.match(/\d+/g)) {
                    index = expression.match(/\d+/g)[0]
                }
                let expressArry = expression.split('.')
                let valData = that.formReadDataWrapper
                let valText = null
                for (let express of expressArry) {
                    if (!valData) {
                        break
                    }
                    if (readIgnores && readIgnores.includes(express)) {
                        continue
                    }
                    valText = valData[express + 'Zh'] ? valData[express + 'Zh'] : null
                    valData = valData[express]
                    if (valData && Array.isArray(valData)) {
                        valData = valData[index]
                        continue
                    }
                }
                if (valData) {
                    readValue = valData
                }
                if (valText) {
                    readText = valText
                }
            }
            if (readRefField && !readValue) {
                readValue = that.formReadDataWrapper[readRefField]
            }
            if (readValue) {
                let itemWrapper = { ...item }
                if (itemWrapper?.componentOptions && itemWrapper.componentOptions.propsData) {
                    itemWrapper.componentOptions.propsData.value = readValue
                    itemWrapper.componentOptions.propsData.readValue = readValue
                    itemWrapper.componentOptions.propsData.readText = readText
                }
                if (itemWrapper?.data && itemWrapper.data.model) {
                    itemWrapper.data.model.readText = readText
                    itemWrapper.data.model.readValue = readValue
                    itemWrapper.data.model.value = readValue
                    itemWrapper.data.model.expression = ''
                }
                itemWrapper.value = readValue
                itemWrapper.readValue = readValue
                itemWrapper.readText = readText
                itemWrapper.disabled = false
                return <a-form-item attrs={formItemProps} name={formItemProps.prop} v-model={readValue} v-show={show}>
                    {itemWrapper}
                </a-form-item>
            }
            return <a-form-item attrs={formItemProps} name={formItemProps.prop} v-show={show}>
                {item}
            </a-form-item>
        },
        pageIsReadTableRender (item) {
            if (!item) {
                return item
            }
            const that = this
            let readTableData = that.formReadDataWrapper['readTableData']
            let elemType = item.componentOptions?.tag
            let eleTableWrapper = null
            let eleTableIndex = item.componentOptions?.children?.findIndex(eleItem => eleItem?.componentOptions?.tag === 'pro-table')
            if (['pro-card'].includes(elemType)) {
                if (eleTableIndex > -1) {
                    eleTableWrapper = { ...item.componentOptions?.children[eleTableIndex] }
                } else {
                    return item
                }
            } else if ('pro-table' === elemType) {
                eleTableWrapper = { ...item }
            }
            if (eleTableWrapper) {
                const exFormKey = eleTableWrapper.componentOptions?.propsData?.exFormKey
                if (exFormKey) {
                    let tableReadData = []
                    if (exFormKey.indexOf(',') > -1) {
                        let exFormKeyArr = exFormKey.split(',')

                        exFormKeyArr.forEach(exKeyItem => {
                            let formRefTableData = that.formReadDataWrapper[exKeyItem]
                            if (typeof formRefTableData === 'string') {
                                formRefTableData = JSON.parse(formRefTableData)
                            }
                            tableReadData = [...tableReadData, ...formRefTableData]
                        })
                    } else {
                        let formRefTableData = that.formReadDataWrapper[exFormKey]
                        if (typeof formRefTableData === 'string') {
                            formRefTableData = JSON.parse(formRefTableData)
                        }
                        tableReadData = formRefTableData
                    }
                    if (tableReadData) {
                        if (eleTableWrapper?.componentOptions && eleTableWrapper?.componentOptions?.propsData) {
                            eleTableWrapper.componentOptions.propsData.readTableData = tableReadData
                        }
                        if (eleTableWrapper?.data && eleTableWrapper?.data?.model) {
                            eleTableWrapper.data.model.readTableData = tableReadData
                        }
                        elemType === 'pro-table' ? item = { ...eleTableWrapper } : item.componentOptions?.children?.splice(eleTableIndex, 1, eleTableWrapper)
                    }
                } else if (readTableData) {
                    readTableData = JSON.parse(readTableData)
                    if (eleTableWrapper.componentOptions && eleTableWrapper.componentOptions.propsData) {
                        eleTableWrapper.componentOptions.propsData.readTableData = readTableData
                    }
                    if (eleTableWrapper.data && eleTableWrapper.data.model) {
                        eleTableWrapper.data.model.readTableData = readTableData
                    }
                    elemType === 'pro-table' ? item = { ...eleTableWrapper } : item.componentOptions?.children?.splice(eleTableIndex, 1, eleTableWrapper)
                }
            } else if (item.tag === 'div' && item?.children?.length > 0) {
                let fileEleItem = item?.children?.find(eleItem => eleItem.componentOptions?.tag === 'file-partition-widget')
                if (fileEleItem) {
                    const fileTraceNo = that.formReadDataWrapper["uploadFilename"] ? that.formReadDataWrapper["uploadFilename"] : that.formReadDataWrapper["appendFileId"]
                    if (fileTraceNo) {
                        if (fileEleItem?.componentOptions && fileEleItem?.componentOptions?.propsData) {
                            fileEleItem.componentOptions.propsData.traceNo = fileTraceNo
                            fileEleItem.componentOptions.propsData.readValue = fileTraceNo
                        }
                        if (fileEleItem?.data && fileEleItem?.data?.model) {
                            fileEleItem.data.model.traceNo = fileTraceNo
                            fileEleItem.data.model.readValue = fileTraceNo
                            fileEleItem.data.model.expression = ''
                        }
                        fileEleItem.traceNo = fileTraceNo
                        fileEleItem.readValue = fileTraceNo
                    }
                }
            }
        },
    },
    render () {
        const that = this
        let layout = that.$parent?.$attrs.attrs?.layout ?? "card"
        console.log('pro-form-grid----------------------------------------------')

        if (layout == 'card') {
            let header = this.cardHeaderSlot()
            return (<ProFormCard bodyStyle={that.bodyStyle} colNum={that.colNum} sidebarId={this.sidebarId}>
                {/* card布局头部插槽 */}
                {header}
                {this.$slots.default && this.$slots.default()?.map(item => {
                    if (item.children === "v-if") {
                        return item;
                    }
                    if (!item.props) {
                        return item;
                    }
                    let { formItemProps } = item.props
                    if (formItemProps) {
                        formItemProps = { ...formItemProps }
                        let show = true
                        //处理v-show
                        item.dirs?.forEach(item => {
                            if (item.dir.name == 'show' && item.value == false) {
                                show = false
                            }
                        })
                        if (that.pageIsReadOnly) {
                            show = show || that.visiableReadOnly
                            return that.pageIsReadRender(item, formItemProps, show)
                        }
                        return <a-form-item label={formItemProps.label} name={formItemProps.prop} v-show={show}>
                            {item}
                        </a-form-item>
                    } else {
                        if (that.pageIsReadOnly) {
                            that.pageIsReadTableRender(item)
                        }
                        return item
                    }
                })}
            </ProFormCard>)
        } else if (layout == 'tabs') {
            return (<ProFormCard bodyStyle={that.bodyStyle} colNum={that.colNum} >
                {this.$slots.default && this.$slots.default().map(item => {
                    if (!item.props) {
                        return item;
                    }
                    let { formItemProps } = item.props
                    if (formItemProps) {
                        formItemProps = { ...formItemProps }
                        let show = true
                        //处理v-show
                        item.dirs?.forEach(item => {
                            if (item.dir.name == 'show' && item.value == false) {
                                show = false
                            }
                        })
                        if (that.pageIsReadOnly) {
                            show = show || that.visiableReadOnly
                            return that.pageIsReadRender(item, formItemProps, show)
                        }
                        return <a-form-item label={formItemProps.label} name={formItemProps.prop} v-show={show}>
                            {item}
                        </a-form-item>
                    } else {
                        if (that.pageIsReadOnly) {
                            that.pageIsReadTableRender(item)
                        }
                        return item
                    }
                })}
            </ProFormCard>)
        }

    }
}
