<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-08-14 16:51:07
 * @LastEditors: 无尘
 * @LastEditTime: 2020-03-12 09:33:23
 -->
<!--
<wx-tree v-model="itemData" ></wx-tree>

import wxTree from './wx-tree.vue';
-->
<template>
  <ul class="tree-ul-body">
    <draggable :list="itemData" class="wx-component" :options="rightOption" @input="emitter" @change="changeData" :move="onMove" @start="isDragging = true" @end="itemMoveEnd">
      <li v-for="(item, index) in itemData" :key="index + 'wx'">
        <div class="li-cell cursor-pointer">
          <div class="li-cell-inner flex flex-space-between boder-box p-r-20" :style="{ 'margin-left': (item.level + 1) * 20 + 'px' }">
            <div class="tree-left" :title="item.gicEnterpriseName" @click="toggleExpand(item)">
              <span :class="['font-12 color-606266 el-icon-expand', item.isStore == 1 || !item.hasSonNode ? 'color-fff' : '', item.expand ? 'el-icon-caret-bottom' : 'el-icon-caret-right']"></span><span :class="['font-14 p-l-10 p-r-10 iconfont', item.isStore == 1 ? 'icondianpu-kuai' : 'iconqiye-tianchong', item.bindFlag == 1 ? 'color-2f54eb' : 'color-dedfe6']"></span><span class="font-14 color-606266">{{ item.label }}</span>
            </div>
            <div class="tree-right">
              <el-button v-if="item.isStore == 0" type="text" @click.stop="addChild(item)">添加子部门</el-button>
              <el-button type="text" @click.stop="modChild(item)">修改名称</el-button>
              <el-button v-if="(item.level > 0 && !item.children.length && !item.hasSonNode) || !item.hasSonNode" type="text" @click.stop="delChild(item)">删除</el-button>
            </div>
          </div>
        </div>
        <li-row v-show="(item.expand && item.isStore == 0) || (!item.children.length && item.isStore == 0)" :itemObj="item" :itemData="item.children" @changeParent="changeParent" @refreshRecycle="refreshRecycle"></li-row
        ><!-- v-show="!!item.children.length && item.expand" -->
      </li>
    </draggable>
    <add-depart v-if="addShow" :departObj="modItem" @refreshData="refreshData"></add-depart>
    <div v-show="showDropIndicator" class="drag-indicator" ref="dropIndicator"></div>
  </ul>
</template>
<script>
import addDepart from '@/components/company/add-depart.vue';
import localforage from 'localforage';
import draggable from 'vuedraggable';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { getRequest, postRequest } from '@/api/api';
export default {
  name: 'li-row',
  components: {
    draggable,
    addDepart
  },
  props: {
    value: {
      type: [Object, Array],
      default() {
        return [];
      }
    },
    itemData: {
      type: [Object, Array],
      default() {
        return [];
      }
    },
    itemObj: {
      type: [Object, Array],
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      rightOption: {
        group: {
          name: 'people',
          pull: true,
          put: true
        },
        sort: true
      },
      addShow: false,
      additem: {},
      modItem: {},
      showDropIndicator: false
    };
  },
  computed: {},
  methods: {
    findNearestComponent(element, componentName) {
      let target = element;
      while (target && target.tagName !== 'BODY') {
        if (target.__vue__ && target.__vue__.$options.name === componentName) {
          return target.__vue__;
        }
        target = target.parentNode;
      }
      return null;
    },
    /**
     * 刷新数据
     */
    refreshRecycle() {
      const that = this;
      that.$emit('refreshRecycle');
    },
    /**
     * 触发父级
     */
    changeParent(itemObj, flag) {
      const that = this;
      console.log('触发父级:', itemObj);
      if (itemObj.addFlag) {
        that.$emit('changeParent', that.itemObj, flag);
        return false;
      }
      console.log('父级非新增：', itemObj, flag);
      let storeAddData = [];
      if (that.$store.state.addDepartment.length) {
        // 去掉重复的父级
        that.$store.state.addDepartment.forEach(ele => {
          if (ele.departmentId != itemObj.departmentId) {
            storeAddData.push(ele);
          }
        });
        that.$store.dispatch('clearAddData');
        storeAddData.forEach(ele => {
          that.$store.dispatch('saveAddInfo', ele);
        });
      }

      let storeEditData = [];
      if (that.$store.state.editDepartment.length) {
        // 去掉重复的父级
        that.$store.state.editDepartment.forEach(ele => {
          if (ele.departmentId != itemObj.departmentId) {
            storeEditData.push(ele);
          }
        });
        that.$store.dispatch('clearEditData');
        storeEditData.forEach(ele => {
          that.$store.dispatch('saveEditInfo', ele);
        });
      }

      if (flag == 'add') {
        that.$store.dispatch('saveAddInfo', itemObj);
      }
      if (flag == 'edit') {
        that.$store.dispatch('saveEditInfo', itemObj);
      }
    },
    /**
     *   移动中
     */
    onMove(evt, originalEvent) {
      // const that = this;
      // 判断中间是否存在父级
      /* console.log(evt, originalEvent);
      const treePosition = that.$el.getBoundingClientRect();
      console.log('1', that.$el, that.$el.getBoundingClientRect());
      console.log('2', evt.dragged.getBoundingClientRect());
      console.log('3', treePosition); */
      const draggedElement = evt.draggedContext.element;
      // 首
      if (draggedElement.level == 0) {
        return false;
      }
      /* console.log(that.$el.querySelector('.el-icon-expand'));
      const iconPosition = that.$el.querySelector('.el-icon-expand').getBoundingClientRect();
      console.log('iconPosition:', iconPosition);
      const dropIndicator = that.$refs.dropIndicator;

      dropIndicator.style.top = iconPosition.top + 'px';
      dropIndicator.style.left = iconPosition.left - treePosition.left + 'px';
      console.log(dropIndicator.style.top, dropIndicator.style.left);
      that.showDropIndicator = true; */
      return !draggedElement.fixed;
    },
    /**
     *  m],ove end
     */
    itemMoveEnd(evt) {
      const that = this;
      that.showDropIndicator = false;
      // 判断中间是否已经添加
      console.log('移动后：', evt, that.itemObj, that.itemData);
      that.$forceUpdate();
    },
    /**
     *    改变数组数据
     */
    emitter(value) {
      // console.log(value);
      this.$emit('input', value);
    },

    handleAdded(pitem, addFlag) {
      const that = this;
      pitem.children.forEach((ele, index) => {
        ele.parentId = pitem.departmentId;
        ele.parentDepartmentId = pitem.departmentId;
        ele.level = pitem.level + 1;
        // 如果gic部门移入是多层级的，需要设置子级的 addFlag
        ele.addFlag = !!addFlag ? true : false;
        if (ele.children.length) {
          that.handleAdded(ele, addFlag);
        }
      });
    },
    /* eslint-disable */
    async changeData(value) {
      const that = this;
      // that.$store.dispatch('saveAddInfo', );
      console.log('wx:change:', value, that.itemObj);
      // 跨级移动后还要判断原来父级有没有子级，设置
      if (value['removed']) {
        console.log('removed:',that.itemData)
        if (that.itemData.length) {
          console.log('跨级移动remove:',)
          that.itemObj.hasSonNode = true;
        }else {
          that.itemObj.hasSonNode = false;
        }
      }
      const objKey = !!value['added'] ? 'added' : !!value['moved'] ? 'moved' : 'removed';

      if (!!objKey && objKey != 'removed') {
        // 如果移入的父级原来子级是空的，需要判断来设置有没有子级字段
        if (that.itemObj.children.length) {
          that.$set(that.itemObj, 'hasSonNode', true);
        }
        let sort = '';
        for (let index = 0; index < that.itemObj.children.length; index++) {
          that.itemObj.children[index].sort = index;
          if (value[objKey].element.departmentId == that.itemObj.children[index].departmentId) {
            sort = index;
            that.itemObj.children[index].parentDepartmentIdOld = that.itemObj.children[index].parentDepartmentId;
            that.itemObj.children[index].parentId = that.itemObj.departmentId;
            that.itemObj.children[index].parentDepartmentId = that.itemObj.departmentId;
            that.itemObj.children[index].level = that.itemObj.level + 1;
            // added 且 wxEnterpriseId 不存在
            that.itemObj.children[index].addFlag = that.itemObj.children[index].addFlag ? that.itemObj.children[index].addFlag : objKey == 'added' && !that.itemObj.children[index].wxEnterpriseId ? true : false;
          }
          if (that.itemObj.children[index].children.length) {
            //await that.handleAdded(that.itemObj.children[index], that.itemObj.children[index].addFlag ? that.itemObj.children[index].addFlag : objKey == 'added' && !that.itemObj.children[index].wxEnterpriseId);
          }
        }
        console.log('父级:', that.itemObj);

        let newEle = JSON.parse(JSON.stringify(value[objKey].element));
        newEle.parentDepartmentIdOld = newEle.parentDepartmentId;
        newEle.parentId = that.itemObj.departmentId;
        newEle.parentDepartmentId = that.itemObj.departmentId;
        newEle.storeFlag = newEle.isStore;
        newEle.level = that.itemObj.level + 1;
        newEle.sort = sort;
        // 只有gic部门移入企业微信才加 addFlag
        newEle.addFlag = newEle.addFlag ? newEle.addFlag : objKey == 'added' && !newEle.wxEnterpriseId ? true : false;
        // 移入如果是多层级结构，就要循环遍历
        if (newEle.children.length) {
          await that.handleAdded(newEle, newEle.addFlag);
        }
        console.log('移入部门数据：', newEle,that.itemObj);

        that.$nextTick(() => {
          // 同级移动，如果是新增部门同级移动，不用存数据
          if (objKey == 'moved' && newEle.addFlag) {
            console.log('同级移动，如果是新增部门同级移动！不用存数据:');
            return false;
          }
          // 企业微信同级移动排序, 移动的时候还要去重
          if (objKey == 'moved') {
            // 从存储的数据中查找当前移动的部门是否存在，存在了就要删除老数据，
            // 去掉重复的父级,不要 判断存储中不存在 才添加
            let storeEditData = [];
            that.$store.state.editDepartment.forEach(ele => {
              if (ele.departmentId != newEle.departmentId) {
                storeEditData.push(ele);
              }
            });
            that.$store.dispatch('clearEditData');
            storeEditData.forEach(ele => {
              that.$store.dispatch('saveEditInfo', ele);
            });
            that.$store.dispatch('saveEditInfo', newEle);
            if (that.itemObj.addFlag) {
              that.$emit('changeParent', that.itemObj, 'edit');
              return false;
            }
            // 父级去重
            let storeEditObj = [];
            that.$store.state.editDepartment.forEach(ele => {
              if (ele.departmentId != that.itemObj.departmentId) {
                storeEditObj.push(ele);
              }
            });
            that.$store.dispatch('clearEditData');
            storeEditObj.forEach(ele => {
              that.$store.dispatch('saveEditInfo', ele);
            });
            that.$store.dispatch('saveEditInfo', that.itemObj);
            return false;
          }

          // 企业微信跨级移动,如果是新增部门跨级移动，删老数据---属于新增
          if (objKey == 'added' && newEle.addFlag && !newEle.wxEnterpriseId) {
            console.log('跨级移动，如果是新增部门跨级移动！，删除老数据,--属于新增');
            // 去掉重复的父级
            let storeEditDataWxAdd = [];
            that.$store.state.addDepartment.forEach(ele => {
              if (ele.departmentId != newEle.departmentId) {
                storeEditDataWxAdd.push(ele);
              }
            });
            that.$store.dispatch('clearAddData');
            storeEditDataWxAdd.forEach(ele => {
              that.$store.dispatch('saveAddInfo', ele);
            });
            that.$store.dispatch('saveAddInfo', newEle);
            // 判断父级是否新增
            if (that.itemObj.addFlag) {
              that.$emit('changeParent', that.itemObj, 'edit');
              return false;
            }
            // 新的排序
            that.$store.dispatch('saveEditInfo', that.itemObj);
            return false;
          }
          // 企业微信跨级移动,如果是老部门
          if (objKey == 'added' && !newEle.addFlag && !!newEle.wxEnterpriseId) {
            console.log(that.itemData)
            if (that.itemData.length) {
              console.log('企业微信跨级移动,是老部门:',that.itemObj)
              that.itemObj.hasSonNode = true;
            }
            // 去掉重复的父级
            let storeEditDataWx = [];
            that.$store.state.editDepartment.forEach(ele => {
              if (ele.departmentId != newEle.departmentId) {
                storeEditDataWx.push(ele);
              }
            });
            that.$store.dispatch('clearEditData');
            storeEditDataWx.forEach(ele => {
              that.$store.dispatch('saveEditInfo', ele);
            });
            that.$store.dispatch('saveEditInfo', newEle);
            if (that.itemObj.addFlag) {
              that.$emit('changeParent', that.itemObj, 'edit');
              return false;
            }
            console.log('addFlag:');
            // 父级去重
            let storeEditWx = [];
            that.$store.state.editDepartment.forEach(ele => {
              if (ele.departmentId != that.itemObj.departmentId) {
                storeEditWx.push(ele);
              }
            });
            that.$store.dispatch('clearEditData');
            storeEditWx.forEach(ele => {
              that.$store.dispatch('saveEditInfo', ele);
            });
            that.$store.dispatch('saveEditInfo', that.itemObj);
          }
          // gic 移动到企业微信
          if (objKey == 'added' && !newEle.wxEnterpriseId) {
            that.$store.dispatch('saveAddInfo', newEle);
            if (that.itemObj.addFlag) {
              that.$emit('changeParent', that.itemObj, 'edit');
              return false;
            }
            console.log('addFlag: gic 移动到企业微信:');
            // 父级去重
            let storeEditGic = [];
            that.$store.state.editDepartment.forEach(ele => {
              if (ele.departmentId != that.itemObj.departmentId) {
                storeEditGic.push(ele);
              }
            });
            that.$store.dispatch('clearEditData');
            storeEditGic.forEach(ele => {
              that.$store.dispatch('saveEditInfo', ele);
            });
            that.$store.dispatch('saveEditInfo', that.itemObj);
          }
        });
        that.$forceUpdate();
      }
    },
    /**
     * 展开或者关闭下级
     */
    async toggleExpand(item) {
      const that = this;
      console.log(item);
      item.expand = item.expand ? false : true;

      // 新增加子部门不存本地数据
      if (item.addFlag) {
        return false;
      }
      // 点击的时候，如果非门店且子级是空的需要请求获取子级
      if (item.isStore == 0 && !item.children.length && !item.loaded) {
        item.children = await that.getChildData(item);
      }

      //   只有展开且不是门店的才会保存
      if (item.expand && !item.isStore) {
        localforage.setItem('org' + item.departmentId, item);
      }
      if (!item.expand) {
        localforage.removeItem('org' + item.departmentId);
      }
      that.$emit('getSelectData', item);
      that.$forceUpdate();
    },
    /**
     * 添加子部门
     */
    addChild(item) {
      const that = this;
      // console.log('添加：', item);
      that.addShow = true;
      that.additem = item;
      that.modItem = {};
    },
    /**
     * 修改名称
     */
    modChild(item) {
      const that = this;
      console.log('修改：', item);
      // item.label = 2222;
      that.modItem = item;
      that.addShow = true;
      that.$forceUpdate();
    },

    async refreshData(name, mod) {
      const that = this;
      that.addShow = false;
      if (name == 'close') {
        return false;
      }
      if (mod == 'modify') {
        that.modItem.label = name;
        that.modItem.departmentName = name;
        // 如果是新增后又编辑，---属于新增
        if (that.modItem.addFlag) {
          // 去掉重复的父级
          console.log('新增后又编辑:',that.$store.state.addDepartment)
          let storeAddData = [];
          that.$store.state.addDepartment.forEach(ele => {
            if (ele.departmentId != that.modItem.departmentId) {
              storeAddData.push(ele);
            }
          });
          that.$store.dispatch('clearAddData');
          storeAddData.forEach(ele => {
            that.$store.dispatch('saveAddInfo', ele);
          });
          that.$store.dispatch('saveAddInfo', that.modItem);
          console.log('新增后又编辑，---属于新增:',that.modItem)
          return false;
        }
        that.$store.dispatch('saveEditInfo', that.modItem);
        return false;
      }
      // 添加子  部门的时候判断是否有子级且不是新添加
      const arr = !that.additem.addFlag && !that.additem.children.length ? await that.getChildData(that.additem) : [];
      if (arr.length && !that.additem.addFlag) {
        arr.forEach(ele => {
          that.additem.children.push(ele);
        });
      }
      let childObj = {
        id: String(new Date().getTime()),
        departmentId: String(new Date().getTime()),
        expand: true,
        level: that.additem.level + 1,
        isStore: 0,
        label: name,
        departmentName: name,
        addFlag: true,
        parentId: that.additem.departmentId,
        parentDepartmentId: that.additem.departmentId,
        children: []
      };
      that.$set(that.additem, 'hasSonNode', true);
      that.additem.children.push(childObj);
      // 增加的字段
      that.$store.dispatch('saveAddInfo', childObj);
      console.log(that.itemObj, that.itemObj.addFlag, that.$store.state.addDepartment);
      // 由于操作在当前层级，需要判断当前部门是不是新增部门
      if (that.additem.addFlag) {
        that.$emit('changeParent', that.itemObj, 'add');
        return false;
      }
      console.log('addFlag:');
      // 父级
      that.$store.dispatch('saveAddInfo', that.additem);

      that.$forceUpdate();
    },

    /**
     *   删除
     */
    delPost(item) {
      const that = this;
      let params = {
        departmentId: item.departmentId
      };
      return new Promise((resolve, reject) => {
        postRequest('/haoban-manage3-web/department-del', params)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              showMsg.showmsg('删除成功', 'success');
              that.$emit('refreshRecycle');
              resolve(true);
              return false;
            }
            errMsg.errorMsg(resData);
            resolve(false);
          })
          .catch(function(error) {
            resolve(false);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },

    async handleDelDepart(item) {
      const that = this;
      for (let index = 0; index < item.children.length; index++) {
        const ele = item.children[index];
        !ele.addFlag ? await that.delPost(ele) : '';
        if (ele.children.length) {
          await that.handleDelDepart(ele);
        }
      }
    },

    /**
     * 删除
     */
    async delChild(item) {
      const that = this;
      let key = '';
      that.itemData.forEach((ele, index) => {
        if (ele.departmentId == item.departmentId) {
          key = index;
        }
      });
      console.log('del:', key, that.itemData, item);
      // 如果是新增的子部门删除，就直接删除掉，不用调接口
      if (item.addFlag) {
        // 需要判断子级有没有已存在部门
        // if (item.children.length) {
        //   await that.handleDelDepart(item);
        // }
        that.itemData.splice(key, 1);
        if(!that.itemData.length) {
          that.itemObj.hasSonNode = false;
        }
        console.log(that.itemObj);
        showMsg.showmsg('删除成功', 'success');
        that.$forceUpdate();
        return false;
      }
      // 如果是以前的部门，需要先调接口删除
      const flag = await that.delPost(item);
      console.log('删除:', item, that.itemData);
      if (!flag) {
        // showMsg.showmsg('当前节点下有子节点，不可删除', 'warning');
        return false;
      }
      that.itemData.splice(key, 1);
      if(!that.itemData.length) {
        that.itemObj.hasSonNode = false;
      }
      that.$forceUpdate();
    },
    /* *
     *  获取下级数据
     */
    getChildData(item) {
      const that = this;
      let para = {
        parentId: item.departmentId, //
        isStore: item.isStore, //
        keyword: '' //
      };
      return new Promise((resolve, reject) => {
        getRequest('/haoban-manage3-web/department-list-level', para)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              // 加一个已加载标志
              item.loaded = true;
              if (resData.result.length) {
                item.loaded = true;
                resData.result.forEach(ele => {
                  ele.expand = false;
                  ele.children = [];
                  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
            });
          });
      });
    },

    async checkLocal(data) {
      // con st that = this;
      return new Promise((resolve, reject) => {
        localforage
          .getItem('org' + data.departmentId)
          .then(value => {
            //  当离线仓库中的值被载入时，此处代码运行
            // console.log(value);
            value ? resolve(true) : resolve(false);
          })
          .catch(function(err) {
            // 当出错时，此处代码运行
            resolve(false);
            // console.log(err);
          });
      });
    },
    /**
     * 处理变化的数据
     */
    handleChangeChild(parent,item) {
      const that = this;
      for (let index = 0; index < item.length; index++) {
        item[index].parentDepartmentId = parent.departmentId;
        item[index].level = parent.level + 1;
        if (item[index].children.length) {
          item[index].hasSonNode = true;
          that.handleChangeChild(item[index],item[index].children);
        }
      }
    },

    /**
     * 获取存储的数据
     */
    async getLocalData() {
      const that = this;
      for (let index = 0; index < that.itemData.length; index++) {
        const flag = await that.checkLocal(that.itemData[index]);
        if (flag) {
          that.itemData[index].expand = true;
          console.log('itemData:', that.itemData[index]);
          // 获取子集的时候会加一个加载的标志，来避免移动后重复加载子集
          if (!that.itemData[index].loaded) {
            that.itemData[index].children = await that.getChildData(that.itemData[index]);
          }
          // 拖拽进去
          if (that.itemData[index].loaded && !that.itemData[index].children.length) {
            that.$set(that.itemData[index],'hasSonNode',false);
            that.itemData[index].hasSonNode = false;
          }
          if (that.itemData[index].children.length) {
            that.$set(that.itemData[index],'hasSonNode',true);
            // console.log('that.itemData[index]:',that.itemData[index])
            that.itemData[index].hasSonNode = true;
            that.handleChangeChild(that.itemData[index],that.itemData[index].children);
          }
        }
      }
    }
  },
  watch: {
    itemData: function(newData, oldData) {
      const that = this;
      if (newData.length) {
        that.getLocalData();
      }
    }
  },
  mounted() {
    const that = this;
    if (that.itemData.length) {
      that.getLocalData();
    }
  }
};
</script>
<style lang="less" scoped>
.drag-indicator {
  position: absolute;
  left: 0;
  right: 0;
  height: 1px;
  background-color: #409eff;
}
.tree-ul-body {

  min-height: 3px;
  .wx-component {
    min-height: 3px;
  }
}
ul {
  min-height: 3px;
  .wx-component {
    min-height: 3px;
  }
}

.li-cell {
  min-height: 26px;
  line-height: 26px;
  white-space: nowrap;
  // overflow: hidden;
  text-overflow: ellipsis;
  .tree-left {
    .color-fff {
      color: #fff;
    }
  }
  .tree-right {
    display: none;
  }
  &:hover {
    background: rgba(47, 84, 235, 0.05);
    .tree-left {
      .color-fff {
        color: rgba(47, 84, 235, 0.05);
      }
    }
    .tree-right {
      display: block;
    }
  }
}

.w-110 {
  width: 110px;
}

.w-320 {
  width: 320px;
}

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

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