<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-03-20 14:36:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-03-23 10:45:57
 -->
<template>
  <div class="my-customer-wrap common-set-wrap">
    <nav-crumb :navpath="navpath"> </nav-crumb>
    <div class="right-content">
      <div class="right-box" :style="{ 'min-height': bgHeight }">
        <div class="apps-content flex">
          <div class="apps-content-left">
            <div class="content-gic-title font-16 color-303133 text-left">GIC门店架构</div>
            <div class="content-gic flex">
              <div class="gic-content-business">
                <ul>
                  <li class="cursor-pointer" v-for="(item, index) in enterpriseData" :key="index + 'li'" @click="selectEnterprise(item)">
                    <div class="ul-li-cell flex">
                      <div class="cell-img">
                        <img :src="item.enterpriseLogo" alt="img" />
                      </div>
                      <div class="cell-info">
                        <div class="cell-info-name font-14 color-303133">
                          <span class="gic-name">{{ item.enterpriseName }}</span
                          ><span class="gic-version">{{ item.version }}</span>
                        </div>
                        <div class="cell-info-version font-12 color-909399">{{ item.nodeCount }}</div>
                      </div>
                    </div>
                  </li>
                </ul>
                <div class="add-enterprise cursor-pointer text-center" @click="showAddDialog"><span class="iconfont icontianjiajiahaowubiankuang font-12 color-2f54eb"></span><span class="font-12 color-2f54eb p-l-10">新建GIC商户授权</span></div>
              </div>
              <div class="gic-content-depart">
                <org-tree v-if="gicData.length" :wxData="wxData" :itemData="gicData"></org-tree>
                <div v-else class="font-14 color-606266">暂无数据</div>
              </div>
            </div>
          </div>
          <div class="apps-content-right">
            <div class="content-wx-title flex flex-space-between">
              <span class="font-16 color-303133 text-left">企业微信组织架构</span>
              <el-button type="text" @click="toRecycle">回收站（{{ recycleCount }}）</el-button>
            </div>
            <div class="content-wx">
              <ul class="" style="position: relative;">
                <li v-for="(item, index) in wxData" :key="index + 'wx'">
                  <div class="li-cell cursor-pointer" @click="toggleExpand(item)">
                    <div class="li-cell-inner flex flex-space-between boder-box p-r-20" :style="{ 'padding-left': (item.level + 1) * 20 + 'px' }">
                      <div class="tree-left">
                        <span v-if="!item.isStore" :class="['font-12 color-606266', 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" type="text" @click.stop="addChild(item)">添加子部门</el-button>
                        <el-button type="text" @click.stop="modChild(item)">修改名称</el-button>
                      </div>
                    </div>
                  </div>
                  <wx-tree v-if="item.expand" :itemObj="item" :itemData="item.children" v-model="item.children" @changeParent="changeParent" @refreshRecycle="refreshRecycle"></wx-tree>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div class="save-body m-t-10">
          <div v-if="syncDate" class="change-title text-center font-14 color-303133">好办组织结构于{{ syncDate | formatTimeStamp }} 发生改动</div>
          <div class="text-center m-t-15">
            <el-button type="primary" @click="saveData">保存更改并同步至企业微信</el-button>
          </div>
        </div>
      </div>
      <add-enterprise v-if="addShow" @refreshData="refreshData"></add-enterprise>
      <add-depart v-if="addDepartShow" :departObj="modItem" @refreshData="refreshDepartData"></add-depart>
    </div>
    <!-- <vue-gic-footer></vue-gic-footer> -->
  </div>
</template>
<script>
import navCrumb from '@/components/nav/nav.vue';
import addEnterprise from '@/components/company/add-enterprise.vue';
import orgTree from '@/components/company/org-tree.vue';
import wxTree from '@/components/company/wx-tree.vue';
import addDepart from '@/components/company/add-depart.vue';
import { getRequest, postRequest, postJson } from '@/api/api';
import errMsg from '@/common/js/error';
import showMsg from '@/common/js/showmsg';
import { _debounce } from '@/common/js/public';
import localforage from 'localforage';
export default {
  name: 'reviewed',
  data() {
    return {
      bgHeight: window.screen.availHeight - 288 + 'px',
      loading: null,
      // 面包屑参数
      navpath: [
        {
          name: '首页',
          path: '/index'
        },
        {
          name: '通讯录',
          path: '/contactsList'
        },
        {
          name: '组织架构管理',
          path: ''
        }
      ],
      wxEnterpriseId: JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId,
      addShow: false,
      enterpriseData: [],
      gicData: [],
      wxData: [
        //{
        //     id: 2,
        //     level: 1,
        //     expand: false,
        //     isStore: 0,
        //     label: '总部2',
        //     bindFlag: 0,
        //     children: [{
        //       id: 22,
        //       level: 2,
        //       expand: false,
        //       isStore: 1,
        //       label: '总部2',
        //       bindFlag: 1,
        //       children: []
        //     }]
        //   }
      ],
      addDepartShow: false,
      additem: {},
      modItem: {},
      recycleCount: 0,
      syncDate: '',
      syncKey: '',
      syncTime: null
    };
  },
  computed: {},
  methods: {
    /**
     * 触发父级
     */
    changeParent(itemObj) {
      // const that = this;
      console.log('触发父(顶)级:', itemObj);
    },
    refreshRecycle() {
      const that = this;
      that.getRecycleCount();
    },
    /**
     * 保存
     */
    saveData: _debounce(function() {
      const that = this; //!that.$store.state.addDepartment.length &&
      /* if (!that.$store.state.addDepartment.length && !that.$store.state.editDepartment.length) {
        showMsg.showmsg('暂无修改，无法同步', 'warning');
        return false;
      } */
      // 去除重复添加数据
      // 1.
      if (that.$store.state.addDepartment.length) {
        let hash = {};
        let arr = JSON.parse(JSON.stringify(that.$store.state.addDepartment));
        arr = arr.reduce(function(item, next) {
          hash[next.departmentId] ? '' : (hash[next.departmentId] = true && item.push(next));
          return item;
        }, []);
        console.log(arr);
        that.$store.dispatch('clearAddData');
        arr.forEach(ele => {
          that.$store.dispatch('saveAddInfo', ele);
        });
      }
      // 去除重复添加数据
      // 1.
      if (that.$store.state.editDepartment.length) {
        let hash = {};
        let arr = JSON.parse(JSON.stringify(that.$store.state.editDepartment));
        arr = arr.reduce(function(item, next) {
          hash[next.departmentId] ? '' : (hash[next.departmentId] = true && item.push(next));
          return item;
        }, []);
        that.$store.dispatch('clearEditData');
        arr.forEach(ele => {
          that.$store.dispatch('saveEditInfo', ele);
        });
      }

      console.log('同步数据：', that.$store.state.addDepartment, that.$store.state.editDepartment);
      that.postSaveData();
    }, 300),
    postSaveData() {
      const that = this;
      that.loading = that.$loading({
        lock: true,
        text: '此过程处理时间可能会较久，请耐心等待!',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let para = {
        addDepartment: that.$store.state.addDepartment,
        editDepartment: that.$store.state.editDepartment
      };
      postJson('/haoban-manage3-web/department-batch-sync', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!resData.result) {
              that.loading.close();
              return false;
            }
            // 清空
            that.$store.dispatch('clearTreeData');
            that.syncKey = resData.result;
            that.syncTime = setInterval(() => {
              that.postSyncData();
            }, 3000);
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loading.close();
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    postSyncData() {
      const that = this;
      let para = {
        syncKey: that.syncKey
      };
      postRequest('/haoban-manage3-web/department-batch-sync-success', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (resData.result) {
              clearInterval(that.syncTime);
              that.syncTime = null;
              that.loading.close();
              showMsg.showmsg('同步成功', 'success');
              // 同步后需要刷新数据
              that.wxData = [];
              that.getWxData();
            }
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loading.close();
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 选择企业
     */
    selectEnterprise(item) {
      const that = this;
      that.getGicData(item);
    },
    getGicData(item) {
      const that = this;
      let para = {
        enterpriseId: item.enterpriseId //
      };
      getRequest('/haoban-manage3-web/unbind-department-list', 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 = 0;
                ele.label = ele.departmentName;
                ele.enterpriseId = item.enterpriseId;
              });
            }
            that.gicData = resData.result || [];
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    getWxData() {
      const that = this;
      let para = {
        parentId: '',
        isStore: 0
      };
      getRequest('/haoban-manage3-web/department-list-level', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result && resData.result.length) {
              resData.result.forEach(ele => {
                ele.loading = false;
                ele.expand = false;
                ele.children = [];
                ele.level = 0;
                ele.label = ele.departmentName;
              });
            }
            that.wxData = resData.result || [];
            that.getLocalData();
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 添加子部门
     */
    addChild(item) {
      const that = this;
      // console.log('添加：', item);
      that.addDepartShow = true;
      that.additem = item;
    },
    /**
     * 修改名称
     */
    modChild(item) {
      const that = this;
      // console.log('修改：', item);
      that.modItem = item;
      that.addDepartShow = true;
      that.$forceUpdate();
    },

    async refreshDepartData(name, mod) {
      const that = this;
      that.addDepartShow = 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,
        parentId: that.additem.departmentId,
        parentDepartmentId: that.additem.departmentId,
        addFlag: true,
        children: []
      };
      that.additem.children.push(childObj);
      // 增加的字段
      that.$store.dispatch('saveAddInfo', that.additem);
      that.$store.dispatch('saveAddInfo', childObj);
      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.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.$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.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('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.wxData.length; index++) {
        const flag = await that.checkLocal(that.wxData[index]);
        if (flag) {
          that.wxData[index].expand = true;
          if (that.wxData[index].isStore == 0 && that.wxData[index].hasSonNode == true) {
            that.wxData[index].loading = true;
            that.wxData[index].children = await that.getChildData(that.wxData[index]);
            that.wxData[index].loading = false;
          }
        }
      }
    },
    /**
     * 新增企业
     */
    showAddDialog() {
      const that = this;
      that.addShow = true;
    },
    refreshData(res) {
      const that = this;
      that.addShow = false;
      if (res == 'close') {
        return;
      }
      that.getTableList();
    },
    /**
     * 跳转回收站
     */
    toRecycle() {
      const that = this;
      that.changeRoute('/recycle');
    },
    /**
     * 路由跳转
     */
    changeRoute(path) {
      this.$router.push(path);
    },
    /**
     * 获取回收站数据
     */
    getRecycleCount(val) {
      const that = this;
      let para = {};
      getRequest('/haoban-manage3-web/department-recycle-count', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.recycleCount = resData.result.count || 0;
            that.syncDate = resData.result.syncDate || '';
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 获取企业列表数据
     */
    getTableList(val) {
      const that = this;
      let para = {};
      getRequest('/haoban-manage3-web/wx-enterprise-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.enterpriseData = resData.result || [];
            if (!!resData.result && resData.result.length) {
              that.getGicData(resData.result[0]);
            }
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {},
  mounted() {
    const that = this;
    that.getTableList();
    that.getWxData();
    that.getRecycleCount();
    document.documentElement.style.backgroundColor = '#f0f2f5';
  },
  destroyed() {
    document.documentElement.style.backgroundColor = '#fff';
  },
  components: {
    navCrumb,
    addEnterprise,
    orgTree,
    wxTree,
    addDepart
  }
};
</script>
<style type="text/scss" lang="scss" scoped>
.bg-82C5FF {
  background: #82c5ff;
}
.color-508CEE {
  color: #508cee;
}
.color-FF585C {
  color: #ff585c;
}
.line-h-18 {
  line-height: 18px;
}
.tooltip-text {
  width: 100%;
  white-space: pre-wrap;
  word-break: break-all;
}
.my-customer-wrap {
  height: 100%;
}
.right-content {
  /*width: 100%;*/
  padding: 0 20px 20px 20px;
  min-height: calc(100% - 160px);
  .right-box {
    min-height: 500px;
    padding: 0px;
    .save-body {
      width: 100%;
      height: 120px;
      padding: 32px 0 22px 0;
      background: #fff;
      box-sizing: border-box;
    }
    .apps-content {
      .apps-content-left {
        width: 50%;
        height: 100%;
        background: #fff;
        overflow-x: hidden;
        overflow-y: auto;
        .content-gic-title {
          height: 46px;
          line-height: 46px;
          padding: 0 20px;
          box-sizing: border-box;
          border-bottom: 1px solid #e4e7ed;
        }
        .content-gic {
          min-height: calc(100% - 160px);
          .gic-content-business {
            position: relative;
            width: 262px;
            height: calc(100vh - 277px);
            padding: 0 20px 52px 20px;
            box-sizing: border-box;
            border-right: 1px solid #e4e7ed;
            ul {
              height: 100%;
              overflow-x: hidden;
              overflow-y: auto;
              li {
                margin-top: 20px;
              }
            }
            .add-enterprise {
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
              height: 48px;
              line-height: 48px;
              box-shadow: 0px -1px 4px 0px rgba(0, 0, 0, 0.12);
              background: #fff;
              z-index: 1;
              .iconfont {
                font-size: 13px;
              }
            }
            .ul-li-cell {
              .cell-img {
                width: 52px;
                min-width: 52px;
                max-width: 52px;
                height: 52px;
                border-radius: 2px;
                border: 1px solid rgba(228, 231, 237, 1);
                box-sizing: border-box;
                img {
                  width: 100%;
                }
              }
              .cell-info {
                padding-left: 10px;
                box-sizing: border-box;
                .cell-info-name {
                  height: 37px;
                  white-space: pre-wrap;
                  word-break: break-all;
                }
                .gic-name {
                  font-size: 14px;
                  color: #303133;
                  line-height: 18px;
                }
                .gic-version {
                  display: inline-block;
                  padding: 2px 5px;
                  margin-left: 5px;
                  background: rgba(255, 241, 240, 1);
                  border-radius: 2px;
                  border: 1px solid rgba(255, 163, 158, 1);
                  font-size: 10px;
                  color: #f5222d;
                }
              }
            }
          }
          .gic-content-depart {
            position: relative;
            padding: 20px;
            box-sizing: border-box;
            height: calc(100vh - 277px);
            overflow-x: hidden;
            overflow-y: auto;
          }
        }
      }
      .apps-content-right {
        width: 50%;
        height: 100%;
        margin-left: 10px;
        background: #fff;
        .content-wx-title {
          height: 46px;
          line-height: 46px;
          padding: 0 20px;
          box-sizing: border-box;
          border-bottom: 1px solid #e4e7ed;
        }
        .content-wx {
          position: relative;
          height: calc(100vh - 277px);
          overflow-x: hidden;
          overflow-y: auto;
          padding: 10px 0 20px 0;
          box-sizing: border-box;
          .li-cell {
            min-height: 26px;
            line-height: 26px;
            .li-cell-inner {
              line-height: 33px;
            }
            .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;
              }
            }
          }
        }
      }
    }
  }
}
</style>
