/**
 * pro tree
 * 1. 右键下拉菜单
 * 2. 适配dataSource
 * 3. 单选、多选绑定
 * 4. 
 * @author xiufu.wang
 */
import ElTree from 'mars-pro/packages/tree';
import { isArray, isObject } from 'mars-pro/src/pro/util';

export default {
    name: 'ProDataTree',
    componentName: 'ProDataTree',
    inheritAttrs: false,
    components: {
        ElTree
    },
    props: {
        //数据源
        dataSource: [Object, Array],
        // 绑定选择节点-支持双向绑定
        selectNodes: {},
        /**
         * 定义选择节点类型: 
         * {
         *  leafOnly: true, 仅包含叶子节点
         * }
         */
        selectNodesIncludes: {
            type: Object,
            default: function () {
                return {
                    leafOnly: true
                }
            }
        },
        //选择模式 single | multiple
        selectModel: [String, Boolean],
        //nodeKey
        nodeKey: String
    },
    computed: {
        treeDatas() {
            const dataSource = this.dataSource
            if (dataSource && dataSource.isDataSource == true) {
                return dataSource.formatDatas
            }
            return dataSource
        },
        /**
         * 解析选择keys: 单选为string|number, 多选为数组
         * @returns 
         */
        selectNodeKeys() {
            const nodeKey = this.nodeKey
            let selectNodes = this.selectNodes || []
            selectNodes = isArray(selectNodes) ? selectNodes : [selectNodes]
            let res = selectNodes.map(r => isObject(r) ? r : { [nodeKey]: r }).map(r => r[nodeKey])
            return this.selectModel === 'multiple' ? res : res[0]
        }
    },
    watch: {
        selectNodeKeys: {
            immediate: true,
            handler: function () { 
                if (this.selectModel && this.selectModel === 'multiple' && this.$refs.eltree) {
                    const store =  this.$refs.eltree.store;
                    const allNodes = store._getAllNodes()
                    allNodes.forEach(n => {
                        n.setChecked(false, store.checkStrictly)
                    })
                }
            }
        },
        selectNodes() {
            if (this.selectModel && this.selectModel !== 'multiple') {
                this.setCurrentNodeSelect()
            }
        },
        treeDatas() {
            if (this.selectModel && this.selectModel !== 'multiple') {
                this.$nextTick(this.setCurrentNodeSelect)
            }
        }
    },
    methods: {
        renderNodeContent(h, { context, node, data, store }) {
            if (this.$scopedSlots.nodeContent) {
                const vNodes = this.$scopedSlots.nodeContent({ context, node, data, store })
                return <span class="el-tree-node__label">{vNodes}</span>
            }
        },
        //单选模式下
        setCurrentNodeSelect() {
            this.$refs.eltree.store.setCurrentNodeKey(this.selectNodeKeys)
        },
        //节点选择
        handleNodeSelect(data, node) {
            this.$emit('current-change', data, node)
            const selectNodesIncludes = this.selectNodesIncludes || {}
            // 仅能选择叶子节点
            if (selectNodesIncludes.leafOnly === true && !node.isLeaf) {
                return
            }
            this.$emit('update:selectNodes', node.key)
        },
        //checkox选择
        handleNodeCheckSelect(data, options) {
            this.$emit('check', data, options)
            const selectNodesIncludes = this.selectNodesIncludes || {}
            let res = this.$refs.eltree.store.getCheckedNodes(
                selectNodesIncludes.leafOnly === true
            ).map((_data) => (_data || {})[this.$refs.eltree.store.key]);
            this.$emit('update:selectNodes', res)
        },
        // 监听异步加载的数据变化
        handleLazyLoad(treeNode, cb) {
            const load = ((this.dataSource || {}).treeAsyncTreeload) || this.$attrs.load
            if (load) {
                load(treeNode, (data) => {
                    cb(data)
                    this.$nextTick(() => {
                        if (this.selectModel && this.selectModel !== 'multiple') {
                            this.setCurrentNodeSelect()
                        }
                    })
                })
            }
        }
    },
    render() {
        const _datas = {
            props: {
                data: this.treeDatas,
                load: this.handleLazyLoad,
                renderContent: this.$scopedSlots.nodeContent ? this.renderNodeContent : null,
                nodeKey: this.nodeKey,
                showCheckbox: this.selectModel === 'multiple',
                // 多选时反向选择交给eltree完成
                ...(this.selectModel === 'multiple' ? { defaultCheckedKeys: this.selectNodeKeys } : {}),
                ...(!!this.selectModel ? { highlightCurrent: true } : {}),
                ...this.$attrs
            },
            attrs: {
                ...this.$attrs
            },
            on: {
                ...this.$listeners,
                ...(this.selectModel === 'multiple' ? { check: this.handleNodeCheckSelect } : {}),
                ...(this.selectModel && this.selectModel !== 'multiple' ? { 'current-change': this.handleNodeSelect } : {})
            }
        }

        return (<ElTree {..._datas} ref="eltree"></ElTree>)
    },
    mounted() {
        //单选模式
        if (this.selectModel && this.selectModel !== 'multiple') {
            this.setCurrentNodeSelect()
        }
    }
}