<!--
 * @Descripttion: 选择门店分组组件
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-11-08 10:27:21
 * @LastEditors: 无尘
 * @LastEditTime: 2020-11-24 17:56:08
 -->
<!--
  <gic-select-group-mult
  :select-data="selectData"
  @checkGroupIds="checkGroupIds">
  </gic-select-group-mult>

  import gicSelectGroupMult from '@/components/common/gic-select-group-mult.vue';

  checkGroupIds: function(nodes) {
    const that = this;
    that.conditionObj.groupIds = nodes;
  },
 -->
<template>
  <el-popover placement="bottom" v-model="departmentVisible">
    <div class="font-12 color-909399">最终选择范围是根据选择范围和管理员管辖范围内的相同分组或门店。</div>
    <div class="select-search m-t-10">
      <el-input placeholder="请输入内容" maxlength="50" 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">
      <!--:load="loadNode"-->
      <el-tree :filter-node-method="filterNode" :data="groupData" check-strictly :default-checked-keys="checkedKeys" node-key="storeGroupId" ref="groupTree" show-checkbox default-expand-all :props="defaultProps" :expand-on-click-node="false" @check="checkGroup">
        <span class="custom-tree-node" slot-scope="{ node }">
          <span :class="['font-14 p-r-10 iconfont iconqiye-tianchong', '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 style="display:block">
              <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.storeGroupName }}</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 fetch from '@/api/merchant-auth.js';
const { getGroupList } = fetch;
import { _debounce } from '@/common/js/public';
export default {
  name: 'GicSelectGroupMult',
  props: {
    width: {
      type: String,
      default() {
        return '357px';
      }
    },
    selectData: {
      type: [ Object, Array ],
      default() {
        return [];
      }
    },
    brandId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      projectName: '', // 当前项目名
      enterpriseId: this.brandId,
      searchSelect: '', // 搜索字段
      departmentVisible: false,
      groupIds: [],
      groupData: [],
      groupDataCopy: [],
      defaultProps: {
        children: 'children',
        label: 'storeGroupName'
      },
      checkedKeys: this.selectData.length ? this.selectData.map(ele => ele.departmentId) : []
    };
  },
  mounted() {
    const that = this;
    // 对否有默认选中数据
    if (!!that.selectData.length) {
      that.groupIds = that.selectData;
    } else {
      that.groupIds = [];
    }
    that.getGroup();
  },
  methods: {
    /**
     * @description: 过滤
     * @param {String} value
     * @param {Object} data
     * @return {Boolean}
     * @author: 无尘
     */
    filterNode(value, data) {
      if (!value || !data.label) return true;
      return data.label.indexOf(value) !== -1;
    },

    /**
     * @description: 输入
     * @param {Object} e
     * @param {String} value
     * @returns {Boolean}
     * @author: 无尘
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      // that.getGroup();
      if (!that.groupDataCopy.length) {
        return false;
      }
    }, 500),
    /**
     * @description: 清空
     * @author: 无尘
     */
    clearSearch() {
      const that = this;
      that.groupData = JSON.parse(JSON.stringify(that.groupDataCopy));
    },

    /**
     * @description: 删除
     * @param {Number} index
     * @param {Array} arr
     * @author: 无尘
     */
    delDepart(index, arr) {
      const that = this;
      arr.splice(index, 1);
      const keys = arr.map(ele => ele.storeGroupId);
      that.setCheckedKeys(keys);
    },

    /**
     * @description: 选择 tree 节点,获取选择节点信息
     * @author: 无尘
     */
    checkGroup: function() {
      const that = this;
      that.groupIds = that.$refs.groupTree.getCheckedNodes();
      that.$emit('checkGroupIds', that.$refs.groupTree.getCheckedNodes());
    },
    /**
     * @description: 设置 tree
     * @param {Array} keys
     * @author: 无尘
     */
    setCheckedKeys(keys) {
      const that = this;
      that.$refs.groupTree.setCheckedKeys(keys);
      that.$emit('checkGroupIds', that.$refs.groupTree.getCheckedNodes());
    },
    /**
     * @description: 简单数组-->父子数组对象
     * @param {Array} data
     * @author: 无尘
     */
    async treeData(data) {
      let tree = data.filter(father => {
        // 循环所有项
        let branchArr = data.filter(child => {
          return father.storeGroupId == child.parentId; // 返回每一项的子级数组
        });
        if (branchArr.length > 0) {
          father.children = branchArr; // 如果存在子级，则给父级添加一个children属性，并赋值
        }else {
          father.children = [];
        }
        return father.parentId == 0; // 返回第一层
      });
      return tree;
    },

    /**
     * @description: 获取门店分组
     * @author: 无尘
     */
    async getGroup() {
      const that = this;
      let para = {
        enterpriseId: that.brandId
      };
      getGroupList(para)
        .then(async res => {
          if (!!res.result && !!res.result.length) {
            res.result.forEach(ele => {
              ele.label = ele.storeGroupName;
            });
            const data = await that.treeData(res.result);
            that.$nextTick(() => {
              that.groupData = JSON.parse(JSON.stringify(data)) || [];
              that.groupDataCopy = JSON.parse(JSON.stringify(that.groupData)) || [];
            });
            that.$forceUpdate();
          }
        })
        .catch(function(error) {

        });
    }
  },
  watch: {
    selectData: function(newData, oldData) {
      let that = this;
      if (!!newData.length) {
        that.groupIds = newData;
      } else {
        that.groupIds = [];
      }
    },
    searchSelect(val) {
      this.$refs.groupTree.filter(val);
    },
    brandId(val) {
      const that = this;
      if (val) {
        that.searchSelect = '';
        that.groupIds = [];
        that.groupData = [];
        that.groupDataCopy = [];
        that.getGroup();
      }
    }
  }
};
</script>
<style lang="less" scoped>
.depart-item-content {
  width: 213px;
  height: 32px;
  overflow: hidden;
  white-space: nowrap;
  border-radius: 2px;
  border: 1px solid #c4c6cf;
  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;
  }
  .el-select {
    .el-tag {
      border-radius: 2px;
      border: 1px solid rgba(220, 223, 230, 1);
      background-color: #fff;
      .el-tag__close {
        top: 1px;
        color: #909399;
        &:hover {
          background-color: transparent;
        }
      }
    }
  }
}
</style>
