/**
 * 高度自适应
 * @author xiufu.wang
 */
import { addResizeListener, removeResizeListener } from 'mars-pro/src/utils/resize-event'
import { hasClass } from 'mars-pro/src/utils/dom'
export default {
    name: 'ProFullHeight',
    componentName: 'ProFullHeight',
    props: {
        // 误差
        decrease: {
            type: Number,
            default:0
        },
        // 全局唯一
        containerSelector: {
            type: String,
            default: 'body'
        },
        // 全局唯一
        sourceSelector: String
    },
    data() {
        return {
            height: 'auto'
        }
    },
    components: {},
    computed: {},
    mounted() {
        this.contanerEl = this.containerSelector === 'body' ? document.body : this.getEl(this.containerSelector)
        this.sourceEl = this.sourceSelector ? this.contanerEl.querySelector(this.sourceSelector) : this.$el
        if (!this.contanerEl || !this.sourceEl) {
            return
        }
        //绑定事件
        addResizeListener(this.contanerEl, this.onResize)
        // 初始化
        this.onResize()
    },
    methods: {
        getEl(selector) { 
            let cur = this.$el.parentNode
            if (selector[0] === '.') { 
                selector = selector.slice(1)
            }
            while (cur && cur) { 
                if (hasClass(cur, selector)) { 
                    return cur
                }
                cur = cur.parentNode
            }
            return null
        },
        onResize() {
            const stop = this.sourceEl.getBoundingClientRect().top
            const cbottom = this.contanerEl.getBoundingClientRect().bottom
            this.height = `${cbottom - stop + this.decrease}px`
            this.$nextTick(() => {
                this.$emit('resize', this.height)
            })
        }
    },
    render() {
        let vnodes = null
        if (this.$scopedSlots.default) {
            vnodes = this.$scopedSlots.default({ height: this.height })
        } else {
            vnodes = this.$slots.default
        }
        return vnodes ? vnodes[0] : null
    },
    beforeDestroy() { 
        if (this.contanerEl) { 
            removeResizeListener(this.contanerEl, this.onResize)
        }
    }
}