<template>
    <div class="tree-select-content">
        <a-input-search class="input-search" placeholder="请输入账户名或ID" @change="onChange" />
        <div class="tree-select-class">
            <div class="select-class-left">
                <div class="class-left-header">选择分享的账户名称</div>
                <div class="class-left-content">
                    <template>
                        <a-tree
                            v-model="checkedKeys"
                            checkable
                            :expanded-keys="expandedKeys"
                            :auto-expand-parent="autoExpandParent"
                            :selected-keys="selectedKeys"
                            :tree-data="treeData"
                            @check="onCheck"
                            @expand="onExpand"
                        />
                    </template>
                    <div class="example">
                        <a-spin :spinning="spinning"/>
                        <span v-if="leftTreeNoData">暂无数据</span>
                    </div>
                </div>
            </div>
            <div class="select-class-right">
                <div class="class-left-header">
                    已选 （{{ applyTypeOption.length ? applyTypeOption.length : 0}}/100）
                    <a-popover placement="topRight">
                        <template slot="content">
                            <p>1、输入账户超出推送范围，请检查是否同主体账户</p>
                            <p>2、有效账户将不会重复推送，请登录该账户查看使用</p>
                        </template>
                        <span><a-icon type="question-circle" /></span>
                    </a-popover>
                </div>
                <div v-if="applyTypeOption.length" class="class-left-content">
                    <div class="apply-right-tree" v-for="item in applyTypeOption" :key="item.key">
                        <p class="left-content-p">
                            <a-tooltip placement="left">
                                <template slot="title">
                                    <span>{{ item.title }}</span>
                                </template>
                                {{ item.title }}
                            </a-tooltip>
                        </p>
                        <a-icon type="delete" class="delete-type-class" @click="handleDelTree(item)" />
                    </div>
                </div>
                <div v-else class="no-data-class">暂无数据</div>
            </div>
        </div>
    </div>
</template>
<script>
import {mapGetters} from 'vuex';
import {postAction} from '@/api/manage';

export default {
    name: 'tree-select',
    data() {
        return {
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [],
            treeData: [],
            updateTreeData: [],
            applyTypeOption: [],
            selectRightData: new Set(),
            spinning: true,
            leftTreeNoData: false,
            middleValue: []
        };
    },
    mounted() {
        this.getAccountId();
    },
    methods: {
        ...mapGetters(['userInfo']),
        getAccountId() {
            postAction('/ctop/projectMember/participateListByMediaId', {
                userId: this.userInfo().id,
                type: 'kuaishou'
            }).then(result => {
                if (result.result.length) {
                    this.spinning = false;
                    this.treeData = result.result.map(item => {
                        return {
                            key: item.projectId + 'projectId',
                            title: item.projectName + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0' + item.advertiserName,
                            children: item.accountList
                            ? item.accountList.map(i => {
                                return {
                                    key: i.accountId,
                                    title:
                                    (i.userName.length === 2
                                        ? i.userName + '\xa0\xa0\xa0\xa0\xa0'
                                        : i.userName.length === 3
                                        ? i.userName + '\xa0\xa0\xa0\xa0'
                                        : i.userName)
                                        + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0'
                                        + i.accountId
                                        + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0'
                                        + i.authName
                                };
                            }) : []
                        };
                    });
                    this.updateTreeData = [...this.treeData];
                }
                else {
                    this.spinning = false;
                    this.leftTreeNoData = true;
                }
            });
        },
        handleDelTree(list) {
            const defaultTypeOption = JSON.parse(JSON.stringify(this.applyTypeOption));
            const defaultCheckKey = JSON.parse(JSON.stringify(this.checkedKeys));
            const len = defaultTypeOption.length;
            const keysLen = defaultCheckKey.length;
            for(let i = len - 1; i >= 0; i--) {
                if(defaultTypeOption[i].key === list.key) {
                    defaultTypeOption.splice(i, 1);
                }
            }
            this.applyTypeOption = defaultTypeOption;
            this.selectRightData = new Set(defaultTypeOption);
            const txt = this.handleDelFindId(this.treeData, list.key);
            const lastIndex = defaultCheckKey.findIndex(item => item === txt);
            let value = null;
            if (lastIndex > -1) {
                value = defaultCheckKey.findIndex(item => item === txt);
                for(let i = keysLen - 1; i >= 0; i--) {
                    if(defaultCheckKey[i] === list.key) {
                        defaultCheckKey.splice(i, 1);
                    }
                }
            }
            else {
                value = defaultCheckKey.findIndex(item => item === list.key);
            }
            defaultCheckKey.splice(value, 1);
            this.checkedKeys = defaultCheckKey;
            this.$emit('applyType', this.applyTypeOption);
        },
        onChange(e) {
            const value = e.target.value;
            this.treeData = value !== '' ? this.getNewTreeData(this.updateTreeData, value) : [...this.updateTreeData];
            if(value !== '') {
                this.middleValue = this.checkedKeys.filter(item=>typeof item === 'number');
            }
            else {
                this.middleValue = [];
            }
            if (!this.treeData.length) {
                this.spinning = false;
                this.leftTreeNoData = true;
            }
            else {
                this.leftTreeNoData = false;
            }
        },
        handleDelFindId(treeData, value) {
            if (!treeData) {
                return null;
            }
            let node = null;
            let children = null;
            let text = '';
            for (let i = 0; i < treeData.length; i++) {
                node = treeData[i];
                if (node.children) {
                    children = node.children;
                    text = node.key;
                    for (let j = 0; j < children.length; j++) {
                        if (children[j].key === value) {
                            return text;
                        }
                    }
                }
            }
        },
        // 根据关键词查询所有相关的tree节点
        getNewTreeData(treeData, value) {
            if (!treeData) {
                return null;
            }
            let newTreeData = new Array();
            let node = null;
            let children = null;
            let text = '';
            for (let i = 0; i < treeData.length; i++) { // 多个根节点开始遍历
                node = treeData[i];
                if (node.children) {
                    children = node.children;
                }
                text = node.title;
                if (text.indexOf(value) > -1) {
                    newTreeData.push(node);
                    continue;
                }
                else {
                    if (children) {
                        let newNodes = this.getNewTreeData(node.children, value);
                        if (newNodes.length > 0) {
                            node.children = newNodes;
                            newTreeData.push(node);
                        }
                    }
                }

            }
            return newTreeData;
        },
        onExpand(expandedKeys) {
            this.expandedKeys = expandedKeys;
            this.autoExpandParent = false;
        },
        // 去重的方法
        Es6duplicate(arr, type) {
            if (!arr.length){
                return arr;
            }
            else {
                if (type) {
                    let obj = {};
                    let newArr = arr.reduce((cur, next) => {
                        obj[next.key] ? '' : obj[next.key] = true && cur.push(next);
                        return cur;
                    }, []);
                    return newArr;
                }
                else {
                    return Array.from(new Set(arr));
                }
            }
        },
        onCheck(checkedKeys) {
            this.nodes(this.treeData, checkedKeys);
            const filterCheckKey = this.checkedKeys.filter(item => typeof item === 'number');
            let filterCheckKeySet = new Set(filterCheckKey.concat(this.middleValue));
            let selectRightDataSet = new Set(this.selectRightData);
            let difference = new Set([...selectRightDataSet].filter(item => !filterCheckKeySet.has(item.key)));
            this.selectRightData.delete(...difference);
            this.applyTypeOption = this.Es6duplicate([...this.selectRightData], 'key');
            const changeSelectData = this.applyTypeOption.map(item => item.key);
            this.checkedKeys = changeSelectData;
              
            if (this.applyTypeOption.length > 100) {
                const lastOptionKey = this.applyTypeOption[99].key;
                const lastIndex = changeSelectData.findIndex(item => item === lastOptionKey);
                this.checkedKeys = changeSelectData.slice(0, lastIndex + 1);
                this.applyTypeOption = [...this.selectRightData].slice(0, 100);
            }
            this.$emit('applyType', this.applyTypeOption);
        },
        nodes(data, checkedKeys) {
            data.forEach(item => {
                if (item.children) {
                    this.nodes(item.children, checkedKeys);
                }
                else {
                    if (checkedKeys.indexOf(item.key) !== -1) {
                        this.selectRightData.add(item);
                    }
                    else {
                        this.selectRightData.delete(item);
                    }
                }
            });
        }
    }
};
</script>
<style lang="less" scoped>
    @import 'tree-select';
</style>