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

import wxTree from './wx-tree.vue';
-->
<template>
  <ul class="">
    <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="flex flex-space-between boder-box p-r-20" :style="{ 'padding-left': (item.level + 1) * 10 + 'px' }">
            <div class="tree-left">
              <span @click="toggleExpand(item)" :class="['font-12 color-606266', item.isStore == 1 ? '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" type="text" @click.stop="delChild(item)">删除</el-button>
            </div>
          </div>
        </div>
        <li-row v-if="item.expand" :itemObj="item" :itemData="item.children" @changeParent="changeParent"></li-row
        ><!-- v-show="!!item.children.length && item.expand" -->
      </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';
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: {}
    };
  },
  computed: {},
  methods: {
    /**
     * 触发父级
     */
    changeParent(itemObj, flag) {
      const that = this;
      if (itemObj.addFlag) {
        that.$emit('changeParent', that.itemObj, flag);
        return false;
      }
      console.log('父级非新增：', itemObj, flag);
      if (flag == 'add') {
        that.$store.dispatch('saveAddInfo', itemObj);
      }
      if (flag == 'edit') {
        that.$store.dispatch('saveEditInfo', itemObj);
      }
    },
    /**
     *   移动中
     */
    onMove(evt) {
      // const that = this;
      // 判断中间是否存在父级
      const draggedElement = evt.draggedContext.element;
      // 首
      if (draggedElement.level == 0) {
        return false;
      }
      return !draggedElement.fixed;
    },
    /**
     *  m],ove end
     */
    itemMoveEnd(evt) {
      const that = this;
      // 判断中间是否已经添加
      console.log('移动后：', evt, that.itemObj, that.itemData);
      that.$forceUpdate();
    },
    /**
     *    改变数组数据
     */
    emitter(value) {
      // console.log(value);
      this.$emit('input', value);
    },

    handleAdded(pitem) {
      const that = this;
      pitem.children.forEach((ele, index) => {
        ele.level = pitem.level + 1;
        if (ele.children.length) {
          that.handleAdded(ele);
        }
      });
    },
    async changeData(value) {
      const that = this;
      // that.$store.dispatch('saveAddInfo', );
      console.log('wx:change:', value, that.itemObj);
      const objKey = !!value['added'] ? 'added' : !!value['moved'] ? 'moved' : 'removed';

      if (!!objKey) {
        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].level = that.itemObj.level + 1;
          }
          if (that.itemObj.children[index].children.length) {
            await that.handleAdded(that.itemObj.children[index]);
          }
        }
        let newEle = JSON.parse(JSON.stringify(value[objKey].element));
        newEle.parentId = that.itemObj.departmentId;
        newEle.parentDepartmentId = that.itemObj.departmentId;
        newEle.storeFlag = newEle.isStore;
        newEle.level = that.itemObj.level + 1;
        newEle.sort = sort;
        newEle.addFlag = objKey == 'added' ? true : false;
        // 移入如果是多层级结构，就要循环遍历
        if (newEle.children.length) {
          await that.handleAdded(newEle);
        }
        console.log(newEle);
        that.$nextTick(() => {
          // 企业微信同级移动排序
          if (objKey == 'moved') {
            if (that.itemObj.addFlag) {
              that.$emit('changeParent', that.itemObj, 'edit');
            }
            that.$store.dispatch('saveEditInfo', newEle);
            that.$store.dispatch('saveEditInfo', that.itemObj);
            return false;
          }
          // if (objKey == 'removed') {
          //   if (that.itemObj.addFlag) {
          //     that.$emit('changeParent', that.itemObj, 'edit');
          //   }
          //   that.$store.dispatch('saveEditInfo', newEle);
          //   that.$store.dispatch('saveEditInfo', that.itemObj);
          //   return false;
          // }
          // 企业微信跨级移动
          if (objKey == 'added' && !!newEle.wxEnterpriseId) {
            if (that.itemObj.addFlag) {
              that.$emit('changeParent', that.itemObj, 'edit');
            }
            that.$store.dispatch('saveEditInfo', newEle);
            that.$store.dispatch('saveEditInfo', that.itemObj);
          }
          // gic 移动到企业微信
          if (objKey == 'added' && !newEle.wxEnterpriseId) {
            if (that.itemObj.addFlag) {
              that.$emit('changeParent', that.itemObj, 'edit');
            }
            that.$store.dispatch('saveAddInfo', newEle);
            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;
    },
    /**
     * 修改名称
     */
    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;
        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.additem.children.push(childObj);
      // 增加的字段
      if (that.itemObj.addFlag) {
        that.$emit('changeParent', that.itemObj, 'add');
      }
      that.$store.dispatch('saveAddInfo', that.additem);
      that.$store.dispatch('saveAddInfo', childObj);
      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) {
              resolve(true);
              return false;
            }
            errMsg.errorMsg(resData);
            resolve(false);
          })
          .catch(function(error) {
            resolve(false);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },

    /**
     * 删除
     */
    async delChild(item) {
      const that = this;
      let key = '';
      that.itemData.forEach((ele, index) => {
        if (ele.id == item.id) {
          key = index;
        }
      });
      // 如果是新增的子部门删除，就直接删除掉，不用调接口
      if (item.addFlag) {
        that.itemData.splice(key, 1);
        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);
      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);
          });
      });
    },

    /**
     * 获取存储的数据
     */
    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]);
          }
        }
      }
    }
  },
  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>
.li-cell {
  min-height: 26px;
  line-height: 26px;
  .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>
