<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-08-14 16:51:07
 * @LastEditors  : 无尘
 * @LastEditTime : 2020-02-24 14:44:34
 -->
<!--
<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" type="text" @click.stop="delChild(item)">删除</el-button>
            </div>
          </div>
        </div>
        <li-row v-if="item.expand" :itemData="item.children"></li-row
        ><!-- v-show="!!item.children.length && item.expand" -->
      </li>
    </draggable>
    <add-depart v-if="addShow" :departObj="departObj" @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 [];
      }
    }
  },
  data() {
    return {
      rightOption: {
        group: {
          name: 'people',
          pull: true,
          put: true
        },
        sort: true
      },
      addShow: false,
      additem: {},
      departObj: {}
    };
  },
  computed: {},
  methods: {
    onMove(evt) {
      // const that = this;
      // 判断中间是否存在父级
      const draggedElement = evt.draggedContext.element;
      // 首级不能移动
      if (draggedElement.level == 0) {
        return false;
      }
      console.log(evt, draggedElement, !draggedElement.fixed);
      return !draggedElement.fixed;
    },
    /**
     *  move end
     */
    itemMoveEnd(evt) {
      const that = this;
      // 判断中间是否已经添加
      console.log(evt, that.itemData);
      that.$forceUpdate();
    },
    /**
     *  改变数组数据
     */
    emitter(value) {
      // console.log(value);
      this.$emit('input', value);
    },
    changeData(value) {
      // console.log(value);
    },
    /**
     * 展开或者关闭下级
     */
    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.addShow = true;
      that.$forceUpdate();
    },

    async refreshData(name) {
      const that = this;
      that.addShow = false;
      if (name == 'close') {
        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);
        });
      }
      that.additem.children.push({
        id: String(new Date().getTime()),
        expand: true,
        level: that.additem.level + 1,
        isStore: 0,
        label: name,
        departmentName: name,
        addFlag: true,
        children: []
      });
      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;
      const flag = await that.delPost(item);
      // console.log('删除:', item, that.itemData);
      if (!flag) {
        // showMsg.showmsg('当前节点下有子节点，不可删除', 'warning');
        return false;
      }
      let key = '';
      that.itemData.forEach((ele, index) => {
        if (ele.id == item.id) {
          key = index;
        }
      });
      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) {
              // 加一个已加载标志
              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) {
      // const 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();
    }
  }
  /*  beforeDestroy() {} */
};
</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>
