<!--
 * @Descripttion: 应用内选择门店分组
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-11-17 14:02:31
 * @LastEditors: 无尘
 * @LastEditTime: 2020-11-24 16:40:59
-->
<!--
  <app-select-group :brand-id="brandId" :store-type="storeType" :select-group="selectGroup"></app-select-group>
  import appSelectGroup from '@/components/app/app-select-group.vue';
  -->
<template>
  <div class="bind-store-body">
    <div class="select-search">
      <el-input placeholder="请输入分组名称" 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 ref="groupTree" :filter-node-method="filterNode" :data="groupData" node-key="storeGroupId" show-checkbox default-expand-all :props="defaultProps" :expand-on-click-node="false" @check="checkGroup">
        <span :id="data.storeGroupId" class="custom-tree-node"  slot-scope="{ node, data }">
          <span class="font-14 color-606266">{{ node.label }}</span>
        </span>
      </el-tree>
    </div>
  </div>
</template>
<script>
import { _debounce } from '@/common/js/public';
import fetch from '@/api/merchant-auth.js';
const { getGroupList } = fetch;
export default {
  name: 'AppSelectGroup',
  props: {
    brandId: {
      type: String,
      default: ''
    },
    storeType: {
      type: String,
      default: '2' // 1 门店绑定， 2 门店共享
    },
    selectGroup: {
      type: [ Object, Array ],
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',
      searchSelect: '', // 搜索字段
      groupData: [],
      groupDataCopy: [],
      defaultProps: {
        children: 'children',
        label: 'storeGroupName'
      }
    };
  },
  mounted() {
    const that = this;
    if (that.brandId) {
      that.getGroup();
    }
    if (that.selectGroup.length) {
      that.$nextTick(()=>{
        that.$refs.groupTree.setCheckedKeys(that.selectGroup.map(ele=>ele.storeGroupId));
      });
    }else {
      that.$nextTick(()=>{
        that.$refs.groupTree.setCheckedKeys([]);
      });
    }
  },
  methods: {
    /**
     * @description: 过滤搜索
     * @param {String} value
     * @param {Object} data
     * @returns {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;
      if (!that.groupDataCopy.length) {
        return false;
      }
    }, 200),
    /**
     * @description: 清空
     * @returns {Boolean}
     * @author: 无尘
     */
    clearSearch() {
      return false;
    },
    /**
     * @description: 选择 tree 节点,获取选择节点信息
     * @param {Object} e
     * @param {Array} checkedKeys
     * @author: 无尘
     */
    checkGroup: function(e, checkedKeys) {
      const that = this;
      // 这里还要过滤已选的数据，把非禁用的数据过滤出来
      const groups = that.$refs.groupTree.getCheckedNodes();
      if (!!groups.length) {
        that.$emit('checkGroupIds', groups);
      }else {
        that.$emit('checkGroupIds', []);
      }

    },
    /**
     * @description: 简单数组变父子关系
     * @param {Array} data
     * @return {Array}
     * @author: 无尘
     */
    treeData(data) {
      let tree = data.filter(father => {
        // 循环所有项
        let branchArr = data.filter(child => {
          return father.storeGroupId == child.parentId; // 返回每一项的子级数组
        });
        if (branchArr.length > 0) {
          father.hasSonNode = true;
          father.children = branchArr; // 如果存在子级，则给父级添加一个children属性，并赋值
        } else {
          father.children = [];
          father.hasSonNode = false;
        }
        return father.parentId == 0; // 返回第一层
      });
      return tree;
    },

    /**
     * @description: 获取门店分组
     * @author: 无尘
     */
    getGroup() {
      const that = this;
      const para = {
        type: that.storeType,
        enterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId
      };
      getGroupList(para, { headers: { sign: that.brandId } })
        .then(async res => {
          if (!!res.result && res.result.length) {
            res.result.forEach(ele => {
              ele.expand = false;
              ele.children = [];
              ele.label = ele.storeGroupName;
            });
          }
          that.groupData = await that.treeData(JSON.parse(JSON.stringify(res.result))) || [];
          // 存一份数据自己搜索
          // console.log(that.groupData)
          that.groupDataCopy = JSON.parse(JSON.stringify(res.result));

        })
        .catch(function(error) {

        });
    },
  },
  watch: {
    searchSelect(val) {
      this.$refs.groupTree.filter(val);
    },
    selectGroup(val) {
      const that = this;
      if (val.length) {
        that.$nextTick(()=>{
          that.$refs.groupTree.setCheckedKeys(val.map(ele=>ele.storeGroupId));
        });
      }else {
        that.$nextTick(()=>{
          that.$refs.groupTree.setCheckedKeys([]);
        });
      }
    },
    brandId(val) {
      const that = this;
      if (!!val) {
        that.getGroup();
      }
    }
  }

};
</script>
<style lang="less" scoped>
  .bind-store-body {
    width: 331px;
    padding: 10px;
    margin: 20px 0 0 0 ;
    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;
        }
      }
    }
  }
</style>
