<template>
  <div>
    <div class="employee_selector_box">
      <el-row :gutter="10">
        <el-col :xs="11" :sm="11" :md="11" :lg="11" :xl="11" class="scroller-box one">
          <div class="search-box">
            <!-- <div class="search flex-box" style="margin-bottom: 7px;"><el-input v-model="keyword" placeholder="请输入内容" clearable></el-input></div> -->
            <div class="search flex-box" style="margin-top: 7px; width: 80%; position: relative;">
              <deptData  v-if="toPdept1 && toPdept1!=0" :refsName="$refs.dept1" :toPdept="toPdept1"></deptData>
              <el-cascader
                style="width: 100%;"
                v-model="dept_id"
                @change="dept1_null"
                ref="dept1"
                :options="dept_list"
                :props="{ checkStrictly: true, value: 'id', label: 'name', children: 'children' }"
                clearable
                filterable
                placeholder="全公司"
              >
                <template slot-scope="{ node, data }">
                  <span>
                    <WWOpenData type="departmentName" :openid="data.name"></WWOpenData>
                  </span>
                </template>
              </el-cascader>
            </div>
          </div>
          <div class="flex-box-end" v-if="isChecKedAll&&multi" style="padding: 10px;border-bottom: 1px solid #f1f1f1;">
            <el-checkbox v-model="checked" @change="checkedChange">全选</el-checkbox>
          </div>
          <el-scrollbar wrap-class="column-wrapper scrollable-items-container" :native="false" :class="isChecKedAll ? 'scrollbarHeight1' : 'scrollbarHeight2'" v-loading="table_loading">
            <div class="choose_left">
              <div class="persons_box" style="padding-top:4px;" v-if="list.length > 0">
                <a class="employee_cell_a" href="javascript:void(0)" v-for="(item, index) in list" :key="index" v-show="item.id">
                  <div class="employee_cell" v-if="can_select_employee" @click.prevent.stop="select_employee(item)">
                    <div class="employee_checkbox"><el-checkbox v-model="item.checked"></el-checkbox></div>
                    <div class="employee_img_url"><img :src="item.img_url" class="employee_cell_head_img" /></div>
                    <div class="employee_name">
                      <WWOpenData type="userName" :openid="item.name"></WWOpenData>
                      <!-- {{ item.name }} -->
                    </div>
                    <div class="employee_cell_clear"></div>
                  </div>
                </a>
              </div>
              <div v-else class="fontColorF" style="text-align: center;margin-top: 50px;">暂无可选人员</div>
            </div>
          </el-scrollbar>
        </el-col>
        <el-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2" class="col-line"><span style="opacity: 0;">空</span></el-col>
        <el-col :xs="11" :sm="11" :md="11" :lg="11" :xl="11" class="scroller-box">
          <div class="option-box">
            <span style="line-height: 40px; padding-left: 10px;" class="fl" v-show="multi">已选择{{ employee_selected_list.length }}个员工</span>
            <el-button type="type" @click="clear_data">清空</el-button>
          </div>
          <el-scrollbar wrap-class="column-wrapper scrollable-items-container" :native="false" style="height: 400px;">
            <div class="choose_right">
              <div class="employee_cell" v-for="(item, index) in dept_selected_list" :key="index">
                <div class="employee_name">
                  <WWOpenData type="departmentName" :openid="data.name"></WWOpenData>
                  <!-- {{ item.dept_name }} -->
                </div>
                <div class="employee_delete"><el-button type="default" size="mini" @click="dept_cancel(item)" icon="el-icon-close" circle></el-button></div>
                <div class="employee_cell_clear"></div>
              </div>
              <div class="employee_cell" v-for="(item, index) in employee_selected_list" :key="index">
                <div class="employee_img_url" v-if="item.img_url"><img :src="item.img_url" class="employee_cell_head_img" /></div>
                <div class="employee_img_url" v-else><img src="static/images/head_default.png" class="employee_cell_head_img" /></div>
                <div class="employee_name">
                  <WWOpenData type="userName" :openid="item.name"></WWOpenData>
                  <!-- {{ item.name }} -->
                </div>
                <div class="employee_delete"><el-button type="default" size="mini" @click="employee_cancel(item, true)" icon="el-icon-close" circle></el-button></div>
                <div class="employee_cell_clear"></div>
              </div>
            </div>
          </el-scrollbar>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
var timers = null;
export default {
  props: {
    can_select_dept: {// 是否能选择部门
      type: Boolean,
      default: true
    },
    can_select_employee: {// 指定是否能选择员工
      type: Boolean,
      default: true
    },
    employee_not_select: {// 排除员工的ID，包含ID时不出现在选择列表中
      type: Array,
      default: () => {
        return [];
      }
    },
    dept_not_select: { // 排除部门ID
      type: Array,
      default: () => {
        return [];
      }
    },
    selected: {// 已经选择的员工和部门
      type: Object,
      default: () => {
        return { employee: [], dept: [] };
      }
    },
    multi: { // 指定员工是否能多选
      type: Boolean,
      default: true
    },
    dept_multi: { // 指定部门是否能多选
      type: Boolean,
      default: true
    },
    employee_list: { // 指定显示的员工列表，注意：传值后组件的员工数据将不是统一向服务器获取的，而是指定的员工列表，格式是：[{id: 1, name: “张三”, img_url: “”}]
      type: Array,
      default: () => {
        return [];
      }
    },
    user_employee_list:{// 为true时，employee_list才生效
    		 type: Boolean,
    		 default: false
    },
    isChecKedAll: { //是否全选
      type: Boolean,
      default: true
    },
    close_clear_data: { //关闭时是否清除选择的数据
      type: Boolean,
      default: true
    },
    max: { //选择的人数限制
      type: Number,
      default: 0
    },
    is_filtration_creator:{//是否去除创始人
      type: Boolean,
      default: false
    },
    is_manager_only:{//是否只显示管理者
      type: Boolean,
      default: false
    },
    include_self:{//是否显示自己
      type: Boolean,
      default: true
    },
  },
  name: 'EmployeeSelector',
  data() {
    let selected = JSON.parse(JSON.stringify(this.selected));
    return {
      table_loading:false,
      searchBox: [],//用于搜索的全部人员
      employee_selected_list: selected.employee,
      dept_selected_list: selected.dept,
      employee_selected: [],
      dept_selected: [],
      dept_name: '',
      dept_id: 0,
      list: [],
      dept_list: [],
      keyword: '',
      pid: 0,
      pid_list: [],
      selected_box_width: '0',
      indeterminate: false,
      pid_list_arr: [],
      checked: false,
      toPdept1:0,//选择部门的遮到
    };
  },
  watch: {
    // dept_id(val){
    // 	if(val.length>1){
    // 		this.pid=val[val.length-1];
    // 	}else{
    // 		this.pid=val[0];
    // 	}
    // 	this.$nextTick(() => {
    // 		this.$refs.dept.dropDownVisible = false;
    // 		this.get_user_list();
    // 		this.checked=false;
    // 	});
    // },
    selected: {
      deep: true,
      handler(val) {
        let selected = JSON.parse(JSON.stringify(val));
        this.employee_selected = [];
        this.dept_selected = [];
        this.employee_selected_list = selected.employee;
        this.dept_selected_list = selected.dept;
        for (let i in selected.employee) {
          this.employee_selected.push(selected.employee[i].id);
        }
        for (let i in selected.dept) {
          this.dept_selected.push(selected.dept[i].dept_id);
        }
      },
      immediate: true
    },
    keyword(val) {
      this.list = this.searchBox.filter(item => item.name.includes(this.keyword));
      if(!val){
        this.checked=false;
      }
    }
  },
  methods: {
    dept1_null(val){
      this.toPdept1 = val[val.length-1]
    	if(val.length>1){
    		this.pid=val[val.length-1];
    	}else{
    		this.pid=val[0];
    	}
      // let valItem = 0
      // for(let i in val){
      //   valItem = val[i]
      // }
      this.$nextTick(()=>{
    		this.get_user_list();
    		this.checked=false;
        this.$refs.dept1.dropDownVisible = false;
      })
    },
    // 全选
    checkedChange(val) {
      if (val) {
        this.$nextTick(() => {
          let employeeSelectedList = JSON.parse(JSON.stringify(this.employee_selected_list));//获取选择的人员
          let employeeSelectedIds = [],total = 0;
          employeeSelectedList.forEach(element => {
            employeeSelectedIds.push(element.id);
          });
          for (let i in this.list) {
            this.$set(this.list[i], 'checked', true)
            if (!employeeSelectedIds.includes(this.list[i].id)) {//去除已经选择的人员
               this.employee_selected_list.push(this.list[i]);
            }
          }
        });
      } else {
        this.employee_selected_list = [];
        this.employee_selected = [];
        for (let i in this.list) {
          this.$set(this.list[i], 'checked', false);
        }
      }
    },
    back() {
      this.pid = this.pid_list[this.pid_list.length - 1];
      this.pid_list.splice(this.pid_list.length - 1);
      this.pid_list_arr.splice(this.pid_list_arr.length - 1);
      this.get_user_list();
    },
    back_by_index(index) {
      if (index == this.pid_list.length) {
        return false;
      }
      this.pid = this.pid_list[index];
      this.pid_list.splice(index, 100);
      this.pid_list_arr.splice(index, 100);
      this.get_user_list();
    },
    show_child(item) {
      this.pid_list.push(this.pid);
      this.pid_list_arr.push(item);
      this.pid = item.id;
      this.get_user_list();
    },
    employee_cancel(item) {
      this.checked=false;
      this.employee_selected.splice(this.employee_selected.indexOf(item.id), 1);
      let delete_index = -1;
      for (let i in this.employee_selected_list) {
        if (this.employee_selected.indexOf(this.employee_selected_list[i].id) < 0) {
          delete_index = i;
        }
      }
      if (delete_index >= 0) {
        for (let i in this.list) {
          if (this.list[i].id == item.id) {
            this.$set(this.list[i], 'checked', false);
          }
        }
        for (let i in this.employee_selected_list) {
          if (this.employee_selected_list[i].id == item.id) {
            this.employee_selected_list.splice(i, 1);
          }
        }
      }
    },
    dept_cancel(item) {
      this.checked = false;
      this.dept_selected.splice(this.dept_selected.indexOf(item.dept_id), 1);
      let delete_index = -1;
      for (let i in this.dept_selected_list) {
        if (this.dept_selected.indexOf(this.dept_selected_list[i].dept_id) < 0) {
          delete_index = i;
        }
      }
      if (delete_index >= 0) {
        this.dept_selected_list.splice(delete_index, 1);
        for (let i in this.dept_list) {
          if (this.dept_list[i].id == item.dept_id) {
            this.$set(this.dept_list[i], 'checked', false);
          }
        }
      }
    },
    select_employee(item) {
      if (item.checked) {
        item.checked = false;
        this.employee_cancel(item);
        this.$emit('confirms', '');
      } else {
        if (!this.multi) {
          this.employee_selected = [];
          this.employee_selected_list = [];
          for (let i in this.list) {
            this.$set(this.list[i], 'checked', false);
          }
        }
        if (this.max > 0 && this.employee_selected.length == this.max && this.multi) {
          this.$toast('最多只能选择' + this.max + '人');
          return false;
        }
        this.employee_selected.push(item.id);
        this.employee_selected_list.push({ id: item.id, name: item.name, img_url: item.img_url });
        item.checked = true;
        this.$emit('confirms', this.employee_selected_list);
      }
    },
    select_dept(item) {
      if (!this.can_select_dept) {
        this.show_child(item);
        return false;
      }
      if (item.checked) {
        item.checked = false;
        this.dept_cancel(item);
      } else {
        if (!this.dept_multi) {
          this.dept_selected = [];
          this.dept_selected_list = [];
          for (let i in this.dept_list) {
            this.$set(this.dept_list[i], 'checked', false);
          }
        }
        this.dept_selected.push(item.id);
        this.dept_selected_list.push({ dept_id: item.id, dept_name: item.name, avatar: 'static/images/e66f.jpg' });
        item.checked = true;
      }
    },
    clear_data() {
      this.checked = false;
      this.employee_selected = [];
      this.employee_selected_list = [];
      this.dept_selected = [];
      this.dept_selected_list = [];
      for (let i in this.list) {
        this.$set(this.list[i], 'checked', false);
      }
      for (let i in this.dept_list) {
        this.$set(this.dept_list[i], 'checked', false);
      }
    },
    close() {
      this.$emit('cancel');
      if (this.close_clear_data) {
        this.employee_selected = [];
        this.employee_selected_list = [];
        this.dept_selected = [];
        this.dept_selected_list = [];
        for (let i in this.list) {
          this.$set(this.list[i], 'checked', false);
        }
        for (let i in this.dept_list) {
          this.$set(this.dept_list[i], 'checked', false);
        }
      }
    },
    confirm() {
      this.$emit('confirm', {
        employee: this.employee_selected_list,
        dept: this.dept_selected_list
      });
      this.close();
    },
    get_dept_list() {
      this.$http('get', '/api/department/tree','').then(res => {
        this.dept_list =this.getTreeData(res.data.data.list);
      });
    },
    getTreeData(data) {
    		for (var i = 0; i < data.length; i++) {
    			if (data[i].children.length < 1) {
    				// children若为空数组，则将children设为undefined
    				data[i].children = undefined;
    			} else {
    				// children若不为空数组，则继续 递归调用 本方法
    				this.getTreeData(data[i].children);
    			}
    		}
    		return data;
    },

    // 默认选择中的人勾上
    parse_list (data) {
      this.list = []
      let _list = []
      data.map((item)=>{
      	 item['checked'] = false;
      	 for(var i in this.employee_selected_list){//判断传进来的员工是否是员工集合里的，是就设为已点击状态
      	   if(this.employee_selected_list[i].id==item.id){
      		 item['checked'] = true;
      	   }
      	 }
         if (item.img_url == '') {
           item.img_url = 'static/images/head_default.png'
         }
      });
      this.searchBox = data;
      this.list = data;
    },
    get_user_list() {
      this.table_loading = true;
      let params = {
        dept_id: this.pid,
        keywords: this.keyword,
        page: 0,
        page_size: 2000,
        is_official: 1
      }
      this.list = [];
      this.$http('get', '/api/employee/index', params).then(res => {
          let list = this.filtration(res.data.data.list);
          // 当有指定显示列表时
          if (this.user_employee_list) {
            var employee_list = this.employee_list
            var userData = []
            list.map((item) => { // 列表数据是否是自己的管理范围
              employee_list.map((item2) => {
                if (item.id == item2.id) {
                  userData.push(item)
                }
              })
            })
            this.parse_list(userData)
          } else { // 没有指定人员列表
            this.parse_list(list)
          }
        }).finally(()=>{
          this.table_loading = false;
        })
    },
    // 过滤各种条件：如：自己，创始人，只显示管理者等。。。
    filtration (data) {
      var list = data
      // 去除已经离职的人
      list.forEach((item, index) => {
          if (item.status == 2) {
            list.splice(index, 1)
          }
      })
      var managerList = []// 管理者列表
      // 只显示管理者
      if (this.is_manager_only) {
        var isManager=false;
        list.map((item) => {
          item.employee_detail.role_list.map((item2) => {
            if (item2.name == 'creator' || item2.name == 'point_manager' || item2.name == 'dept_manager' || item2.name == 'admin') {
              isManager=true;
            }
          })
          if(isManager){ managerList.push(item)}
        })
        list = managerList
      }
      // 过滤自己
      if (!this.include_self) {
        const currUserId = this.$store.getters.user_info.id;
        for (let i = 0; i < list.length; i++) {
          if (list[i].id == currUserId) {
            list.splice(i, 1);
            i--
          }
        }
      }
      // 过滤创始人
      list.forEach((item, index) => {
        if (this.is_filtration_creator) {
          if (item.is_creator == 1) {
            list.splice(index, 1)
          }
        }
      })
      //过滤指定人员[]
      list.forEach((item, index) => {
        if (this.employee_not_select.length>0) {
          if (this.employee_not_select.indexOf(item.id) >= 0) {
            list.splice(index, 1);
          }
        }
      })
      return list
    }
  },
  mounted() {
  },
  created() {
    setTimeout(() => {
      if (this.$route.query.pid) {
        this.pid = this.$route.query.pid;
      }
      this.get_user_list(function() {});
      this.get_dept_list();
    }, 200);
  }
};
</script>

<style scoped>
.employee_selector_box {
  width: 600px;
  padding: 20px;
  box-sizing: border-box;
  margin: 0 auto;
}

/* 搜索框 */
.employee_selector_box .search {
  margin: 0 auto;
  width: 80%;
}

.employee_selector_box .search-box button {
  display: inline-block;
  vertical-align: middle;
  margin-left: 10px;
  width: auto;
  padding: 0;
  background: none;
  border-radius: 0px;
  border: none;
}
/* /搜索框 */

/* 左边框 */
.employee_selector_box .choose_left {
  padding: 8px 10px 8px 10px;
}

.employee_selector_box .choose_left .employee_cell {
  border-bottom: 1px #f8f8f8 solid;
}

.employee_selector_box .choose_left .employee_cell_a .employee_cell {
  border-bottom: none;
}

.employee_selector_box .choose_left .employee_checkbox {
  padding-left: 8px;
}

.employee_selector_box .choose_left .employee_img_url {
  padding-left: 8px;
}

.employee_selector_box .choose_left .employee_name {
  padding-left: 8px;
}

.employee_selector_box ::v-deep .el-scrollbar__thumb {
  width: 2px;
  margin: 15px 0 0 6px;
  background: #409eff;
}

/* 左边框 */

/* 右边距 */
.employee_selector_box .option-box {
  padding: 14px 0;
}

.employee_selector_box .option-box button {
  margin-right: 16px;
}

.employee_selector_box .choose_right {
  padding: 8px 10px;
}

.employee_selector_box .choose_right .employee_delete .el-button {
  transform: scale(0.5);
  background: #c0c4cc;
}

.employee_selector_box .choose_right .employee_delete .el-button /deep/ .el-icon-close {
  color: #fff;
}

.employee_selector_box .choose_right .employee_delete .el-button:active {
  background: #409eff;
}

.employee_selector_box .choose_right .employee_delete .el-button:active /deep/ .el-icon-close {
  color: #fff;
}

.employee_selector_box .choose_right .employee_cell .employee_name {
  padding-left: 8px;
}

.employee_selector_box .choose_right .employee_cell .employee_img_url {
  padding-left: 8px;
}

/* 右边距 */

.employee_selector_box /deep/ .employee_cell {
  padding: 8px 0;
}

.employee_selector_box /deep/ .employee_cell:hover {
  background: #ecf5ff;
}

.employee_cell {
  display: -webkit-inline-box;
  cursor: pointer;
  width: 100%;
  color: #606266;
  padding: 8px 0;
  background-color: transparent;
}

.employee_cell .employee_cell_clear {
  clear: both;
}

.employee_cell .employee_img_url {
  display: table-cell;
  vertical-align: middle;
  width: 30px;
  padding-left: 0px;
}

.employee_cell .employee_img_url img {
  width: 24px;
  height: 24px;
  border-radius: 50%;
}

.employee_cell .employee_checkbox {
  display: table-cell;
  vertical-align: middle;
  width: 30px;
  text-align: center;
}

.employee_cell .employee_name {
  display: table-cell;
  vertical-align: middle;
  color: #606266;
}

.employee_delete {
  display: table-cell;
  text-align: right;
  padding-right: 0px;
}

.employee_cell_a {
  display: block;
}

.employee_cell_a:hover {
  background-color: #ecf5ff;
  border-radius: 4px;
}

.dept_child_cell {
  display: table-cell;
  vertical-align: middle;
}

.dept_child_cell span {
  float: right;
  padding-right: 8px;
}

.dept_child_cell span:hover {
  color: #1c1c1c;
}

.dept_child_cell span:active {
  color: #1c1c1c;
}

.scroller-box {
  height: 440px;
  padding-right: 0px !important;
  background-color: #fdfdfd;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
}
/* .scroller-box.one{
    height: 440px;
  } */

.col-line {
  position: relative;
  height: 400px;
}

.col-line:before {
  content: ' ';
  width: 1px;
  height: 400px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 50%;
  background-color: #eee;
}

.search-box {
  background-color: #fff;
  padding: 14px 5px;
  border-bottom: 1px solid #eee;
  margin: 0 -5px;
}

.option-box {
  padding: 5px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  margin: 0 -5px;
  text-align: right;
}
.child_btn {
  color: #409eff;
}
.scrollbarHeight1 {
  height: 310px;
}
.scrollbarHeight2 {
  height: 350px;
}
</style>
