<template>
    <div :class="classes" :lstyle="lstyle">
        <div :class="prefixCls + '-header'">
            <template v-if="checkHidden"></template>
            <template v-else>
                <Checkbox :value="checkedAll" :disabled="checkedAllDisabled" @on-change="toggleSelectAll"></Checkbox>
            </template>
            <span>{{ title }}</span>
            <span :class="prefixCls + '-header-count'">{{ count }}</span>
        </div>
        <div :class="bodyClasses">
            <div :class="prefixCls + '-body-search-wrapper'" v-if="filterable">
                <Search
                        :prefix-cls="prefixCls + '-search'"
                        :query="query"
                        @on-query-clear="handleQueryClear"
                        @on-query-change="handleQueryChange"
                        :placeholder="filterPlaceholder"></Search>
            </div>
            <template v-if="leftTree">
                <ul :class="prefixCls + '-content'">
                    <template v-for="item in filterData">
                        <li
                                :id="liID(item.pId,item.key)"
                                :class="itemClasses(item)"
                                @click.prevent="select(item)">
                            <template v-for="le in item.level">
                                <span class="ut-transfer-tree-indent"></span>
                            </template>
                            <span v-if="operateClass(item)" class="ut-transfer-tree-indent"></span>
                            <span class="ut-transfer-tree-swc"  @click="operateNode(item)">
                                  <template v-if="item.hasChild">
                                  <Icon type="arrow-right-b"></Icon>
                                  </template>
                            </span>
                            <img v-if="item.icon" :src="item.icon" @click="operateNode(item)" width="18px" height="18px"/>
                            <template v-if="checkHidden"></template>
                            <template v-else>
                                <Checkbox :value="isCheck(item)" :disabled="item.disabled"></Checkbox>
                            </template>
                            <span v-html="showLabel(item)"></span>
                        </li>
                    </template>
                    <li :class="prefixCls + '-content-not-found'">{{ notFoundText }}</li>
                </ul>
            </template>
            <template v-else>
                <ul :class="prefixCls + '-content'">
                    <li
                            v-for="item in filterData"
                            :class="itemClasses(item)"
                            @click.prevent="select(item)">
                        <template v-if="checkHidden"></template>
                        <template v-else>
                            <Checkbox :value="isCheck(item)" :disabled="item.disabled"></Checkbox>
                        </template>
                        <span v-html="showLabel(item)"></span>
                    </li>
                    <li :class="prefixCls + '-content-not-found'">{{ notFoundText }}</li>
                </ul>
            </template>
        </div>
        <div :class="prefixCls + '-footer'" v-if="showFooter"><slot></slot></div>
    </div>
</template>
<script>
    import Search from './search.vue';
    import Checkbox from '../checkbox/checkbox.vue';

    export default {
        name: 'TransferList',
        components: { Search, Checkbox },
        props: {
            prefixCls: String,
            data: Array,
            leftTree:{
                type:Boolean,
                default:false
            },
            checkHidden:{
                type:Boolean,
                default:false
            },
            renderFormat: Function,
            checkedKeys: Array,
            lstyle: Object,
            title: [String, Number],
            filterable: Boolean,
            filterPlaceholder: String,
            filterMethod: Function,
            notFoundText: String,
            validKeysCount: Number
        },
        data () {
            return {
                showItems: [],
                query: '',
                showFooter: true
            };
        },
        watch: {
            data () {
                this.updateFilteredData();
            }
        },
        computed: {
            classes () {
                return [
                    `${this.prefixCls}`,
                    {
                        [`${this.prefixCls}-with-footer`]: this.showFooter
                    }
                ];
            },
            bodyClasses () {
                return [
                    `${this.prefixCls}-body`,
                    {
                        [`${this.prefixCls}-body-with-search`]: this.filterable,
                        [`${this.prefixCls}-body-with-footer`]: this.showFooter
                    }
                ];
            },
            count () {
                let totalCount=this.data.length;
                if(this.leftTree){
                    let vCount=0;
                    let obj;
                    for (let i=0;i<this.data.length;i++){
                        if(!this.data[i].hasChild&&this.data[i].pId!=null&&this.data[i].pId!=""){
                            obj=document.getElementById("li_" + this.data[i].pId + "_" + this.data[i].key);
                            if (obj!=undefined&&obj!=null&&this.hasClass(obj, "remove-hidden")){
                            }else{
                                vCount=vCount+1;
                            }
                        }
                    }
                    totalCount=vCount;
                }
                const validKeysCount = this.validKeysCount;
                return (validKeysCount > 0 ? `${validKeysCount}/` : '') + `${totalCount}`;
            },
            checkedAll () {
                return this.data.filter(data => !data.disabled).length === this.validKeysCount && this.validKeysCount !== 0;
            },
            checkedAllDisabled () {
                return this.data.filter(data => !data.disabled).length <= 0;
            },
            filterData () {
                return this.showItems.filter(item => this.filterMethod(item, this.query));
            }
        },
        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("li_"+child[i].pId+"_"+child[i].key+"");
                        this.addClass(obj,"ut-hidden");
                        this.removeClass(obj,"ut-expanded");
                    }else{
                        obj=document.getElementById("li_"+child[i].pId+"_"+child[i].key+"");
                        this.addClass(obj,"ut-hidden");
                        this.removeClass(obj,"ut-expanded");
                        this.foreachNodeClose(child[i].child);
                    }
                }
            },
            foreachNodeOpen:function (child,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("li_"+child[i].pId+"_"+child[i].key+"");
                        this.removeClass(obj,"ut-hidden");
                        this.addClass(obj,"ut-transfer-tree-leaf")
                    }else {
                        obj = document.getElementById("li_" + child[i].pId + "_" + child[i].key + "");
                        this.removeClass(obj, "ut-hidden");
                        if(level>2){
                            this.foreachNodeOpen(child[i].child, 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("li_Root_"+row.key);
                } else{
                    obj=document.getElementById("li_"+row.pId+"_"+row.key);
                }
                if(this.hasClass(obj,"ut-expanded")){
                    this.removeClass(obj,"ut-expanded")
                    this.foreachNodeClose(row.child);
                }else{
                    this.addClass(obj,"ut-expanded")
                    this.foreachNodeOpen(row.child,0)
                }
                obj=document.getElementById(row.firstR)
                this.addClass(obj,"rowOperate")
            },
            liID:function (pID,ID) {
                return (pID==null||pID=="")?"li_Root_"+ID+"":"li_"+pID+"_"+ID+""
            },
            itemClasses (item) {
                console.log(item.disabled)
                console.log((item.disabled!=undefined)?item.disabled:false)
                return [
                    `${this.prefixCls}-content-item`,
                    {
                        [`${this.prefixCls}-content-item-disabled`]: (item.disabled!=undefined)?item.disabled:false
                    },
                    this.treeItemClass(item)
                ];
            },
            treeItemClass(item){
                let sReturn="";
                if(item.level!=undefined&&item.level!=null&&this.leftTree){
                    let obj=document.getElementById(item.firstR);
                    if(obj==undefined){
                        if(item.level==0){
                            if(item.parentTr=="Root"){
                                sReturn="rowOperate"
                            }else{
                                sReturn="ut-transfer-tree-leaf"
                            }
                        }else{
                            sReturn="ut-hidden"
                        }
                    }
                    else{
                        if(this.hasClass(obj,"rowOperate")){
                            if(item.parentTr=="Root"){
                                obj=document.getElementById("li_Root_"+item.key);
                                sReturn=" rowOperate"
                            }else{
                                obj=document.getElementById("li_"+item.pId+"_"+item.key);
                            }
                            if(this.hasClass(obj,"ut-transfer-tree-leaf")){
                                sReturn="ut-transfer-tree-leaf "+sReturn
                            }
                            if(this.hasClass(obj,"ut-hidden")){
                                sReturn="ut-hidden "+sReturn
                            }
                            if(this.hasClass(obj,"ut-expanded")){
                                sReturn="ut-expanded "+sReturn
                            }
                        }else{
                            if(item.level==0){
                                if(item.parentTr=="Root"){
                                    sReturn="rowOperate"
                                }else{
                                    sReturn="ut-transfer-tree-leaf"
                                }
                            }else{
                                sReturn="ut-hidden"
                            }
                        }
                    }
                }
                return sReturn;
            },
            operateClass(item){
                let bReturn=false
                if(item.parentTr!="Root"&&!item.hasChild){
                    bReturn=true;
                }
                return bReturn;
            },
            showLabel (item) {
                return this.renderFormat(item);
            },
            isCheck (item) {
                return this.checkedKeys.some(key => key === item.key);
            },
            select (item) {
                if (item.disabled!=undefined?item.disabled:false) return;
                if(this.checkHidden){
                    this.checkedKeys.splice(0,this.checkedKeys.length);
                }
                if (this.leftTree) {
                    if (item.parentTr == "Root") {
                    } else {
                        let obj = document.getElementById("li_" + item.pId + "_" + item.key);
                        if (this.hasClass(obj, "ut-transfer-tree-leaf")) {
                            const index = this.checkedKeys.indexOf(item.key);
                            index > -1 ? this.checkedKeys.splice(index, 1) : this.checkedKeys.push(item.key);
                        }
                    }
                } else {
                    const index = this.checkedKeys.indexOf(item.key);
                    index > -1 ? this.checkedKeys.splice(index, 1) : this.checkedKeys.push(item.key);
                }
            },
            updateFilteredData () {
                this.showItems = this.data;
            },
            toggleSelectAll (status) {
                const keys = status ?
                        this.data.filter(data => !(data.disabled!=undefined?data.disabled:false) || this.checkedKeys.indexOf(data.key) > -1).map(data => data.key) :
                        this.data.filter(data => (data.disabled!=undefined?data.disabled:false) && this.checkedKeys.indexOf(data.key) > -1).map(data => data.key);
                this.$emit('on-checked-keys-change', keys);
            },
            handleQueryClear () {
                this.query = '';
            },
            handleQueryChange (val) {
                this.query = val;
            }
        },
        created () {
            this.updateFilteredData();
        },
        mounted () {
            this.showFooter = this.$slots.default !== undefined;
        }
    };
</script>

