<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-02-08 10:27:21
 * @LastEditors: 无尘
 * @LastEditTime: 2020-08-26 09:57:22
 -->
<!--
  选择门店分组组件：
  <gic-select-group-mult
  :selectData="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 v-if="false" placement="bottom" style="min-width: 357px" v-model="departmentVisible">
    <div class="select-search">
      <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" clearable :data="groupData" :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, data }">
          <span :class="['font-14 p-r-10 iconfont-hb3', 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 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.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: 'gic-select-group',
  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) : []
    };
  },

  methods: {
    filterNode(value, data) {
      if (!value || !data.label) 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.storeGroupId);
      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);
      that.$emit('checkGroupIds', that.$refs.groupTree.getCheckedNodes());
    },

    /**
     * 处理排序
     */
    async handleSort(item) {
      const that = this;
      for (let i = 0; i < item.children.length; i++) {
        item.children.sort(function(a, b) {
          return a.storeGroupSort - b.storeGroupSort;
        });
        if (item.children[i].length) {
          await that.handleSort(item.children[i]);
        }
      }
    },

    /**
     * 简单数组-->父子数组对象
     */
    async treeData(data) {
      // const that = this;
      let tree = data.filter(father => {
        //循环所有项
        let branchArr = data.filter(child => {
          return father.storeGroupId == child.parentGroupId; //返回每一项的子级数组
        });
        if (branchArr.length > 0) {
          father.children = branchArr; //如果存在子级，则给父级添加一个children属性，并赋值
        }
        return father.parentGroupId == 0; //返回第一层
      });
      // 排序
      if (tree.length) {
        tree.sort(function(a, b) {
          return a.storeGroupSort - b.storeGroupSort;
        });
      }
      /* for (let i = 0; i < tree[0].children.length; i++) {
            if (tree[0].children[i].lenth) {
              await that.handleSort(tree[0].children[i]);
            }
          } */
      tree.forEach(function(ele, index) {
        if (!!ele.children && ele.children.length) {
          ele.children.sort(function(a, b) {
            return a.storeGroupSort - b.storeGroupSort;
          });
        }
      });
      return tree;
    },

    /**
     * 获取门店分组
     */
    async getGroup() {
      const that = this;
      let para = {
        enterpriseId: that.brandId
      };
      getRequest('/haoban-manage3-web/gic-department-list', para)
        .then(async res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result && !!resData.result.length) {
              resData.result.forEach(ele => {
                ele.label = ele.storeGroupName;
                ele.departmentName = ele.storeGroupName;
              });
              const data = await that.treeData(resData.result);
              that.$nextTick(() => {
                that.groupData = JSON.parse(JSON.stringify(data)) || [];
                that.groupDataCopy = JSON.parse(JSON.stringify(that.groupData)) || [];
              });
              that.$forceUpdate();
            }
            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;
      } 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();
      }
    }
  },
  mounted() {
    console.log('此组件废弃');
    return;
    const that = this;
    // 对否有默认选中数据
    if (!!that.selectData.length) {
      that.groupIds = that.selectData;
    } else {
      that.groupIds = [];
    }
    that.getGroup();
  }
};
</script>
<style lang="scss" scoped>
.depart-item-content {
  width: 213px;
  height: 32px;
  overflow: hidden;
  white-space: nowrap;
  border-radius: 2px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  box-sizing: border-box;
}

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

.item-cell-select {
  >>> .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>
