<!--
 * @Descripttion: gic选择分组
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-07-21 10:10:57
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-09 15:51:24
 -->
<!--
  门店绑定-选择分组
  <store-auth-group :company-id="companyId" :store-type="storeType" :select-group="selectGroup" @checkGroupIds="checkGroupIds"></store-auth-group>
  import storeAuthGroup from '@/components/company/store-auth-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" check-strictly :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 }" @click="toShowMsg(node, data)">
          <span class="font-14 color-606266">{{ node.label }}</span><span v-if="data.bindFlag == 1&&data.auditFlag != 1" class="font-12 color-909399 p-l-10">{{ data.bindWxEnterpriseName }} 企业已授权</span><span v-if="data.auditFlag == 1" class="font-12 color-909399 p-l-10">{{ data.bindWxEnterpriseName }} 企业授权中</span>
        </span>
      </el-tree>
    </div>
  </div>
</template>
<script>
import {  _debounce } from '@/common/js/public';
import fetch from '@/api/merchant-auth.js';
const { getGroupList } = fetch;
import showMsg from '@/common/js/showmsg';
export default {
  name: 'StoreAuthGroup',
  props: {
    companyId: {
      type: String,
      default: ''
    },
    storeType: {
      type: String,
      default: '1' // 1 门店绑定， 2 门店共享
    },
    selectGroup: {
      type: [ Object, Array ],
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      searchSelect: '', // 搜索字段
      groupData: [],
      groupDataCopy: [],
      defaultProps: {
        children: 'children',
        label: 'storeGroupName'
      }
    };
  },
  mounted() {
    const that = this;
    if (that.companyId) {
      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 {Object} node
     * @param {Object} data
     * @returns {Boolean}
     * @author: 无尘
     */
    toShowMsg(node, data) {
      if (data.auditFlag == 1) {
        showMsg.showmsg(`${data.bindWxEnterpriseName} 企业授权中，无法选择！`, 'warning');
        return false;
      }
      if (data.bindFlag == 1) {
        showMsg.showmsg('当前分组已被其他企业绑定，当前企业无法选择！', 'warning');
      }
    },
    /**
     * @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() {
      // const that = this;
      return false;
      // that.groupData = JSON.parse(JSON.stringify(that.groupDataCopy));
    },
    /**
     * @description: 选择 tree 节点,获取选择节点信息
     * @param {Object} e
     * @param {Array} checkedKeys
     * @author: 无尘
     */
    checkGroup: function(e, checkedKeys) {
      const that = this;
      // 如果是共享的也要限制勾选父级子级禁用
      /*  if (that.storeType == 2) {
        that.$emit('checkGroupIds', that.$refs.groupTree.getCheckedNodes());
        return false
      } */
      if(!!e.children) {
        // 父级已被绑定，子级要红色显示（暂时去掉）
        const className = document.getElementById(e.storeGroupId).previousElementSibling.children[0].className;
        const parentNode = !!that.$refs.groupTree.getNode(e.storeGroupId) ? that.$refs.groupTree.getNode(e.storeGroupId).parent : '';

        const checkFlag = checkedKeys.checkedKeys.includes(e.storeGroupId);
        // 选择并且父级已绑定
        if (className.includes('is-checked') && !!parentNode && parentNode.data.bindFlag == 1) {
          // document.getElementById(e.storeGroupId).previousElementSibling.children[0].children[0].style.borderColor = '#f5222d';
          // document.getElementById(e.storeGroupId).previousElementSibling.children[0].children[0].style.backgroundColor = '#f5222d';
        }/* else {
          document.getElementById(e.storeGroupId).previousElementSibling.children[0].children[0].style.borderColor = '#dcdfe6';
          document.getElementById(e.storeGroupId).previousElementSibling.children[0].children[0].style.backgroundColor = '#ffffff';
        } */
        // 取消红色
        if (!checkFlag) {
          document.getElementById(e.storeGroupId).previousElementSibling.children[0].children[0].setAttribute('style', '');
        }

        that.$refs.groupTree.setChecked(e.storeGroupId, checkFlag, true);
        e.children.forEach(ele => {
          that.$refs.groupTree.setChecked(ele.storeGroupId, checkFlag, true);
          if (checkFlag) {
            ele.disabled = true;
          }else {
            ele.disabled = ele.bindFlag ? true : false;
          }
          // 递归子级禁用和选中
          if (!!ele.children && !!ele.children.length) {
            that.checkChild(ele, checkFlag);
          }
        });
      }
      // 这里还要过滤已选的数据，把非禁用的数据过滤出来
      const groups = that.$refs.groupTree.getCheckedNodes();
      if (!!groups.length) {
        let arr = [];
        groups.forEach(ele => {
          if (!ele.disabled) {
            arr.push(ele);
          }
        });
        that.$emit('checkGroupIds', arr);
      }else {
        that.$emit('checkGroupIds', []);
      }
      that.$nextTick(()=> {
        // 被禁用时的红色,去掉样式
        const nodes = document.querySelectorAll('.el-checkbox__input');
        if (!!nodes && !!nodes.length) {
          nodes.forEach(ele => {
            if (ele.className.includes('is-checked') && ele.className.includes('is-disabled')) {
              ele.children[0].setAttribute('style', '');
            }
          });
        }
      });
    },
    /**
     * @description: checkchild
     * @param {Array} arr
     * @param {Boolean} checkFlag
     * @author: 无尘
     */
    checkChild(arr, checkFlag) {
      const that = this;
      arr.children.forEach(ele => {
        that.$refs.groupTree.setChecked(ele.storeGroupId, checkFlag, true);
        if (checkFlag) {
          ele.disabled = true;
        }else {
          ele.disabled = ele.bindFlag ? true : false;
        }
        // 递归子级禁用和选中
        if (!!ele.children && !!ele.children.length) {
          that.checkChild(ele, checkFlag);
        }
      });
    },
    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: 无尘
     */
    setSelectCheck() {
      const that = this;
      const ids = that.selectGroup.map(ele=>ele.storeGroupId);
      that.groupData.forEach(ele => {
        // 如果父级选中了，设置子级禁用
        if (ids.includes(ele.storeGroupId) && !!ele.children.length) {
          that.checkChild(ele, true);
        }
        // 如果父级没有选中，查找子级，再判断父级有没有禁用
        if (!ids.includes(ele.storeGroupId)) {
          that.disableChild(ele, ids);
        }
      });
    },
    /**
     * @description: disableChild
     * @param {Array} arr
     * @param {Array} ids
     * @author: 无尘
     */
    disableChild(arr, ids) {
      const that = this;
      arr.children.forEach(ele => {
        // 如果父级选中了，设置子级禁用
        if (ids.includes(ele.storeGroupId) && !!ele.children.length) {
          that.checkChild(ele, true);
        }
        // 如果父级没有选中，查找子级，再判断父级有没有禁用
        if (!ids.includes(ele.storeGroupId) && !!ele.children.length) {
          that.disableChild(ele, ids);
        }
      });
    },
    /**
     * @description: 获取门店分组
     * @author: 无尘
     */
    getGroup() {
      const that = this;
      const para = {
        type: that.storeType,
        enterpriseId: that.companyId
      };

      getGroupList(para)
        .then(async res => {
          if (!!res.result && res.result.length) {
            res.result.forEach(ele => {
              ele.expand = false;
              ele.children = [];
              ele.disabled = ele.bindFlag == 1 || ele.auditFlag == 1 ? true : false;
              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));
          that.$nextTick(()=>{
            // 如果是共享门店，也去设置禁用子级
            /* if (that.storeType == 2) {
              return false;
            }*/
            that.setSelectCheck();
          });
        })
        .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([]);
        });
      }
    },
    companyId(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>
