<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-03-20 14:36:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-08-26 10:05:01
 -->
<template>
  <div class="contacts-wrap common-set-wrap">
    <nav-crumb :navpath="navpath"> </nav-crumb>
    <div class="right-content">
      <div class="right-box" :style="{ 'min-height': bgHeight }" v-loading="loading">
        <div class="apps-content flex" :style="{ 'min-height': bgHeight }">
          <div class="apps-content-left border-box">
            <div class="left-tree-body border-box">
              <div class="left-tree-search">
                <el-input placeholder="搜索部门" maxlength="50" v-model="searchInput" class="w-225" @keyup.native="value => toInput(value, searchInput)" clearable @clear="clearInput"></el-input>
                <span class="iconfont iconshouquanyanzheng m-l-10 cursor-pointer" @click="toManage"></span>
              </div>
              <div class="help-body flex flex-space-between" @click="toRefreshMember"><span class="font-12 color-2f54eb">刷新企业成员</span><span class="font-12 color-2f54eb iconfont iconshuaxin1"></span></div>
              <!-- <div class="p-t-14">
                <el-button style="width: 100%;" :disabled="refreshTag" type="primary" @click="toRefreshMember">刷新企业成员</el-button>
              </div> -->
              <div class="left-tree p-t-14">
                <contact-tree v-if="!searchInput" :departObj="departObj" :itemData="wxData" v-model="wxData" @getSelectData="getSelectData"></contact-tree>
                <div v-if="searchInput" class="contact-search-body">
                  <ul v-if="searchData.length">
                    <li class="contact-li" v-for="(item, index) in searchData" :key="index + 'gic'">
                      <div :class="['li-cell cursor-pointer', departObj.departmentId == item.departmentId ? 'li-cell-active' : '']" @click="selectSearch(item)">
                        <div class="li-cell-p" :style="{ 'margin-left': 20 + 'px' }">
                          <span :class="['font-14 p-r-10 iconfont  iconqiye-tianchong', departObj.departmentId == item.departmentId ? 'color-2f54eb' : 'color-dedfe6']"></span><span class="font-14 color-606266 span-departName">{{ item.departmentName }}</span>
                        </div>
                      </div>
                    </li>
                  </ul>
                  <div v-else class="no-search-data font-14 color-909399">无结果</div>
                </div>
              </div>
            </div>
          </div>
          <div class="apps-content-right">
            <div class="content-right-body border-box" style="min-height: 100%;">
              <new-depart-member :departObj="departObj" @changeDepart="changeDepart"></new-depart-member>
            </div>
          </div>
        </div>
      </div>
    </div>
    <sync-dialog v-if="syncStatusData.syncStatus == 1 || syncStatusData.syncStatus == 2 || syncStatusData.syncStatus == 3" :syncData="syncStatusData"></sync-dialog>
    <!-- <vue-gic-footer></vue-gic-footer> -->
  </div>
</template>
<script>
import navCrumb from '@/components/nav/nav.vue';
import contactTree from '@/components/company/contact-tree.vue';
import newDepartMember from '@/components/company/new-depart-member.vue';
import syncDialog from '@/components/company/sync-dialog.vue';
import { getRequest } from '@/api/api';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
export default {
  name: 'reviewed',
  components: {
    navCrumb,
    contactTree,
    newDepartMember,
    syncDialog
  },
  data() {
    return {
      bgHeight: window.screen.availHeight - 288 + 'px',
      // 面包屑参数
      navpath: [
        {
          name: '首页',
          path: '/index'
        },
        {
          name: '通讯录',
          path: ''
        }
      ],
      loading: true,
      refreshTag: false,
      searchInput: '',
      searchData: [],
      wxData: [], // 部门数据
      wxDataCopy: [], //本地搜索使用
      selectData: {},
      departObj: {},
      // 同步状态
      syncStatusData: {
        syncStatus: 0
      },
      syncTime: null
    };
  },
  computed: {},
  methods: {
    /**
     * 获取同步状态
     */
    getSyncStatus() {
      const that = this;
      let para = {};
      getRequest('/haoban-manage3-web/department-sync-check', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.syncStatusData = resData.result || {};
            if (!resData.result || (resData.result.syncStatus !== 1 && resData.result.syncStatus !== 2 && resData.result.syncStatus !== 3)) {
              window.clearInterval(that.syncTime);
              that.syncTime = null;
            }
            if (resData.result.syncStatus == 4) {
              that.getTableList();
            }
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 选中搜索的部门
     */
    selectSearch(item) {
      const that = this;
      that.departObj = item;
    },
    /**
     * 刷新企业成员
     */
    toRefreshMember: _debounce(function() {
      const that = this;
      that.refreshTag = true;
      let para = {};
      getRequest('/haoban-manage3-web/sync-qywx', para)
        .then(res => {
          that.refreshTag = false;
          let resData = res.data;
          if (resData.errorCode == 1) {
            // 同步后需要刷新数据
            that.getSyncStatus();
            that.syncTime = null;
            that.syncTime = window.setInterval(() => {
              that.getSyncStatus();
            }, 3000);
            that.$once('hook:beforeDestroy', () => {
              clearInterval(that.syncTime);
            });
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.refreshTag = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }, 500),

    /**
     * 点击 tree 数据
     */
    resetCheckData(data) {
      const that = this;
      that.departObj = data;
    },

    async setParent(obj, copyData) {
      const that = this;
      for (let i = 0; i < copyData.length; i++) {
        if (obj.parentDepartmentId == copyData[i].departmentId) {
          copyData[i].expand = true;
          if (copyData[i].parentDepartmentId != 0) {
            await that.setParent(copyData[i], copyData);
          }
        }
      }
    },

    /**
     * 点击子部门触发
     */
    async changeDepart(obj) {
      const that = this;
      that.departObj = obj;
      that.searchInput = '';
      that.departObj.expand = true;
      // 重新组装树形部门
      let copyData = JSON.parse(JSON.stringify(that.wxDataCopy));

      for (let i = 0; i < copyData.length; i++) {
        if (that.departObj.parentDepartmentId == copyData[i].departmentId) {
          copyData[i].expand = true;
          if (copyData[i].parentDepartmentId != 0) {
            await that.setParent(copyData[i], copyData);
          }
        }
      }
      that.wxData = await that.treeData(JSON.parse(JSON.stringify(copyData)));
      that.wxData[0].expand = true;
    },
    /**
     * 获取下级数据
     */
    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 addDepart(obj) {
      const that = this;
      that.$set(that.departObj, 'hasSonNode', true);
      that.$set(that.departObj, 'loading', false);
      that.departObj.children = await that.getChildData(that.departObj);
      that.$forceUpdate();
    },
    /**
     * 修改部门名称触发
     */
    resetData(name) {
      const that = this;
      that.selectData.departmentName = name;
      that.departObj.departmentName = name;
    },

    /**
     * 组织架构管理
     */
    toManage() {
      const that = this;
      that.$router.push('/authMerchant');
    },
    /**
     * 每次选中一个树中节点，把当前数据返回，
     * 获取选中部门/门店数据
     */
    getSelectData(obj) {
      const that = this;
      // console.log(obj);
      // obj.label = '测试';
      that.selectData = obj;
      that.departObj = obj;
    },
    getSearchSelectData(obj) {
      const that = this;
      obj.loading = false;
      that.departObj = obj;
    },
    /**
     * 路由跳转
     */
    changeRoute(path) {
      this.$router.push(path);
    },
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      if (!that.searchInput) {
        return false;
      }
      that.searchData = [];
      that.getSearchData();
    }, 500),
    // 搜索清除
    clearInput() {
      const that = this;
      that.searchData = [];
      // that.groupData = JSON.parse(JSON.stringify(that.groupDataCopy));
      /* that.currentPage = 1;
      that.getTableList(); */
    },
    /**
     * 获取搜索数据
     */
    getSearchData(val) {
      const that = this;
      that.loading = true;
      // 前端搜索
      let groupArr = [];
      groupArr = that.wxDataCopy.filter(ele => ele.departmentName.indexOf(that.searchInput) != -1);
      that.searchData = groupArr || [];
      that.loading = false;
      return false;
      let para = {
        keyWord: that.searchInput || '' // 搜索字段
      };
      getRequest('/haoban-manage3-web/department-list-level', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.departObj = resData.result[0];
            that.wxData = resData.result || [];
            // console.log(that.wxData);
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    treeData(data) {
      let tree = data.filter(father => {
        //循环所有项
        let branchArr = data.filter(child => {
          return father.departmentId == child.parentDepartmentId; //返回每一项的子级数组
        });
        if (branchArr.length > 0) {
          father.hasSonNode = true;
          father.children = branchArr; //如果存在子级，则给父级添加一个children属性，并赋值
        } else {
          father.hasSonNode = false;
        }
        return father.parentDepartmentId == 0; //返回第一层
      });
      return tree;
    },
    /**
     * 获取列表数据
     */
    getTableList(val) {
      const that = this;
      that.loading = true;
      let para = {
        keyWord: that.searchInput || '', // 搜索字段
        isStore: 0, // 当前页
        parentId: '' // 一页显示个数
      };
      getRequest('/haoban-manage3-web/department-list-cache', para)
        .then(async res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            let resultData = [];
            let defalutData = {};
            if (!!resData.result && resData.result.length) {
              resData.result.forEach(ele => {
                ele.loading = false;
                ele.expand = false;
                ele.children = [];
                ele.label = ele.departmentName;
                if (ele.parentDepartmentId == 0) {
                  defalutData = ele;
                }
              });
              // console.time('a1');
              resultData = await that.treeData(JSON.parse(JSON.stringify(resData.result)));
              // console.timeEnd('a1');
              resultData[0].expand = true;
              that.wxDataCopy = JSON.parse(JSON.stringify(resData.result)) || [];
            }
            that.loading = false;
            that.departObj = defalutData;
            that.wxData = resultData || [];
            // console.log(that.wxData);
            return false;
          }
          that.loading = false;
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loading = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    searchInput(val) {
      // this.$refs.groupTree.filter(val);
    },
    $route: {
      handler: function(to, from) {
        const that = this;
        window.clearInterval(that.syncTime);
        that.syncTime = null;
      },
      // 深度观察监听
      deep: true
    }
  },
  async beforeMount() {
    const that = this;
    await that.getTableList();
  },
  mounted() {
    const that = this;
    that.getSyncStatus();
    that.syncTime = null;
    that.syncTime = window.setInterval(() => {
      that.getSyncStatus();
    }, 3000);
    that.$once('hook:beforeDestroy', () => {
      clearInterval(that.syncTime);
    });
    document.documentElement.style.backgroundColor = '#f0f2f5';
  },
  beforeDestroy() {
    const that = this;
    window.clearInterval(that.syncTime);
    that.syncTime = null;
  },
  destroyed() {
    document.documentElement.style.backgroundColor = '#fff';
  }
};
</script>
<style type="text/less" lang="less" scoped>
.bg-82C5FF {
  background: #82c5ff;
}
.color-508CEE {
  color: #508cee;
}
.color-FF585C {
  color: #ff585c;
}
.line-h-18 {
  line-height: 18px;
}
.w-225 {
  width: 225px;
}
.tooltip-text {
  width: 100%;
  white-space: pre-wrap;
  word-break: break-all;
}
.contacts-wrap {
  height: 100%;
}

.right-content {
  /*width: 100%;*/
  padding: 0 20px 20px 20px;
  min-height: calc(100% - 160px);
  .right-box {
    background: #fff;
    min-height: 500px;
    padding: 0px;
    .apps-content {
      .apps-content-left {
        min-width: 293px;
        width: 293px;
        height: 100%;
        max-height: 1955px;
        background: #fff;
        overflow-x: hidden;
        overflow-y: auto;
        .left-tree-body {
          width: 100%;
          padding: 20px 12px;
          .iconshouquanyanzheng {
            display: inline-block;
            vertical-align: middle;
            font-size: 24px;
            color: #c0c4cc;
            &:hover {
              background-color: #eef3f9;
              color: #2f54eb;
            }
          }
        }
      }
      .apps-content-right {
        width: calc(100% - 303px);
        max-height: 1955px;
        padding-left: 10px;
        background: #f0f2f5;
        .content-right-body {
          width: 100%;
          padding: 20px;
          background: #fff;
        }
        .daily-set-wrap {
          height: 100%;
          background: #fff;
        }
        .app-detail-wrap {
          height: 100%;
          background: #fff;
        }
        .common-set-wrap {
          height: 100%;
          background: #fff;
        }
      }
    }
  }
}
.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: #2f54eb;
    }
    .iconqiye-tianchong {
      color: #2f54eb;
    }
    .color-606266 {
      &.color-fff {
        color: #f4f6fe;
      }
    }
  }
}
.no-search-data {
  height: 32px;
  line-height: 32px;
  text-align: center;
}
.contact-li {
  .li-cell {
    &:hover {
      background: #f4f6fe;
      .span-departName {
        color: #303133;
      }
      .color-606266 {
        &.color-fff {
          color: #f4f6fe;
        }
      }
    }
  }
}
.help-body {
  .font-12 {
    font-size: 12px;
  }
}
</style>
