<!--
 * @Descripttion: 添加管理员-选择管理员
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-07-21 10:10:57
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-15 09:58:19
 -->
<!--
  <select-admin :select-admin="selectAdmin" @checkAdmins="checkAdmins"></select-admin>
  import selectAdmin from '@/components/set/select-admin.vue';
  -->
<template>
  <el-dialog width="418px" title="添加管理员" :visible.sync="setVisible" append-to-body :before-close="handleClose">
    <div class="bind-store-body">
      <div class="font-14 color-606266">已选择 <span class="color-303133">{{ totalNum || '0'}}</span> 人</div>
      <div class="select-search m-t-10">
        <el-input placeholder="请输入成员名称" maxlength="50" clearable v-model="searchSelect" @keyup.native="value => toInput(value, searchSelect)" @clear="clearSearch"> <i slot="prefix" class="el-input__icon el-icon-search"></i> </el-input>
      </div>
      <div class="select-tree-wrap auth-select-tree m-t-20">
        <el-tree v-show="searchSelect == ''" ref="groupTree" :load="loadNode" lazy  :data="groupData" :props="defaultProps" >
          <span class="custom-tree-node"  slot-scope="{ node, data }">
            <span><el-checkbox v-if="data.levelType == 1"  :disabled="data.bindFlag == 1" v-model="data.checked" @change="changeItem($event,data)"></el-checkbox><span class="font-14 color-606266 p-l-10">{{ node.label }}</span></span><span v-if="data.bindFlag == 1" class="font-12 color-909399 p-l-10">已选中</span>
          </span>
        </el-tree>
        <div v-show="searchSelect" class="el-select-dropdown__wrap el-scrollbar__wrap" style="overflow: auto;">
          <el-checkbox-group v-model="checkedList" @change="handleStoresChange" :max="50">
            <ul class="el-scrollbar__view el-select-dropdown__list">
              <li :class="['el-select-dropdown__item flex flex-space-between', item.select ? 'selected hover' : '']" v-for="item in searchList" :key="item.staffId">
                <el-checkbox :disabled="item.bindFlag == 1" :label="item.staffId" >{{ item.staffName }}</el-checkbox><span v-if="item.bindFlag == 1" class="font-12 color-909399 p-l-10">已选中</span>
              </li>
              <li v-if="!searchList.length" class="text-center"><span>暂无数据</span></li>
            </ul>
          </el-checkbox-group>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {  _debounce } from '@/common/js/public';
import fetch from '@/api/edit-admin.js';
const { getAdminList, getSearchAdminList } = fetch;
import showMsg from '@/common/js/showmsg';
export default {
  name: 'SelectAdmin',
  props: {
    showAdminFlag: {
      type: Boolean,
      default: false,
    },
    selectAdmin: {
      type: [ Object, Array ],
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',
      searchSelect: '', // 搜索字段
      groupData: [],
      groupDataCopy: [],
      setVisible: false,
      defaultProps: {
        children: 'children',
        label: 'label',
        isLeaf: 'leaf'
      },
      totalNum: '0',
      totalIds: [],
      searchList: [],
      checkedList: [], // 搜索后选中的数据集合
      checkedPeople: [], // tree 选择的所有管理员
      totalArr: [] // 选择的所有人
    };
  },
  mounted() {
    const that = this;
    that.totalNum = that.selectAdmin.length;
    that.totalIds = that.selectAdmin.map(ele => ele.levelId) || [];
    that.checkedList = that.selectAdmin.map(ele => ele.levelId) || [];
    that.setVisible = that.showAdminFlag;
    that.totalArr = JSON.parse(JSON.stringify(that.selectAdmin)) || []; // 总的
    if (that.$route.query.staffId) {
      return false;
    }
    that.getStaff();
  },
  methods: {
    /**
     * @description: 单个选择
     * @param {String} val
     * @param {Object} item
     * @author: 无尘
     */
    async changeItem(val, item) {
      const that = this;
      // 如果不勾选了，需要设置搜索数据中已选删除
      if (!val && that.checkedList.indexOf(item.levelId)) {
        that.checkedList.splice(that.checkedList.indexOf(item.levelId), 1);
      }
      // 需要先获取已选人员(有些问题，获取的时候数据没有)
      that.checkedPeople = [];
      await that.getCheckData();
      // 每次选择或者不选的时候，合并搜索和树中选择数据，即使如果不选中，数据已经加载了，
      that.totalIds = [ ...new Set([ ...that.checkedList, ...that.checkedPeople.map(ele => ele.levelId) ]) ] || [];
      that.checkedList = [ ...new Set([ ...that.checkedList, ...that.checkedPeople.map(ele => ele.levelId) ]) ] || [];
      // 最后记得过滤重复
      let arr = JSON.parse(JSON.stringify(that.totalArr));
      arr = arr.concat(that.checkedPeople);
      await that.delDubbleData(arr);
      if (!val && that.totalArr.map(ele => ele.levelId).indexOf(item.levelId) != -1) {
        let newArr = [];
        that.totalArr.forEach(ele => {
          if (ele.levelId != item.levelId) {
            newArr.push(ele);
          }
        });
        that.totalArr = JSON.parse(JSON.stringify(newArr));
      }
      that.totalNum = that.totalArr.length;
    },
    /**
     * @description: 数组对象去重
     * @param {Array} arr
     * @author: 无尘
     */
    delDubbleData(arr) {
      const that = this;
      let hash = {};
      // 去重数组对象
      arr = arr.reduce(function(item, next) {
        hash[next.levelId] ? '' : (hash[next.levelId] = true && item.push(next));
        return item;
      }, []);
      that.totalArr = JSON.parse(JSON.stringify(arr));
    },
    /**
     * @description: 关闭弹窗
     * @param {Function} done
     * @author: 无尘
     */
    handleClose(done) {
      const that = this;
      done();
      that.$emit('checkAdmins', 'close');
    },
    cancel() {
      const that = this;
      that.$emit('checkAdmins', 'close');
    },
    /**
     * @description: 确定
     * @author: 无尘
     */
    async submitForm() {
      const that = this;
      if (!that.totalArr.length) {
        showMsg.showmsg('请选择管理员', 'warning');
        return false;
      }
      // 只选择了搜索数据，可是搜索数据中,树中数据未加载
      // 选择了搜索数据，也选择了树中已有数据，可是搜索数据中有树中未加载完全数据
      that.$emit('checkAdmins', JSON.parse(JSON.stringify(that.totalArr)));
    },
    /**
     * @description: 搜索选择的变化
     * @param {Array} value
     * @author: 无尘
     */
    async handleStoresChange(value) {
      const that = this;
      let arr = [];
      that.searchList.forEach(ele => {
        if (value.includes(ele.levelId)) {
          arr.push(ele);
        }
      });
      that.totalNum = value.length;
      that.totalIds = value;
      // 数据去重
      let arrMiddleData = JSON.parse(JSON.stringify(that.totalArr));
      arrMiddleData = arrMiddleData.concat(arr);
      await that.delDubbleData(arrMiddleData);
      // 设置树形数据中的人员选中和不选中
      for (let index = 0; index < that.groupData.length; index++) {
        const ele = that.groupData[index];
        if (value.includes(ele.levelId)) {
          ele.checked = true;
        }else {
          ele.checked = false;
        }
        if (!!ele.children && !!ele.children.length) {
          await that.setChildCheck(ele, value);
        }
      }
      // 重新设置已选数据
      that.checkedPeople = [];
      await that.getCheckData();
      // 还需要设置已有的数据选择上
      // 还需要未加载的数据选择上
    },
    async setChildCheck(obj, value) {
      const that = this;
      for (let index = 0; index < obj.children.length; index++) {
        const ele = obj.children[index];
        if (value.includes(ele.levelId)) {
          ele.checked = true;
        }else {
          ele.checked = false;
        }
        if (!!ele.children && !!ele.children.length) {
          await that.setChildCheck(ele, value);
        }
      }
    },
    /**
     * @description: 获取已选择的人员
     * @author: 无尘
     */
    async getCheckData() {
      const that = this;
      for (let index = 0; index < that.groupData.length; index++) {
        const ele = that.groupData[index];
        if (ele.checked) {
          that.checkedPeople.push(ele);
        }
        if (!!ele.children && !!ele.children.length) {
          await that.getChildCheck(ele.children);
        }
      }
    },
    async getChildCheck(arr) {
      const that = this;
      for (let index = 0; index < arr.length; index++) {
        const ele = arr[index];
        if (ele.checked) {
          that.checkedPeople.push(ele);
        }
        if (!!ele.children && !!ele.children.length) {
          await that.getChildCheck(ele.children);
        }
      }
    },
    /**
     * @description: 加载更多
     * @param {Object} node
     * @param {functional} resolve
     * @author: 无尘
     */
    async loadNode(node, resolve) {
      // console.log(node, resolve);
      const that = this;
      if (that.$route.query.staffId) {
        return false;
      }
      if (node.level === 0) {
        return resolve(that.getStaff());
      } else {
        // 判断是不是叶子结点
        await that.getStaff(node, node.data, resolve);
      }
    },
    /**
     * @description: 搜索获取人员
     * @param {String} data
     * @author: 无尘
     */
    getSearchData(data) {
      const that = this;
      const para = {
        staffName: data,
        wxEnterpriseId: that.wxEnterpriseId
      };
      getSearchAdminList(para)
        .then(res => {
          // 因为数据字段不一致，所以加了字段
          if (res.result && res.result.length) {
            res.result.forEach(ele => {
              ele.levelId = ele.staffId;
              ele.levelName = ele.staffName;
            });
          }
          that.searchList = res.result || [];
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 输入
     * @param {Object} e
     * @param {String} value
     * @author: 无尘
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      if (String(that.searchSelect).trim() == '') {
        return false;
      }
      that.getSearchData(that.searchSelect);
    }, 200),
    /**
     * @description: 清空
     * @returns {Boolean}
     * @author: 无尘
     */
    clearSearch() {
      return false;
    },
    /**
     * @description: 获取人
     * @param {Object} node
     * @param {Object} data
     * @param {Function} resolve
     * @author: 无尘
     */
    getStaff(node, data, resolve) {
      const that = this;
      const para = {
        departmentId: !!data ? data.levelId : '',
        wxEnterpriseId: that.wxEnterpriseId
      };
      /* if (node && !data.hasSonNode ) {
        resolve([]);
        return false;
      } */
      getAdminList(para)
        .then(res => {
          if (!!res.result && res.result.length) {
            res.result.forEach(ele => {
              ele.children = [];
              ele.checked = that.totalIds.includes(ele.levelId) ? true : false; // 还需要根据已选数据设置
              ele.label = ele.levelName;
              ele.leaf = ele.levelType == 1 ? true : false;
            });
          }
          if (node) {
            resolve(res.result);
            if (!data.children) {
              that.$set(data, 'children', []);
            }
            data.children = res.result || [];
            that.$forceUpdate();
            return false;
          }
          that.groupData = res.result || [];
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 回显设置树形数据中的人员选中和不选中
     * @param {String} value
     * @author: 无尘
     */
    async setSelectData(value) {
      const that = this;
      for (let index = 0; index < that.groupData.length; index++) {
        const ele = that.groupData[index];
        if (value.includes(ele.levelId)) {
          ele.checked = true;
        }else {
          ele.checked = false;
        }
        if (!!ele.children && !!ele.children.length) {
          await that.setChildCheck(ele, value);
        }
      }
    }
  },
  watch: {
    showAdminFlag(val) {
      this.setVisible = val;
    },
    selectAdmin(val) {
      const that = this;
      that.totalNum = val.length;
      that.totalIds = val.map(ele => ele.levelId) || [];
      that.checkedList = val.map(ele => ele.levelId) || [];
      that.totalArr = JSON.parse(JSON.stringify(val)) || []; // 总的
      that.setSelectData(that.checkedList);
    }
  }
};
</script>
<style lang="less" scoped>
  .bind-store-body {
    width: 331px;
    padding: 10px;
    margin: 0 auto ;
    border: 1px solid #e4e7ed;
    .w-215 {
      width: 215px;
    }

    .w-115 {
      width: 115px;
    }

    .select-tree-wrap {
      height: 323px;
      overflow-y: auto;
      .el-tree {
        width: 309px;
        height: 323px;
        overflow-x: auto;
        .custom-tree-node {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 14px;
          padding-right: 8px;
        }
      }
      .el-select-dropdown__wrap {
        max-height: 343px;
      }
      .el-checkbox-group {
        overflow-x: auto;
        max-height: 306px;
        ul {
          height: 100%;
          li {
            overflow: unset;
            text-overflow: unset;
          }
        }
      }
    }
  }
</style>
