import { rebuildVaildMessage } from "../../utils/util"
import './style/ProForm.less'
import { v4 as uuid } from 'uuid'
// import { isEmpty } from "@/utils/validate"
let sidebarIds = []
let sidebarFuns = {}
export default {
    name: 'ProForm',
    props: {
        tabsProps: Object,
        labelWrap: {
            type: Boolean,
            default: () => true
        },
        layout: {
            type: String,
            default: () => 'card'
        },
        showSidebar: {
            type: Boolean,
            default: false
        },
        readRefFieldInfo: {
            type: Object,
            default: () => { }
        },
        sidebarWidth: {
            type: String,
            default: () => "125px"
        },
        labelCol: {
            type: Object,
            default: () => ({ style: { width: '120px' } })
        },
    },
    inject: {
        // 页面流水号
        pageTraceNo: {
            default: ''
        },
    },
    provide () {
        return {
            pageIsReadOnly: this.pageIsReadOnly,
            formReadData: this.formReadData,
            readRefFieldInfo: this.readRefFieldInfo
        }
    },
    computed: {
        pageIsReadOnly: function () {
            return this.$route.query.pageType === 'view'
        },
        formData: function () {
            let formData = this.$route.query.flowData
            if (typeof formData === 'string') {
                return JSON.parse(formData)
            }
            return formData
        }
    },
    watch: {
        '$attrs.model': {
            deep: true,
            immediate: true,
            handler (val) {
                if (this.pageIsReadOnly) {
                    let formDataWrapper = this.formatFlowData()
                    formDataWrapper = this.beforeFormatFormData(formDataWrapper)
                    console.log('watch attrs.model value trigger beforeFormatFormData method after : ', formDataWrapper)
                    if (val) {
                        this.formReadData = { ...val, ...formDataWrapper }
                    } else {
                        this.formReadData = formDataWrapper
                    }
                }
            }
        }
    },
    mounted () {
        //dialog中的form；其他位置的form需要特殊处理
        // let dialogBody = this.$parent.$el.childNodes[0].childNodes[1]
        // dialogBody?.addEventListener && dialogBody.addEventListener('scroll', this.loadSidebarFuns)
        // this.loadSidebarFuns()
    },
    beforeDestroy () {
        let dialogBody = this.$parent.$el.childNodes[0].childNodes[1]
        dialogBody?.removeEventListener && dialogBody.removeEventListener('scroll', this.loadSidebarFuns)
    },
    data () {
        return {
            uuid: uuid(),
            flag: false,
            formReadData: {}
        }
    },
    methods: {
        /*------------暴露的方法-----------*/
        //获取原生ref
        getOrignRef () {
            return this.$refs.proForm
        },
        //表单校验
        async validate (nameList) {
            let isValid = true;
            try {
                await this.$refs.proForm.validate(nameList)
            } catch (e) {
                isValid = false;
            }
            return isValid;
        },
        /*-------------------------------*/
        getPageTraceNo () {
            return this.pageTraceNo
        },

        getCommonParam () {
            return {
                pageTraceNo: this.pageTraceNo,
                pageIsReadOnly: this.$route.query.pageType === 'view'
            }
        },
        handleSelect (key, keyPath) {
            let uuid = this.uuid
            let element = document.getElementById(uuid + "-" + key)
            element.scrollIntoView({ behavior: "smooth", block: "nearest" })
        },
        //加载侧边栏回调函数
        // loadSidebarFuns () {
        //     if (this.showSidebar) {
        //         const _this = this
        //         sidebarIds.forEach(item => {
        //             let element = document.getElementById(item)
        //             if (!isEmpty(element)) {
        //                 let dialogBody = _this.$parent.$el.childNodes[0].childNodes[1]
        //                 //元素距离浏览器的高度
        //                 const offsetTop = element.offsetTop
        //                 //可视区
        //                 const dialogBodyClientHeight = dialogBody.clientHeight
        //                 //滚动条的滚动的高度
        //                 const scrollTop = dialogBody.scrollTop
        //                 //元素在可视区域
        //                 if (offsetTop - dialogBodyClientHeight - scrollTop < 0) {
        //                     sidebarFuns[item] && sidebarFuns[item]()
        //                     delete sidebarFuns[item]
        //                 }
        //             }
        //         })
        //     }
        // },
        formatFlowData () {
            let formDataWrapper = {}
            for (let key in this.formData) {
                if (key.indexOf('[') > -1 && key.indexOf(']') > -1) {
                    let arrName = key.substring(0, key.indexOf('['))
                    let index = 0
                    if (key.match(/\d+/g)) {
                        index = key.match(/\d+/g)[0]
                        let name = key.substring(key.lastIndexOf('.') + 1)
                        if (!name) {
                            console.error('formatFlowData key:', key, ' name: 为空')
                            continue
                        }
                        if (formDataWrapper[arrName]) {
                            if (!formDataWrapper[arrName][index]) {
                                formDataWrapper[arrName][index] = {}
                            }
                            formDataWrapper[arrName][index][name] = this.formData[key]
                        } else {
                            formDataWrapper[arrName] = []
                            formDataWrapper[arrName][index] = {}
                            formDataWrapper[arrName][index][name] = this.formData[key]
                        }
                    }
                } else {
                    formDataWrapper[key] = this.formData[key]
                }
            }
            return formDataWrapper
        },
        beforeFormatFormData (formDataWrapper) {
            const that = this
            let convertData = {}
            try {
                for (let key in that.readRefFieldInfo) {
                    let beforeVal = formDataWrapper[key]
                    if (beforeVal) {
                        if (typeof beforeVal === 'string') {
                            beforeVal = JSON.parse(beforeVal)
                        }
                        let afterVal = formDataWrapper[that.readRefFieldInfo[key]]
                        let beforeKeyFilterList = Object.keys(beforeVal).filter(item => !beforeVal[item])
                        if (afterVal) {
                            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) {
                formDataWrapper = { ...formDataWrapper, ...convertData }
            }
            return formDataWrapper
        },
    },
    render () {
        const _this = this
        let { rules, ...attrs } = this.$attrs
        //获取表单项prop与label映射
        let propLabel = {}
        let defaultSolts = this.$slots.default()
        defaultSolts.forEach(item => {
            let { type } = item
            let tag = type?.name
            //排除不显示的表单
            if (tag == undefined) {
                return
                //ProFormGrid组件中的表单项
            } else if (tag == 'pro-form-grid' || tag == 'ProFormGrid') {
                item.children.default().forEach(attr => {
                    let formItemProps = attr.props?.formItemProps
                    if (formItemProps) {
                        let { label, prop } = formItemProps
                        if (prop && label) {
                            propLabel[prop] = label.trim()
                        }
                    }
                })
                //直接写在表单中的表单项
            } else {
                let formItemProps = item?.type?.props?.formItemProps
                if (formItemProps) {
                    let { label, prop } = formItemProps
                    if (prop && label) {
                        propLabel[prop] = label.trim()
                    }
                }
            }
        })
        //重构rules,对必输，最小长度，最大长度校验信息进行处理
        rebuildVaildMessage(rules, propLabel)

        let sidebar = []
        //生成侧边栏
        if (this.showSidebar) {
            //如果已经遍历过，则不再赋值为空重新遍历了
            if (!_this.flag) {
                sidebarIds = []
                sidebarFuns = {}
            }
            let tempFlag = false
            this.$slots.default().forEach((item, index) => {
                let tag = item.type?.name
                if (tag == undefined) {
                    return ''
                } else if (tag == 'pro-form-grid' || tag == 'ProFormGrid') {
                    let sidebarId = _this.uuid + '-' + index
                    if (_this.flag == false) {
                        tempFlag = true
                        sidebarIds.push(sidebarId)
                        sidebarFuns[sidebarId] = item.data.attrs.sidebarFun
                    }
                    item.componentOptions.propsData.sidebarId = sidebarId
                    let header = item.componentOptions?.propsData?.header
                    if (header) {
                        let title = header?.title ?? header?.label
                        sidebar.push(<a-menu-item index={index.toString()}>
                            <span slot="title">{title}</span>
                        </a-menu-item>)
                    }
                }
            })
            //如果已经遍历了，下次执行reader函数时不再收集方法，解决重复请求第一个sidebarFun的问题
            if (tempFlag) {
                this.flag = true
            }
        }
        let formStyle = { width: "100%" }
        if (sidebar.length > 0) {
            formStyle.width = "calc(100% - " + this.sidebarWidth + ")"
        }
        if (_this.pageIsReadOnly) {
            return (<span style={{ display: 'flex' }}>
                <a-form ref="proForm" labelWrap={this.$props.labelWrap} {...this.$attrs} v-model={this.formReadData} size="medium" style={formStyle} class={'dhc-proForm ' + this.$attrs.class ?? ""}>
                    {this.layout == 'tabs' ?
                        <a-tabs attrs={this.tabsProps}>
                            {this.$slots.default().map(item => {
                                let tag = item.componentOptions?.tag
                                if (tag == undefined) {
                                    return ''
                                } else if (tag == 'pro-form-grid' || tag == 'ProFormGrid') {
                                    let header = item.componentOptions?.propsData?.header
                                    return <a-tab-pane label={header?.title ?? header?.label} attrs={header} layout='tabs'>
                                        {item}
                                    </a-tab-pane>
                                } else {
                                    return item
                                }
                            })}
                        </a-tabs>
                        : this.$slots.default()}
                </a-form>
                {sidebar.length > 0 ?
                    <a-menu class='dhc-form-sidebar' onSelect={_this.handleSelect}>
                        {sidebar}
                    </a-menu> : ''
                }
            </span>)
        }
        return (<span style={{ display: 'flex' }}>
            <a-form ref="proForm" labelWrap={this.$props.labelWrap} {...this.$attrs} rules={rules} size="medium" style={formStyle} class={'dhc-proForm ' + this.$attrs.class ?? ""} labelCol={this.$props.labelCol}>
                {this.layout == 'tabs' ?
                    <a-tabs attrs={this.tabsProps}>
                        {this.$slots.default().map(item => {
                            let tag = item.type?.name
                            if (tag == undefined) {
                                return ''
                            } else if (tag == 'pro-form-grid' || tag == 'ProFormGrid') {
                                let header = item.componentOptions?.propsData?.header
                                return <a-tab-pane label={header?.title ?? header?.label} attrs={header} layout='tabs'>
                                    {item}
                                </a-tab-pane>
                            } else {
                                return item
                            }
                        })}
                    </a-tabs>
                    : this.$slots.default()}
            </a-form>
            {sidebar.length > 0 ?
                <a-menu class='dhc-form-sidebar' onSelect={_this.handleSelect}>
                    {sidebar}
                </a-menu> : ''
            }
        </span>
        )

    }
}
