<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-02-08 10:27:21
 * @LastEditors: 无尘
 * @LastEditTime: 2020-03-05 09:48:54
 -->
<!--
  添加成员选择部门组件：
  <select-department
  :selectData="selectData"
  @checkGroupIds="checkGroupIds">
  </select-department>

  import selectDepartment from '@/components/company/select-department.vue';

  checkGroupIds: function(nodes) {
    const that = this;
    that.conditionObj.groupIds = nodes;
  },
 -->
<template>
  <el-popover placement="bottom" style="min-width: 357px" v-model="departmentVisible">
    <div class="select-search">
      <el-input placeholder="请输入内容" v-model="searchSelect" style="width: 100%;" @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 m-t-10">
      <el-tree :filter-node-method="filterNode" clearable :data="groupData" :load="loadNode" :default-checked-keys="checkedKeys" node-key="departmentId" ref="groupTree" check-strictly lazy show-checkbox default-expand-all :props="defaultProps" :expand-on-click-node="false" @check="checkGroup">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span :class="['font-14 p-r-10 iconfont', data.isStore == 1 ? 'icondianpu-kuai' : 'iconqiye-tianchong', data.bindFlag == 1 ? 'color-2f54eb' : 'color-dedfe6']"></span><span class="font-14 color-606266">{{ node.label }}</span>
        </span>
      </el-tree>
    </div>
    <div class="flex-column item-cell-select inline-block " slot="reference">
      <div class="depart-item-wrap">
        <div :style="{ width: width }" class="el-select el-select--large depart-item-content">
          <span class="font-14 color-c0c4cc p-l-10" style="display: inline-block;line-height: 32px;color: #c0c4cc;" v-if="!groupIds.length">请选择部门</span>
          <div class="el-select__tags" style="max-width: 348px;">
            <span>
              <template v-for="(item, index) in groupIds">
                <span class="el-tag el-tag--info el-tag--small" :key="index">
                  <span class="el-select__tags-text">{{ item.departmentName }}</span>
                  <i class="el-tag__close el-icon-close" @click.stop="delDepart(index, groupIds)"></i>
                </span>
              </template>
            </span>
          </div>
        </div>
      </div>
    </div>
  </el-popover>
</template>
<script>
import { getRequest } from '@/api/api';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
export default {
  name: 'select-department',
  props: {
    width: {
      type: String,
      default() {
        return '357px';
      }
    },

    selectData: {
      type: [Object, Array],
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      projectName: '', // 当前项目名
      searchSelect: '', // 搜索字段
      departmentVisible: false,
      groupIds: [],
      groupData: [],
      groupDataCopy: [],
      defaultProps: {
        children: 'children',
        label: 'departmentName'
      },
      checkedKeys: this.selectData.length ? this.selectData.map(ele => ele.departmentId) : []
    };
  },

  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /**
     * 加载更多
     */
    async loadNode(node, resolve) {
      // console.log(node, resolve);
      const that = this;
      if (node.level === 0) {
        return resolve(that.getGroup());
      } else {
        await that.getGroup(node, node.data, resolve);
      }
    },
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      // that.getGroup();
      if (!that.groupDataCopy.length) {
        return false;
      }
    }, 500),
    /**
     * 清空
     */
    clearSearch() {
      const that = this;
      that.groupData = JSON.parse(JSON.stringify(that.groupDataCopy));
    },

    /**
     * 删除
     */
    delDepart(index, arr) {
      const that = this;
      arr.splice(index, 1);
      const keys = arr.map(ele => ele.departmentId);
      that.setCheckedKeys(keys);
    },

    /**
     *  选择 tree 节点,获取选择节点信息
     */
    checkGroup: function(e) {
      const that = this;
      that.groupIds = that.$refs.groupTree.getCheckedNodes();
      that.$emit('checkGroupIds', that.$refs.groupTree.getCheckedNodes());
    },
    /**
     * 设置 tree
     */
    setCheckedKeys(keys) {
      const that = this;
      that.$refs.groupTree.setCheckedKeys(keys);
    },

    /**
     * 简单数组-->父子数组对象
     */
    treeData(data) {
      let tree = data.filter(father => {
        //循环所有项
        let branchArr = data.filter(child => {
          return father.groupId == child.parentId; //返回每一项的子级数组
        });
        if (branchArr.length > 0) {
          father.children = branchArr; //如果存在子级，则给父级添加一个children属性，并赋值
        }
        return father.groupId == 0; //返回第一层
      });
      return tree;
    },

    /**
     * 搜素获取门店分组
     */
    getSearchGroup(keyword) {
      let that = this;
      let para = {
        parentId: '',
        isStore: 0,
        keyword: keyword
      };
      getRequest('/haoban-manage3-web/department-list-level', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result && resData.result.length) {
              resData.result.forEach(ele => {
                ele.expand = false;
                ele.children = [];
                ele.label = ele.departmentName;
              });
            }

            that.groupData = resData.result || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取门店分组
     */
    getGroup(node, data, resolve) {
      let that = this;
      let para = {
        parentId: data ? data.departmentId : '',
        isStore: 0
      };
      getRequest('/haoban-manage3-web/department-list-level', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result && resData.result.length) {
              resData.result.forEach(ele => {
                ele.expand = false;
                ele.children = [];
                ele.label = ele.departmentName;
              });
            }
            if (node) {
              resolve(resData.result);
              if (!data.children) {
                that.$set(data, 'children', []);
              }
              data.children = resData.result || [];
              that.$forceUpdate();
              return false;
            }
            that.groupData = resData.result || [];
            // 存一份数据自己搜索
            that.groupDataCopy = JSON.parse(JSON.stringify(that.groupData));
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    selectData: function(newData, oldData) {
      let that = this;
      if (!!newData.length) {
        that.groupIds = newData;
      }
    },
    searchSelect(val) {
      this.$refs.groupTree.filter(val);
    }
  },
  mounted() {
    const that = this;
    console.log(that.selectData);
    if (!!that.selectData.length) {
      that.groupIds = that.selectData;
    }
    that.getGroup();
  }
};
</script>
<style lang="less" scoped>
.depart-item-content {
  width: 213px;
  height: 32px;
  overflow: hidden;
  white-space: nowrap;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  box-sizing: border-box;
}

.select-tree-wrap {
  max-height: 300px;
  overflow-y: auto;
}

.item-cell-select {
  /deep/ .el-select__tags {
    white-space: nowrap;
    overflow: hidden;
  }
}
</style>
