<template>
  <div class="selector">
    <div class="role">
      <div class="tree">
        <a-row class="wrap" type="flex" :gutter="16">
          <a-col class="content left" :span="16">
            <div class="ant-card-bordered">
              <div><strong>选择</strong></div>
              <a-row type="flex">
                <a-col :span="18">
                  <a-input-search style="margin-bottom: 8px" placeholder="搜索" @change="onChange"/>
                  <a-tree
                    class="usertree"
                    @expand="onExpand"
                    :defaultExpandAll="false"
                    :autoExpandParent="autoExpandParent"
                    :treeData="gData"
                    :showIcon="true"
                    :expandedKeys="expandedKeys"
                    @select="handleSelect"
                  >
                    <template slot="title" slot-scope="{title}">
                      <span v-if="title.indexOf(searchValue) > -1">
                        {{ title.substr(0, title.indexOf(searchValue)) }}
                        <span style="color: #f50">{{ searchValue }}</span>
                        {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
                      </span>
                      <span v-else>{{ title }}</span>
                    </template>
                    <a-icon slot="folder" type="folder"/>
                  </a-tree>
                </a-col>
                <a-col class="userlist" :span="6">
                  <div class="list">
                    <template v-for="(user, index) of userList">
                      <div class="user" @click="userSelect(user)" :key="index">
                        <span class="username">{{ user.name }}</span>
                      </div>
                    </template>
                  </div>
                </a-col>
              </a-row>

            </div>
          </a-col>

          <a-col class="content right" :span="8">
            <div class="ant-card-bordered">
              <div><strong>已选</strong></div>
              <div class="userlist">
                <template v-for="(user, index) of selectedList">
                  <a-tooltip v-if="user.name.length > 20" :key="user.id" :title="user.name">
                    <a-tag class="user" :key="index" :closable="true" @close="handleClose(user, $event)">
                      {{ `${user.name.slice(0, 20)}...` }}
                    </a-tag>
                  </a-tooltip>
                  <a-tag class="user" v-else :key="index" :closable="true" @close="handleClose(user, $event)">
                    {{ user.name }}
                  </a-tag>
                </template>
              </div>
              <div v-if="!hasSelectedData">
                暂无
              </div>
            </div>
          </a-col>
        </a-row>

      </div>
    </div>

  </div>
</template>

<script>
  import { Ellipsis } from '@/components';
  import ACol from 'ant-design-vue/es/grid/Col';
  import ARow from 'ant-design-vue/es/grid/Row';
  import { userTree } from '@/api/task';

  /**
   * 搜索时查找父级 id
   * @param key
   * @param tree
   */
  const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  /**
   * 将树状数据转换为list
   * @param data
   */
  const dataList = [];
  const generateList = (data) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const key = node.key;
      dataList.push({ key, title: node.title });
      if (node.children) {
        generateList(node.children, node.key);
      }
    }
  };

  /**
   * 将用户数据转换为list
   * @param data
   */
  let userDataList = [];
  const generateUserList = (data) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const userList = node.userList;
      userDataList = [...userDataList, ...userList];
      if (node.children) {
        generateUserList(node.children, node.key);
      }
    }
  };

  /**
   * 格式化数据为  a-tree 可用的数据
   * @param list
   * @returns {*}
   */
  function t(list) {
    const arr = list;
    for (var i = 0; i < arr.length; i++) {
      const obj = {
        slots: {
          icon: 'folder'
        }
      };
      if (arr[i].childDeptTreeResDTOS) {
        obj.children = t(arr[i].childDeptTreeResDTOS);
      }
      arr[i].userInfoList && (obj.userList = arr[i].userInfoList);
      arr[i].deptName && (obj.title = arr[i].deptName);
      arr[i].deptId && (obj.key = arr[i].deptId);
      arr[i] = obj;
    }
    return arr;
  }

  export default {
    name: 'UserSelectTree',
    components: {
      ARow,
      ACol,
      Ellipsis
    },
    model: {
      prop: 'selectedKeys',
      event: 'change'
    },
    props: {
      selectedKeys: {
        type: Array,
        default: function() {
          return [];
        }
      },
      gData: {
        type: Array,
        default: function() {
          return [];
        }
      }
    },
    data() {
      return {
        expandedKeys: [],
        searchValue: '',
        autoExpandParent: true,
        selectedList: [],
        currentTreeNode: {},
        userList: []
      };
    },
    computed: {
      hasSelectedData() {
        const flag = this.selectedList && this.selectedList.length > 0;
        return flag;
      }
    },
    methods: {
      handleClose(removedTag, e) {
        e.preventDefault();
        const selectedList = this.selectedList;
        const tags = selectedList.filter(tag => tag !== removedTag);
        this.selectedList = [...tags];
        this.$emit('change', this.selectedList.map(item => {
          return item.id;
        }));
        // this.$set(this.selectedList, 'checked', tags)
        // this.selectedList.checked = tags
        // this.$forceUpdate();
      },
      onExpand(expandedKeys) {
        this.expandedKeys = expandedKeys;
        this.autoExpandParent = false;
      },
      handleSelect(selectedKeys, e) {
        console.log('handleSelect', selectedKeys, e);
        this.currentTreeNode = e.node.dataRef;
        this.userList = this.currentTreeNode.userList[0] ? this.currentTreeNode.userList : [];
      },
      onChange(e) {
        const value = e.target.value;
        const expandedKeys = dataList.map((item) => {
          if (item.title.indexOf(value) > -1) {
            return getParentKey(item.key, this.gData);
          }
          return null;
        }).filter((item, i, self) => item && self.indexOf(item) === i);
        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true
        });
      },
      userSelect(user) {
        const hasUser = this.selectedList.some(item => {
          return item === user;
        });
        if (!hasUser) {
          this.selectedList.push(user);
          this.$emit('change', this.selectedList.map(item => {
            return item.id;
          }));
        }
      },
      getUserTreeData() {
        return userTree().then(res => {
          const list = [res.data];
          const treeData = list;
          this.gData = t(treeData);
          console.log('getUserTreeData', this.gData);
        });
      }
    },
    mounted() {
      this.gData[0] && (this.userList = this.gData[0].userList, this.currentTreeNode = this.gData[0]);
      generateList(this.gData);
      generateUserList(this.gData);
      this.selectedList = this.selectedKeys.map(id => {
        return userDataList.find(user => {
          return user.id === id;
        });
      });
    }
  };
</script>

<style lang="less" scoped>
  .wrap {
    height: 453px;
  }

  .tree {
    overflow: hidden;
  }

  .left .usertree {
    max-height: 350px;
    overflow-y: auto;
    overflow-x: hidden;
  }

  .left .userlist, .right .userlist {
    max-height: 390px;
    overflow-y: auto;
    overflow-x: hidden;
  }

  .wrap > .content {
    /*flex: 1;*/
    /*padding: 20px;*/
    display: flex;
  }

  .wrap > .content > div {
    /*flex: 1;*/
    padding: 20px;
    width: 100%;
  }

  .wrap .right .user {
    display: block;
    position: relative;
    margin-bottom: 5px;
  }

  .wrap .right .user /deep/ .anticon-close {
    position: absolute;
    right: 3px;
    line-height: 22px;
  }

  .userlist .list .user {
    padding: 4px 15px;
    cursor: pointer;
  }

  .userlist .list .user .username {
    cursor: pointer;
    transition: color .3s linear 0s;
  }

  .userlist .list .username:hover {
    cursor: pointer;
    font-weight: bold;
    color: #2eabff;
  }
</style>
