<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-08-14 16:51:07
 * @LastEditors: 无尘
 * @LastEditTime: 2020-06-17 14:23:52
 -->
<!--
<org-tree v-if="item.children.length" :itemData="item.children" ></org-tree>

import orgTree from './org-tree.vue';
-->
<template>
  <ul :class="['gic-tree-body', !!itemData[0] && itemData[0].level == 0 ? '' : 'm-l-20']">
    <!--<draggable :list="itemData" class="org-component" :options="leftOption" :move="onMove" @start="isDragging = true" @end="itemMoveEnd">
      -->
    <li v-for="(item, index) in itemData" :key="index + 'gic'">
      <div :class="['li-cell li-cell-copy border-box cursor-pointer', departObj.departmentId == item.departmentId ? 'li-cell-active' : '']" @click="toggleExpand(item)">
        <span :class="['font-12 color-606266', item.isStore == 1 || !item.hasSonNode ? 'color-fff' : '', item.expand ? 'el-icon-caret-bottom' : 'el-icon-caret-right']"></span><span v-if="item.loading" class="el-tree-node__loading-icon el-icon-loading"></span><span class="font-14 color-606266 p-l-10">{{ item.label }}</span>
      </div>
      <li-row v-show="!!item.children.length && item.expand" :departObj="departObj" :wxData="wxData" :itemObj="item" :itemData="item.children" @setFix="setFix" @getSelectData="getSelectData"></li-row>
    </li>
    <!--</draggable>-->
  </ul>
</template>
<script>
// import draggable from 'vuedraggable';
import errMsg from '@/common/js/error';
import { getRequest } from '@/api/api';
import $ from 'jquery';
export default {
  name: 'li-row',
  components: {
    // draggable
  },
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    wxData: {
      type: [Object, Array],
      default() {
        return [];
      }
    },
    itemData: {
      type: [Object, Array],
      default() {
        return [];
      }
    },
    itemObj: {
      type: [Object, Array],
      default() {
        return [];
      }
    },
    // 选中节点
    departObj: {
      type: Object,
      default() {
        return {
          departmentId: '',
          departmentName: '',
          wxDepartmentId: '',
          parentId: '',
          isStore: '',
          staffCount: '',
          bindFlag: '',
          loading: false
        };
      }
    }
  },
  data() {
    return {
      // leftOption
      leftOption: {
        group: {
          name: 'people',
          pull: true,
          put: false
        },
        sort: false,
        disabled: false
      }
    };
  },
  methods: {
    /**
     * 获取选中部门/门店数据
     */
    getSelectData(obj) {
      const that = this;
      that.selectData = obj;
      that.$emit('getSelectData', obj);
    },
    /**
     * 展开或者关闭下级
     */
    async toggleExpand(item) {
      const that = this;
      // console.log(item);
      item.expand = item.expand ? false : true;
      // 点击的时候，如果非门店且子级是空的需要请求获取子级
      if (item.isStore == 0 && !item.children.length && !item.loaded && item.hasSonNode == true) {
        item.loading = true;
        item.children = await that.getChildData(item);
        item.loading = false;
      }
      that.$emit('getSelectData', item);
    },
    /**
     * 获取下级数据
     */
    getChildData(item) {
      const that = this;
      let para = {
        enterpriseId: item.enterpriseId || that.brandId,
        departmentId: item.departmentId, //
        type: item.type //
      };
      return new Promise((resolve, reject) => {
        if (item.type == 3) {
          resolve([]);
          return false;
        }
        getRequest('/haoban-app-customer-web/gic-department-list', para)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              // 加一个已加载标志
              if (resData.result.length) {
                item.loaded = true;
                resData.result.forEach(ele => {
                  ele.loading = false;
                  ele.expand = false;
                  ele.children = [];
                  ele.gicBind = true;
                  ele.level = item.level + 1;
                  ele.label = ele.departmentName;
                });
              }
              resolve(resData.result || []);
              return false;
            }
            resolve([]);
            errMsg.errorMsg(resData);
          })
          .catch(function(error) {
            resolve([]);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },
    handleId(id, list) {
      const that = this;
      let flag = true;
      for (let index = 0; index < list.length; index++) {
        const element = list[index];
        if (element.departmentId == id) {
          flag = false;
          return false;
          break;
        }
        if (flag && element.children.length) {
          flag = that.handleId(id, element.children);
        }
      }
      // console.log('child:', flag);
      return flag;
    },
    /**
     *  move{relatedContext, draggedContext}
     */
    onMove(evt) {
      const that = this;
      $('[style="background: rgba(47, 84, 235, 0.05);"]').removeAttr('style');
      $('.sortable-chosen.sortable-ghost')
        .parent()
        .parent()
        .siblings('.li-cell')
        .css({ background: 'rgba(47,84,235,.05)' });

      // 判断中间是否存在父级
      const draggedElement = evt.draggedContext.element;
      // 首级不能移动
      // console.log('level', draggedElement.level);
      if (draggedElement.level == 0) {
        return false;
      }
      // console.log('wxData:', that.wxData);
      // console.log(that.itemObj, that.itemData);
      const nearElement = evt.relatedContext['element'];
      // console.log('nearElement:', nearElement);
      if (!!nearElement && !!nearElement['gicBind']) {
        return false;
      }
      if (!!nearElement) {
        that.itemData.forEach(ele => {
          if (ele.departmentId == draggedElement['departmentId']) {
            ele.level = nearElement['level'];
          }
        });
      }
      let flag = true;
      for (let index = 0; index < that.wxData[0].children.length; index++) {
        const element = that.wxData[0].children[index];
        if (element.departmentId == draggedElement['departmentId']) {
          flag = false;
          return false;
          break;
        }
        if (flag && element.children.length) {
          flag = that.handleId(draggedElement['departmentId'], element.children);
        }
      }
      // console.log(flag);
      if (!flag) {
        /* that.$message({
              message: '当前部门/门店已存在',
              type: 'warning'
            }); */
        return false;
      }
      that.$nextTick(() => {
        $('.sortable-chosen.sortable-ghost')
          .parent()
          .parent()
          .siblings('.li-cell')
          .css({ background: 'rgba(47,84,235,.05)' });
      });
      // console.log('gic:move-->', evt, !draggedElement.fixed);
      return !draggedElement.fixed;
    },
    /**
     * 设置父级的父级不可拖拽
     */
    setFix() {
      const that = this;
      that.$set(that.itemObj, 'fixed', true);
    },
    /**
     *  move end
     */
    itemMoveEnd(evt) {
      const that = this;
      $('[style="background: rgba(47, 84, 235, 0.05);"]').removeAttr('style');
      // 判断中间是否已经添加
      // console.log('gic:', evt, that.itemObj, that.itemData);
      if (!that.itemObj.children.length) {
        that.itemObj.hasSonNode = false;
      }
      const childData = that.getChildData(that.itemObj);
      if (that.itemObj.children.length != childData.length) {
        that.$set(that.itemObj, 'fixed', true);
        that.$emit('setFix');
      }
      that.$forceUpdate();
    },
    /**
     * 获取子级的数据
     */
    async getNextData() {
      const that = this;
      for (let index = 0; index < that.itemData.length; index++) {
        that.itemData[index].expand = false;
        // 获取子集的时候会加一个加载的标志，来避免移动后重复加载子集
        if (!that.itemData[index].loaded && that.itemData[index].isStore == 0 && that.itemData[index].hasSonNode == true) {
          that.itemData[index].loading = true;
          that.itemData[index].children = await that.getChildData(that.itemData[index]);
          that.itemData[index].loading = false;
        }
      }
    }
  },
  watch: {
    itemData: function(newData, oldData) {
      // const that = this;
      if (newData.length) {
        setTimeout(() => {
          // that.getNextData();
        }, 0);
      }
    }
  },
  mounted() {
    document.body.ondrop = function(event) {
      event.preventDefault();
      event.stopPropagation();
    };
    /* const that = this;
    if (that.itemData.length) {
      that.getNextData();
    } */
  },
  beforeDestroy() {
    this.tempArr = [];
  }
};
</script>
<style lang="less" scoped>
.m-l-20 {
  margin-left: 20px;
}

.gic-tree-body {
  .sortable-chosen.sortable-ghost {
    /* .li-cell::before {
      content: ' ';
      position: absolute;
      left: 20px;
      width: 100%;
      height: 26px;
      border-bottom: 2px solid #e4e7ed;
    }
    .li-cell::after {
      content: ' ';
      position: absolute;
      left: 20px;
      bottom: -3px;
      width: 6px;
      height: 6px;
      border-radius: 50%;
      border: 1px solid #e4e7ed;
      background: #fff;
      z-index: 1;
    } */
  }
}

.li-cell {
  position: relative;
  line-height: 32px;
  padding-left: 20px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  .color-fff {
    color: #fff;
  }
  &.li-cell-active {
    background: rgba(47, 84, 235, 0.05);
    span {
      color: #2f54eb;
    }
  }
}

.w-110 {
  width: 110px;
}

.w-320 {
  width: 320px;
}

.m-t-14 {
  margin-top: 14px;
}

.child-row {
  padding-left: 10px;
}
</style>
