<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-08-14 16:51:07
 * @LastEditors: 无尘
 * @LastEditTime: 2020-06-12 15:35:20
 -->
<!--
<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 v-if="item.loading" class="el-tree-node__loading-icon el-icon-loading"></span><span :class="['font-14  p-r-10 iconfont-hb3', !!item.loading ? '' : 'p-l-10', 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 && !item.gicBind" type="text" @click.stop="addChild(item)">添加子部门</el-button>
              <el-button v-if="!item.gicBind" type="text" @click.stop="modChild(item)">修改名称</el-button>
              <el-button v-if="!item.gicBind && ((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.isStore == 0 && !(item.gicBind && !item.children.length)" :class="['cell-child', !item.expand && item.isStore == 0 ? 'cell-child-show' : '']" :itemObj="item" :itemData="item.children" @changeParent="changeParent" @refreshRecycle="refreshRecycle" @checkParent="checkParent"></li-row
        ><!-- v-show="(item.expand && item.isStore == 0) || (!item.children.length && item.isStore == 0)" -->
      </li>
    </draggable>
    <add-depart v-if="addShow" :departObj="modItem" @refreshData="refreshData"></add-depart>
  </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';
import $ from 'jquery';
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,
        scroll: true,
        animation: 100
      },
      addShow: false,
      additem: {},
      modItem: {}
    };
  },
  computed: {},
  methods: {
    /**
     * 刷新数据
     */
    refreshRecycle() {
      const that = this;
      that.$emit('refreshRecycle');
    },
    /**
     * 检查父级有没有子级
     */
    checkParent(obj) {
      const that = this;
      that.itemObj.children.forEach(ele => {
        if (ele.loaded && ele.children.length) {
          ele.hasSonNode = false;
        }
      });
      that.$forceUpdate();
    },
    /**
     * 触发父级
     */
    changeParent(itemObj, flag) {
      const that = this;
      if (itemObj.addFlag) {
        that.$emit('changeParent', that.itemObj, flag);
        return false;
      }
      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);
      }
    },
    /**
     *   移动中,如果使用 async 异步方法，下面不能拦截
     */
    onMove(evt, originalEvent) {
      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)' });

      // 判断中间是否存在父级
      // console.log('onMove:',evt, originalEvent);
      // console.log('onMove:', that.itemObj, that.itemData);
      if (!that.itemObj.children.length) {
        that.$set(that.itemObj, 'hasSonNode', false);
        that.itemObj.hasSonNode = false;
      }
      // 为了改变level
      const draggedElement = evt.draggedContext.element;
      //gic 移动的不能再动
      // console.log(!!draggedElement['gicBind']);
      if (!!draggedElement && draggedElement.hasOwnProperty('gicBind') && !!draggedElement['gicBind']) {
        return false;
      }
      // 触发父级
      that.$emit('checkParent', draggedElement);
      const nearElement = evt.relatedContext['element'];
      //gic 移动的不能被移入
      // console.log(!!nearElement['gicBind']);
      if (!!nearElement && nearElement.hasOwnProperty('gicBind') && !!nearElement['gicBind']) {
        return false;
      }
      if (!!nearElement && nearElement.hasOwnProperty('level') && draggedElement['level'] != nearElement['level']) {
        that.itemObj.children.forEach(ele => {
          if (ele.departmentId == draggedElement['departmentId']) {
            ele.level = nearElement['level'];
          }
        });
      }
      // 首级
      if (draggedElement.level == 0) {
        return false;
      }

      that.$nextTick(() => {
        $('.sortable-chosen.sortable-ghost')
          .parent()
          .parent()
          .siblings('.li-cell')
          .css({ background: 'rgba(47,84,235,.05)' });
      });

      return !draggedElement.fixed;
    },
    /**
     *  m],ove end
     */
    itemMoveEnd(evt) {
      const that = this;
      $('[style="background: rgba(47, 84, 235, 0.05);"]').removeAttr('style');
      // 判断中间是否已经添加
      // 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.$set(ele, 'hasSonNode', true);
          that.handleAdded(ele, addFlag);
        }
      });
    },
    handleRemoved(pitem) {
      const that = this;
      pitem.children.forEach((ele, index) => {
        ele.parentId = pitem.departmentId;
        ele.parentDepartmentId = pitem.departmentId;
        ele.level = pitem.level + 1;
        if (ele.children.length) {
          that.$set(ele, 'hasSonNode', true);
          that.handleRemoved(ele);
        }
      });
    },
    /* eslint-disable */
    async changeData(value) {
      const that = this;
      // console.log('wx:change:', value, that.itemObj);
      // 跨级移动后还要判断原来父级有没有子级，设置
      if (value['removed']) {
        if (that.itemData.length) {
          that.itemObj.hasSonNode = true;
        } else {
          // that.itemObj.hasSonNode = false;
        }
        // 企业微信老部门跨级移动，出现 removed
        for (let index = 0; index < that.itemData.length; index++) {
          const element = that.itemData[index];
          // 如果移入到有子级却没有加载子级的部门时候，
          if (!that.itemData[index].loaded && that.itemData[index].children.length) {
            await that.handleRemoved(that.itemData[index]);
            const childLevelData = that.itemData[index].hasSonNode ? await that.getChildData(that.itemData[index]) : [];
            childLevelData.forEach(ele => {
              that.itemData[index].children.push(ele);
            });
            // console.log('移入到还没有加载子级的部门1：',that.itemData)
            let hash = {};
            let arr = JSON.parse(JSON.stringify(that.itemData[index].children));
            arr = arr.reduce(function(item, next) {
              hash[next.departmentId] ? '' : (hash[next.departmentId] = true && item.push(next));
              return item;
            }, []);
            that.itemData[index].children = arr;
          }
        }
      }
      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) {
            that.$set(that.itemObj.children[index], 'hasSonNode', true);
            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);
        if (!that.itemObj.loaded && that.itemObj.hasSonNode) {
          const childData = await that.getChildData(that.itemObj);
          childData.forEach(ele => {
            that.itemObj.children.push(ele);
          });
          // console.log('移入到还没有加载子级的部门2：',that.itemObj);
          let hashObj = {};
          let arrObj = JSON.parse(JSON.stringify(that.itemObj.children));
          arrObj = arrObj.reduce(function(item, next) {
            hashObj[next.departmentId] ? '' : (hashObj[next.departmentId] = true && item.push(next));
            return item;
          }, []);
          that.itemObj.children = arrObj;
        }
        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) {
              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);
            });
            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) {
              return false;
            }
            return false;
          }
          // 企业微信跨级移动,如果是老部门
          if (objKey == 'added' && !newEle.addFlag && !!newEle.wxEnterpriseId) {
            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) {
              return false;
            }
            // 父级去重
            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);
            });
          }
          // gic 移动到企业微信
          if (objKey == 'added' && !newEle.wxEnterpriseId) {
            that.$store.dispatch('saveAddInfo', newEle);
            if (that.itemObj.addFlag) {
              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.$forceUpdate();
      }
    },
    /**
     * 展开或者关闭下级
     */
    async toggleExpand(item) {
      const that = this;
      item.expand = item.expand ? false : true;
      // 如果gic 部门，没有加载数据
      if (item.gicBind && item.isStore == 0 && !item.children.length && !item.loaded && item.hasSonNode) {
        item.loading = true;
        item.children = await that.getGicChildData(item);
        item.loading = false;
        return false;
      }
      // 新增加子部门不存本地数据
      if (item.addFlag) {
        return false;
      }
      // 点击的时候，如果非门店且子级是空的需要请求获取子级
      if (item.isStore == 0 && !item.children.length && !item.loaded && item.hasSonNode) {
        item.loading = true;
        item.children = await that.getChildData(item);
        item.loading = false;
      }
      //   只有展开且不是门店的才会保存
      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();
    },
    /**
     * 获取GIC下级数据
     */
    getGicChildData(item) {
      const that = this;
      let para = {
        enterpriseId: item.enterpriseId,
        departmentId: item.departmentId, //
        type: item.type //
      };
      return new Promise((resolve, reject) => {
        if (item.type == 3) {
          resolve([]);
          return false;
        }
        getRequest('/haoban-manage3-web/unbind-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;
                  ele.enterpriseId = item.enterpriseId;
                });
              }
              resolve(resData.result || []);
              return false;
            }
            resolve([]);
            errMsg.errorMsg(resData);
          })
          .catch(function(error) {
            resolve([]);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },
    /**
     * 添加子部门
     */
    async addChild(item) {
      const that = this;
      const tag = await that.getStatus();
      if (!!tag && (tag.syncStatus == 0 || tag.syncStatus == 1 || tag.syncStatus == 2 || tag.syncStatus == 3||tag.syncStatus == 5)) {
        showMsg.showmsg('通讯录同步中，暂无法操作', 'warning');
        return false;
      }
      that.addShow = true;
      that.additem = item;
      that.modItem = {};
    },
    /**
     * 修改名称
     */
    async modChild(item) {
      const that = this;
      const tag = await that.getStatus();
      if (!!tag && (tag.syncStatus == 0 || tag.syncStatus == 1 || tag.syncStatus == 2 || tag.syncStatus == 3||tag.syncStatus == 5)) {
        showMsg.showmsg('通讯录同步中，暂无法操作', 'warning');
        return false;
      }
      that.modItem = item;
      that.addShow = true;
      that.$forceUpdate();
    },

    /**
     * 获取同步状态
     */
    getStatus() {
      const that = this;
      return new Promise((resolve, reject) => {
        let para = {};
        getRequest('/haoban-manage3-web/department-sync-check', para)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              resolve(resData.result);
              return false;
            }
            resolve(false);
            errMsg.errorMsg(resData);
          })
          .catch(function(error) {
            resolve(false);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },

    async refreshData(name, mod) {
      const that = this;
      that.addShow = false;
      if (name == 'close') {
        return false;
      }
      if (mod == 'modify') {
        const modFlag = await that.toModDepart(name);
        if (!modFlag) {
          return false;
        }
        that.modItem.label = name;
        that.modItem.departmentName = name;
        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 = await that.toAddOrMod(name);
      if (!childObj) {
        return false;
      }
      childObj.level = that.additem.level + 1;
      that.$set(that.additem, 'hasSonNode', true);
      that.additem.children.push(childObj);
      that.$forceUpdate();
    },

    /**
     *  新增 --- api
     */
    toAddOrMod(departmentName) {
      const that = this;
      return new Promise((resolve, reject) => {
        let para = {
          departmentName: departmentName,
          parentId: that.additem.departmentId
        };
        postRequest('/haoban-manage3-web/department-add', para)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              showMsg.showmsg('新增成功！', 'success');
              resData.result.label = departmentName;
              resData.result.expand = true;
              resData.result.children = [];
              resolve(resData.result);
              return;
            }
            errMsg.errorMsg(resData);
            resolve(false);
          })
          .catch(function(error) {
            resolve(false);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },
    /**
     *  修改 --- api
     */
    toModDepart(departmentName) {
      const that = this;
      return new Promise((resolve, reject) => {
        let para = {
          departmentId: that.modItem.departmentId,
          departmentName: departmentName,
          parentId: that.modItem.parentDepartmentId
        };
        postRequest('/haoban-manage3-web/department-edit', para)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              showMsg.showmsg('修改成功！', 'success');
              resolve(true);
              return;
            }
            errMsg.errorMsg(resData);
            resolve(false);
          })
          .catch(function(error) {
            resolve(false);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },

    /**
     *   删除
     */
    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;
      const tag = await that.getStatus();
      if (!!tag && (tag.syncStatus == 0 || tag.syncStatus == 1 || tag.syncStatus == 2 || tag.syncStatus == 3||tag.syncStatus == 5)) {
        showMsg.showmsg('通讯录同步中，暂无法操作', 'warning');
        return false;
      }


      let key = '';
      that.itemData.forEach((ele, index) => {
        if (ele.departmentId == item.departmentId) {
          key = index;
        }
      });
      // 如果是新增的子部门删除，就直接删除掉，不用调接口
      if (item.addFlag) {
        // 不需要判断子级有没有已存在部门
        // if (item.children.length) {
        //   await that.handleDelDepart(item);
        // }
        that.itemData.splice(key, 1);
        if (!that.itemData.length) {
          that.itemObj.hasSonNode = false;
        }
        showMsg.showmsg('删除成功', 'success');
        that.$forceUpdate();
        return false;
      }
      that.$confirm('此操作将永久删除该分组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 如果是以前的部门，需要先调接口删除
        const flag = await that.delPost(item);
        if (!flag) {
          return false;
        }
        that.itemData.splice(key, 1);
        if (!that.itemData.length) {
          that.itemObj.hasSonNode = false;
        }
        // 去掉存储的数据
      let storeEditDataWxAdd = [];
      that.$store.state.addDepartment.forEach(ele => {
        if (ele.departmentId != item.departmentId) {
          storeEditDataWxAdd.push(ele);
        }
      });
      that.$store.dispatch('clearAddData');
      storeEditDataWxAdd.forEach(ele => {
        that.$store.dispatch('saveAddInfo', ele);
      });

      // 去掉存储编辑
      let storeEditDataWx = [];
      that.$store.state.editDepartment.forEach(ele => {
        if (ele.departmentId != item.departmentId) {
          storeEditDataWx.push(ele);
        }
      });
      that.$store.dispatch('clearEditData');
      storeEditDataWx.forEach(ele => {
        that.$store.dispatch('saveEditInfo', ele);
      });
        that.$forceUpdate();
      }).catch(() => {})
    },
    /* *
     *  获取下级数据
     */
    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.loading = false;
                  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 => {
            //  当离线仓库中的值被载入时，此处代码运行
            value ? resolve(true) : resolve(false);
          })
          .catch(function(err) {
            // 当出错时，此处代码运行
            resolve(false);
          });
      });
    },
    /**
     * 处理变化的数据
     */
    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;
          // 获取子集的时候会加一个加载的标志，来避免移动后重复加载子集
          if (!that.itemData[index].loaded && that.itemData[index].isStore == 0 && that.itemData[index].hasSonNode == true) {
            that.itemData[index].loading = true;
            // console.log('存储：',that.itemData[index])
            // children 改为不直接赋值，避免有移入数据被替换掉-20200520
            const childData = await that.getChildData(that.itemData[index]);
            childData.forEach(ele => {
              that.itemData[index].children.push(ele);
            });
            that.itemData[index].loading = false;
          }
          // 拖拽进去
          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);
            that.itemData[index].hasSonNode = true;
            that.handleChangeChild(that.itemData[index], that.itemData[index].children);
          }
        }
      }
    }
  },
  watch: {
    itemData: function(newData, oldData) {
      const that = this;
      // console.log('watch: itemData:',newData);
      if (newData.length) {
        setTimeout(() => {
          that.getLocalData();
        }, 0);
      }
    },
    itemObj: function(newData, oldData) {
      // const that = this;
      // console.log('watch: itemObj:',that.itemObj);
    }
  },
  mounted() {
    const that = this;
    document.body.ondrop = function(event) {
      event.preventDefault();
      event.stopPropagation();
    };
    if (that.itemData.length) {
      that.getLocalData();
    }
  }
};
</script>
<style lang="scss" scoped>
.drag-indicator {
  position: absolute;
  left: 0;
  right: 0;
  height: 1px;
  background-color: #409eff;
}

.tree-ul-body {
  min-height: 6px;
  &.cell-child-show {
    // min-height: 10px;
    max-height: 10px;
    overflow: hidden;
    opacity: 0;
    .wx-component {
      // min-height: 10px;
    }
  }
  .wx-component {
    min-height: 6px;
  }
}

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

.li-cell {
  min-height: 26px;
  line-height: 26px;
  white-space: nowrap;
  // overflow: hidden;
  text-overflow: ellipsis;
  .li-cell-inner {
    line-height: 33px;
  }
  .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>
