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

import contactTree from '/components/company/contact-tree.vue';
-->
<template>
  <ul class="">
    <!-- <draggable :list="itemData" class="wx-component" :options="rightOption" @input="emitter" @change="changeData"> -->
    <li class="contact-li" v-for="(item, index) in itemData" :key="index + 'gic'">
      <div :class="['li-cell cursor-pointer', departObj.departmentId == item.departmentId ? 'li-cell-active' : '']" @click="toggleExpand(item)">
        <div class="li-cell-p" :style="{ 'margin-left': (item.level + 1) * 20 + 'px' }">
          <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 p-r-10 iconfont', !!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 span-departName">{{ item.departmentName }}</span>
        </div>
      </div>
      <li-row v-if="item.expand" :departObj="departObj" :itemData="item.children" @getSelectData="getSelectData"></li-row
      ><!-- v-show="!!item.children.length && item.expand" -->
    </li>
    <!-- </draggable> -->
  </ul>
</template>
<script>
import localforage from 'localforage';
// import draggable from 'vuedraggable';
// import showMsg from '@/common/js/showmsg';
import { getRequest } from '@/api/api';
import errMsg from '@/common/js/error';
export default {
  name: 'li-row',
  components: {
    // draggable
  },
  props: {
    value: {
      type: [Object, Array],
      default() {
        return [];
      }
    },
    itemData: {
      type: [Object, Array],
      default() {
        return [];
      }
    },
    // 选中节点
    departObj: {
      type: Object,
      default() {
        return {
          departmentId: '',
          departmentName: '',
          wxDepartmentId: '',
          parentId: '',
          isStore: '',
          staffCount: '',
          bindFlag: '',
          loading: false
        };
      }
    }
  },
  data() {
    return {
      rightOption: {
        group: {
          name: 'people',
          pull: true,
          put: true
        },
        sort: true
      }
    };
  },
  computed: {},
  methods: {
    /**
     *  改变数组数据
     */
    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.isStore == 0 && !item.children.length) {
        item.loading = true;
        item.children = await that.getChildData(item);
        item.loading = false;
      }
      // 只有展开且不是门店的才会保存
      if (item.expand && !item.isStore) {
        localforage.setItem(item.departmentId, item);
      }
      if (!item.expand) {
        localforage.removeItem(item.departmentId);
      }
      that.$emit('getSelectData', item);
      that.$forceUpdate();
    },
    /**
     * 获取选中部门/门店数据
     */
    getSelectData(obj) {
      const that = this;
      that.selectData = obj;
      that.$emit('getSelectData', obj);
    },

    /**
     * 获取下级数据
     */
    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) {
                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) {
      // const that = this;
      return new Promise((resolve, reject) => {
        localforage
          .getItem(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].isStore == 0 && that.itemData[index].hasSonNode == true) {
          that.itemData[index].expand = 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) {
        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;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  .color-606266 {
    &.color-fff {
      color: #fff;
    }
  }
  &.li-cell-active {
    background: #f4f6fe;
    .span-departName {
      color: #303133;
    }
    .color-606266 {
      &.color-fff {
        color: #f4f6fe;
      }
    }
  }
}
.contact-li {
  .li-cell {
    &:hover {
      background: #f4f6fe;
      .span-departName {
        color: #303133;
      }
      .color-606266 {
        &.color-fff {
          color: #f4f6fe;
        }
      }
    }
  }
}

.w-110 {
  width: 110px;
}

.w-320 {
  width: 320px;
}

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

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