<template>
  <div class="selector">
    <div class="role">
      <div class="tree">
        <a-row class="wrap" type="flex" :gutter="16">
          <a-col class="content left" :span="12">
            <div class="ant-card-bordered">
              <div><strong>选择</strong></div>
              <!-- <a-input-search style="margin-bottom: 8px" placeholder="搜索" @change="onChange"/>-->
              <a-tree
                ref="roleTree"
                @expand="onExpand"
                :expandedKeys="expandedKeys"
                :autoExpandParent="autoExpandParent"
                :treeData="gData"
                :checkable="true"
                :checkStrictly="true"
                v-model="selectedList"
                @check="handleCheck"
              >
                <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-tree>
            </div>
          </a-col>

          <a-col class="content right" :span="12">
            <div class="ant-card-bordered">
              <div><strong>已选</strong></div>
              <template v-for="(role, index) in selectedListForTags">
                <a-tooltip v-if="role.title.length > 20" :key="role.key" :title="role.title">
                  <a-tag class="role" :key="role.key" :closable="true" @close="handleClose(role, $event)">
                    {{ `${role.title.slice(0, 20)}...` }}
                  </a-tag>
                </a-tooltip>
                <a-tag class="role" v-else :key="role.key" :closable="true" @close="handleClose(role, $event)">
                  {{ role.title }}
                </a-tag>
              </template>
              <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 { roleTree } from '@/api/task';

  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;
  };

  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);
      }
    }
  };

  export default {
    name: 'RoleSelectTree',
    components: {
      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: this.selectedKeys,
        selectedListForTags: []
      };
    },
    computed: {
      hasSelectedData() {
        const flag = this.selectedListForTags && this.selectedListForTags.length > 0;
        return flag;
      }
    },
    methods: {
      handleClose(removedTag, e) {
        e.preventDefault();
        this.selectedListForTags = this.selectedListForTags.filter(tag => tag !== removedTag);
        console.log('handClse', this.selectedList);
        let selectedList = this.selectedList && this.selectedList.checked;
        if (Array.isArray(this.selectedList)) {
          selectedList = [...this.selectedList];
        }
        const tags = selectedList.filter(tag => tag !== removedTag.key);
        this.selectedList = Object.assign({}, this.selectedList, {
          checked: tags
        });
        this.$emit('change', this.selectedList.checked);
        // this.$set(this.selectedList, 'checked', tags)
        // this.selectedList.checked = tags
        // this.$forceUpdate();
      },
      onExpand(expandedKeys) {
        this.expandedKeys = expandedKeys;
        this.autoExpandParent = false;
      },
      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
        });
      },
      handleCheck(checkedKeys, e) {
        console.log('handleCheck', checkedKeys, e);
        // const checked
        const hasKey = this.selectedListForTags.some(item => {
          return item.key === e.node.eventKey;
        });
        // 取消选中
        if (!e.checked && hasKey) {
          console.log(3);

          this.selectedListForTags = this.selectedListForTags.filter(item => {
            return item.key !== e.node.eventKey;
          });
        }
        // 选中
        if (e.checked && !hasKey) {
          this.selectedListForTags.push(e.node.dataRef);
        }
        this.$emit('change', this.selectedList.checked);
      },
      getRoleTreeData() {
        return roleTree().then(res => {
          const list = res.data || [];
          const treeData = list.map(role => {
            const obj = Object.assign({}, {
              key: role.id,
              title: role.name,
              children: role.roles.map(cRole => {
                const cObj = Object.assign({}, {
                  key: cRole.id,
                  title: cRole.name
                });
                return cObj;
              })
            });
            return obj;
          });
          this.gData = treeData;
        });
      }
    },
    async mounted() {
      // await this.getRoleTreeData()
      generateList(this.gData);
      this.selectedListForTags = this.selectedKeys.map(key => {
        return dataList.find(role => {
          return role.key === key;
        });
      });
    }
  };
</script>

<style lang="less" scoped>
  .tree {
    overflow: hidden;
  }

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

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

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

  .wrap .right .role /deep/ .anticon-close {
    position: absolute;
    right: 3px;
    line-height: 22px;
  }
</style>
