<template>
  <w-dialog :border="false" closeFree width="600px" @ok="selectConfirm" :title="title" v-model="visible">
    <div>
      <div class="picker">
        <div class="candidate" v-loading="loading">
          <div style="padding: 5px 8px;">
            <el-input v-model="filterText" style="width: 100%;" size="small"
                      clearable placeholder="输入关键字进行过滤" prefix-icon="el-icon-search"/>
            <div style="margin-top: 5px">
              <el-radio-group v-model="radio" size="mini" @input="radioChange">
                <el-radio-button :label="0">角色</el-radio-button>
                <el-radio-button :label="1">部门</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <!-- 人员选择 -->
          <el-empty :image-size="100" description="似乎没有数据" v-show="dataList.length === 0"/>
          <el-scrollbar style="height:350px">
            <el-tree :data="dataList" ref="tree" :props="defaultProps" empty-text="" node-key="value"
                     :default-expanded-keys="expandedKeys"
                     :show-checkbox="showCheckbox"
                     @check-change="handleCheckChange"
                     @node-click="handleChange"
                     :filter-node-method="filterNode"
                     check-strictly
            >
              <div class="custom-tree-node" slot-scope="{  node,data }">
                <div v-if="data.type === 0" :style="'height:'+(data.type === 0 ?'50px':'0px')">
                  <el-avatar :src="data.avatar"></el-avatar>
                  {{ node.label }}
                </div>
                <div v-else-if="data.type === 1">
                  <el-icon class="el-icon-user-solid"/>
                  {{ node.label }}
                </div>
                <div v-else>
                  <el-icon class="el-icon-folder-opened"/>
                  {{ node.label }}
                </div>
              </div>
            </el-tree>
          </el-scrollbar>
        </div>

        <div class="selected">
          <div class="count">
            <span>已选 {{ selectList.length }} 项</span>
            <span @click="clearSelected">清空</span>
          </div>
          <div class="org-items" style="height: 350px;">
            <el-empty :image-size="100" description="请点击左侧列表选择数据" v-show="selectList.length === 0"/>
            <div v-for="(selectItem, selectIndex) in selectList" :key="selectIndex" class="org-item">
              <el-avatar :src="selectItem.avatar"></el-avatar>
              {{ selectItem.name }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </w-dialog>
</template>

<script>
import {getUserTree} from "@/api/org";
export default {
  name: "UserPicker",
  props: {
    value: {
      type: Array,
      default: () => {
        return [];
      }
    },
    multiple: { //是否多选
      default: true,
      type: Boolean
    },
    showCheckbox: { //是否显示左侧选择框
      default: true,
      type: Boolean
    }
  },
  data() {
    return {
      radio: 0,
      chooseId: 0,
      selectItem: {
        type: -1,
        value: '0',
      },
      activeNames: ['1'],
      visible: false,
      loading: false,
      title: "请选择",
      selectList: [],
      filterText: "",
      dataList: [],
      expandedKeys: [],
      defaultProps: {
        value: 'value',
        label: 'name',
        children: 'children',
      }
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
  },
  computed: {
    _value: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit("input", val)
      }
    }
  },
  methods: {
    radioChange(e) {
      this.selectItem.type = -2
      this.chooseId = 0
      this.radio = e
      this.expandedKeys = []
      this.getList();
    },
    getList() {
      getUserTree(this.radio, this.chooseId).then(res => {
        if (this.selectItem.type === -1 || this.selectItem.type === -2) {
          this.dataList = this.setData(res.data)
          console.log('--111--2', res.data)
        } else if (this.selectItem.type === 1) {
          this.selectItem.children = res.data
          console.log('111', res.data)
        } else if (this.selectItem.type === 2) {
          console.log('222', res.data)
          this.selectItem.children = this.setData(res.data)
        }
      });
    },
    setData(source) {
      for (let item of source) {
        this.$set(item, "value", this.selectItem.value + "-" + item.id)
        this.$set(item, "children", [])
      }
      return source;
    },
    //通过关键字过滤树节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //用于用户选择
    showUserPicker() {
      this.visible = true;
    },
    //渲染子节点用户或部门及用户数据
    handleChange(item) {
      this.selectItem = item
      this.expandedKeys.push(item.value)
      if (item.type !== 0) {
        this.chooseId = item.id
        this.getList()
      }
    },
    /**
     * 选中用户
     * @param data 选择的每个节点item
     * @param checked 是否选中
     */
    handleCheckChange(data, checked) {
      // 左侧有选择框
      if (this.showCheckbox) {
        // 左侧有选择框 + 多选
        if (this.multiple) {
          // console.log('左侧有选择框 + 多选')
          // //不添加重复的数据到右边
          // for (let i = 0; i < this.selectList.length; i++) {
          //   if (this.selectList[i].value === data.value) {
          //     this.selectList.splice(i, 1);
          //     break;
          //   }
          // }
          // if (checked) {
          //   // if (data.children === undefined) {
          //   this.selectList.push(data);
          //   // }
          // } else if (data === '1') {
          //   this.$refs.tree.setCheckedKeys([]);
          //   this.selectList = [];
          // }
        } else {// 左侧有选择框 + 单选
          //不添加重复的数据到右边
          for (let i = 0; i < this.selectList.length; i++) {
            if (this.selectList[i].id === data.id) {
              this.selectList.splice(i, 1);
              break;
            }
          }
          if (checked) {
            console.log('this.$refs.tree',this.$refs.tree)
            // if(data.type==0){
            // this.$refs.tree.setCheckedNodes([data]);
            this.selectList = [data];
            // }
          } else if (data === "1") {
            this.selectList = [];
            this.$refs.tree.setCheckedKeys([]);
          }
        }
      }
      this._value = this.selectList
    },

    //清空
    clearSelected() {
      this.$confirm("您确定要清空已选中的项?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.handleCheckChange("1");
      });
    },
    //确定按钮
    selectConfirm() {
      this.$emit("ok", this.selectList);
      this.visible = false;
    }
  }
};
</script>

<style lang="less" scoped>
@containWidth: 278px;
/deep/ .el-tree-node {
  .is-leaf + .el-checkbox .el-checkbox__inner {
    display: inline-block;
  }

  .el-checkbox .el-checkbox__inner {
    display: none;
  }
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}

.picker {
  height: 402px;
  position: relative;
  text-align: left;

  .candidate {
    left: 0;
    top: 0;
  }
}

.candidate, .selected {
  position: absolute;
  display: inline-block;
  width: @containWidth;
  height: 400px;
  border: 1px solid #e8e8e8;
}

.selected {
  border-left: none;
  right: 0;
  top: 0;

  .count {
    width: calc(@containWidth - 20px);
    padding: 10px;
    display: inline-block;
    border-bottom: 1px solid #e8e8e8;
    margin-bottom: 5px;

    & > span:nth-child(2) {
      float: right;
      color: #c75450;
      cursor: pointer;
    }
  }
}

.org-items {
  overflow-y: auto;
  height: 350px;

  .el-icon-close {
    position: absolute;
    right: 5px;
    cursor: pointer;
    font-size: larger;
  }

  .org-item {
    margin: 0 5px;
    border-radius: 5px;
    position: relative;
    padding: 7px 5px;
    display: flex;
    align-items: center;

    cursor: pointer;

    &:hover {
      background: #f1f1f1;
    }

    > span {
      margin-left: 5px;
    }
  }
}

/deep/ .el-scrollbar .el-scrollbar__wrap {
  overflow-x: hidden;
}

::-webkit-scrollbar {
  float: right;
  width: 4px;
  height: 4px;
  background-color: white;
}

::-webkit-scrollbar-thumb {
  border-radius: 16px;
  background-color: #efefef;
}

</style>
