<template>
    <div :class="classes" ref="cell">
        <template v-if="renderType === 'index'">{{naturalIndex + 1}}</template>
        <template v-if="renderType === 'selection'">
            <Checkbox :value="checked" @on-change="toggleSelect" :disabled="disabled"></Checkbox>
        </template>
        <template v-if="renderType === 'normal'"><span v-html="row[column.key]"></span></template>
        <template v-if="renderType === 'hidden'"><span v-html="row[column.key]" style="display: none;"></span></template>
        <template v-if="renderType === 'treetable'">
            <template v-for="le in row.level">
                <span class="ut-table-tree-indent"></span>
            </template>
            <span class="ut-table-tree-swc" @click="operateNode(row)"></span>
            <img v-if="row.icon" :src="row.icon" width="18px" height="18px"/>
            <span v-else  class="ut-table-tree-ico"></span>
            <span v-html="row[column.key]"></span></template>
    </div>
</template>
<script>
    import Vue from 'vue';
    import Checkbox from '../checkbox/checkbox.vue';

    export default {
        name: 'TableCell',
        components: { Checkbox },
        props: {
            prefixCls: String,
            treeTable:{
                type:Boolean,
                default:false
            },
            row: Object,
            column: Object,
            naturalIndex: Number,    // index of rebuildData
            index: Number,           // _index of data
            level:Number,
            expandLevel:Number,
            checked: Boolean,
            disabled: Boolean,
            fixed: {
                type: [Boolean, String],
                default: false
            }
        },
        data () {
            return {
                renderType: '',
                uid: -1,
                context: this.$parent.$parent.currentContext
            };
        },
        computed: {
            classes () {
                return [
                    `${this.prefixCls}-cell`,
                    {
                        [`${this.prefixCls}-hidden`]: !this.fixed && this.column.fixed && (this.column.fixed === 'left' || this.column.fixed === 'right'),
                        [`${this.prefixCls}-cell-ellipsis`]: this.column.ellipsis || false
                    }
                ];
            }
        },
        methods: {
            foreachNodeClose:function (child) {
                let obj;
                for(let i=0;i<child.length;i++){
                    if(child[i].child==undefined||child[i].child==null||child[i].child.length==0){
                        obj=document.getElementById("tr_"+child[i].pId+"_"+child[i].id+"");
                        this.addClass(obj,"ut-hidden");
                        this.removeClass(obj,"ut-expanded");
                    }else{
                        obj=document.getElementById("tr_"+child[i].pId+"_"+child[i].id+"");
                        this.addClass(obj,"ut-hidden");
                        this.removeClass(obj,"ut-expanded");
                        this.foreachNodeClose(child[i].child);
                    }
                }
            },
            foreachNodeOpen:function (child,vExpandLevel,level) {
                level=parseInt(level)+1;
                let obj;

                for(let i=0;i<child.length;i++){
                    if(child[i].child==undefined||child[i].child==null||child[i].child.length==0){
                        obj=document.getElementById("tr_"+child[i].pId+"_"+child[i].id+"");
                        this.removeClass(obj,"ut-hidden");
                        this.addClass(obj,"ut-table-tree-leaf")
                    }else{
                        obj=document.getElementById("tr_"+child[i].pId+"_"+child[i].id+"");
                        this.removeClass(obj,"ut-hidden");
                        if(level<vExpandLevel) {
                            this.foreachNodeOpen(child[i].child,vExpandLevel,level);
                        }
                    }
                }
            },
            hasClass:function (obj,cls) {
                return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
            },
            addClass:function (obj,cls) {
                if (!this.hasClass(obj, cls)) obj.className += " " + cls;
            },
            removeClass:function (obj,cls) {
                if (this.hasClass(obj, cls)) {
                    var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
                    obj.className = obj.className.replace(reg, ' ');
                }
            },
            operateNode:function (row) {
                let obj;
                if(row.pId==null||row.pId==""){
                    obj=document.getElementById("tr_Root_"+row.id);
                } else{
                    obj=document.getElementById("tr_"+row.pId+"_"+row.id);
                }
                if(this.hasClass(obj,"ut-expanded")){
                    this.removeClass(obj,"ut-expanded")
                    this.foreachNodeClose(row.child);
                }else{
                    let vExpandLevel=1;
                    if(parseInt(this.expandLevel)>1){
                        vExpandLevel=parseInt(this.expandLevel);
                    }
                    this.addClass(obj,"ut-expanded")
                    this.foreachNodeOpen(row.child,vExpandLevel,0)
                }
                obj=document.getElementById(row.firstR)
                this.addClass(obj,"rowOperate")
            },
            compile () {
                if (this.column.render) {
                    const $parent = this.context;
                    const template = this.column.render(this.row, this.column, this.index);
                    const cell = document.createElement('div');
                    cell.innerHTML = template;

                    this.$el.innerHTML = '';
                    let methods = {};
                    Object.keys($parent).forEach(key => {
                        const func = $parent[key];
                        if (typeof(func) === 'function' && (func.name  === 'boundFn' || func.name === 'n')) {
                            methods[key] = func;
                        }
                    });
                    const res = Vue.compile(cell.outerHTML);
                    // todo 临时解决方案

                    // 获取父组件使用的局部 component
                    const components = {};
                    Object.getOwnPropertyNames($parent.$options.components).forEach(item => {
                        components[item] = $parent.$options.components[item];
                    });

                    const component = new Vue({
                        render: res.render,
                        staticRenderFns: res.staticRenderFns,
                        methods: methods,
                        data () {
                            return $parent._data;
                        },
                        components: components
                    });
                    component.row = this.row;
                    component.column = this.column;

                    const Cell = component.$mount();
                    this.$refs.cell.appendChild(Cell.$el);
                }
            },
            destroy () {

            },
            toggleSelect () {
                this.$parent.$parent.toggleSelect(this.index);
            }
        },
        created () {
            if (this.column.type === 'index') {
                this.renderType = 'index';
            } else if (this.column.type === 'selection') {
                this.renderType = 'selection';
            }else if(this.column.type === 'treetable'){
                this.renderType = 'treetable';
            }
            else if(this.column.type==='hidden'){
                this.renderType='hidden';
            }
            else if (this.column.render) {
                this.renderType = 'render';
            } else {
                this.renderType = 'normal';
            }
        },
        mounted () {
            this.$nextTick(() => {
                this.compile();
            });
        },
        beforeDestroy () {
            this.destroy();
        },
        watch: {
            naturalIndex () {
                this.destroy();
                this.compile();
            }
        }
    };
</script>
