<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>
          <!-- 部门 -->
          <el-empty :image-size="100" description="似乎没有数据" v-show="deptList.length === 0"/>
          <el-scrollbar style="height:350px">
            <el-tree :data="deptList" ref="tree"  :props="deptProps" empty-text=""  node-key="deptId" default-expand-all
                     :show-checkbox="showCheckbox" check-strictly highlight-current
                     @check-change="handleCheckChange" @node-click="(node,check)=>handle(node,check)"  :filter-node-method="filterNode">
              <div class="custom-tree-node" slot-scope="{ node }"  style="width: 100%">
                <i class="el-icon-folder-opened" style="margin-right: 5px"></i>{{ node.label }}
              </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">
              <i class="el-icon-folder-opened"></i>
              <span>{{ selectItem.deptName }}</span>
              <i class="el-icon-close" @click="noSelected(selectItem)" v-if="showCheckbox===false"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
  </w-dialog>
</template>

<script>
import {getDepartmentTree} from "@/api/org";

export default {
  name: "departmentPicker",
  props: {
    value: {
      type: Array,
      default: () => {
        return [];
      }
    },
    multiple: { //是否多选
      default: true,
      type: Boolean
    },
    showCheckbox: { //是否显示左侧选择框
      default: true,
      type: Boolean
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      title: "请选择",
      selectList: [],
      filterText: "",
      deptList: [],
      deptProps:{
        value:'deptId',
        label: 'deptName',
        children: 'children'
      }
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getDepartmentTree();
  },
  computed: {
    _value: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit("input", val)
      }
    }
  },
  methods: {
    //获取部门信息
    getDepartmentTree() {
      getDepartmentTree().then(res => {
        const jsona = JSON.stringify(res.data) // 把接口返回的res.data数据转成字符串
        const jsonb = jsona.replace(/"value"/g, '"deptId"') // 修改成你要的字段
        const jsonc = jsonb.replace(/"label"/g, '"deptName"')
        this.deptList=JSON.parse(jsonc)
        console.log("获取部门信息===========", this.deptList);
      });
    },
    //通过关键字过滤树节点
    filterNode(value, data) {
      if (!value) return true;
      return data.deptName.indexOf(value) !== -1;
    },
    //用于弹开部门选择
    showDeptPicker() {
      this.visible = true;
    },
    /**
     * 选中部门
     * @param data 选择的每个节点item
     * @param checked 是否选中
     */
    handleCheckChange(data, checked) {
      // 左侧有选择框
      if (this.showCheckbox) {
        // 左侧有选择框 + 多选
        if (this.multiple) {
          //不添加重复的数据到右边
          for (let i = 0; i < this.selectList.length; i++) {
            if (this.selectList[i].deptId === data.deptId) {
              this.selectList.splice(i, 1);
              break;
            }
          }
          if (checked) {
            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].deptId === data.deptId) {
              this.selectList.splice(i, 1);
              break;
            }
          }
          if (checked) {
            this.$refs.tree.setCheckedNodes([data]);
            this.selectList = [data];
          } else if(data==='1') {
            this.$refs.tree.setCheckedKeys([]);
            this.selectList = [];
          }
        }
      }
      this._value = this.selectList
    },

    //左侧没有选择框时,点击tree-item
    /**
     * 可以点击树节点deptName,进行选择
     * @param node 选择的每个节点item
     * @param check checked(checkbox选择框)是否选中
     */
    handle(node,check) {
      if(this.multiple){
        //不添加重复的数据到右边
        for (let i = 0; i < this.selectList.length; i++) {
          if (this.selectList[i].deptId === node.deptId) {
            this.selectList.splice(i, 1);
            break;
          }
        }
        check.checked=true
        this.selectList.push(node);
      }else {
        check.checked=true
        this.selectList=[node];
      }
      this._value = this.selectList
    },
    //左侧无选择框时,右侧显示×
    noSelected(selectItem) {
      for (let i = 0; i < this.selectList.length; i++) {
        if (this.selectList[i].deptId === selectItem.deptId) {
          this.selectList.splice(i, 1);
          this.$refs.tree.setCheckedKeys(i);
          break;
        }
      }
      if (this.showCheckbox) {
        // 左侧有选择框 + 单选
        if (this.multiple===false) {
          this.$refs.tree.setCheckedKeys([]);
        }
      }
    },
    //清空
    clearSelected() {
      this.$confirm("您确定要清空已选中的项?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.handleCheckChange("1");
        if(!this.showCheckbox){
          this.selectList=[]
        }
      });
    },
    //确定按钮
    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>
