<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-03-20 14:36:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-09 16:04:50
 -->
<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 flex">
                <el-input placeholder="搜索部门" maxlength="50" v-model="searchInput" class="w-225" @keyup.native="value => toInput(value, searchInput)" clearable @clear="clearInput"></el-input>
                <el-tooltip content="授权商户" placement="top">
                  <div class="cursor-pointer flex flex-align-center flex-pack-center" @click="toManage"><span class="iconfont iconshouquanyanzheng m-l-10 cursor-pointer"></span></div>
                </el-tooltip>
              </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="left-tree p-t-14">
                <contact-tree v-if="!searchInput" :depart-obj="departObj" :item-data="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-if="!searchData.length" 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 :depart-obj="departObj" @changeDepart="changeDepart"></new-depart-member>
            </div>
          </div>
        </div>
      </div>
    </div>
    <sync-dialog v-if="syncStatusData.syncStatus == 1 || syncStatusData.syncStatus == 2 || syncStatusData.syncStatus == 3" :sync-data="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 fetch from '@/api/contact.js';
const { getSyncCheck, refreshWx, getCompanyDepartList } = fetch;
import { _debounce } from '@/common/js/public';
export default {
  name: 'ContactsPage',
  components: {
    // navCrumb,
    contactTree,
    newDepartMember,
    syncDialog
  },
  data() {
    return {
      bgHeight: window.screen.availHeight - 288 + 'px',
      // 面包屑参数
      navpath: [
        {
          name: '首页',
          path: '/index'
        },
        {
          name: '通讯录',
          path: ''
        }
      ],
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',

      loading: true,
      refreshTag: false,
      searchInput: '',
      searchData: [],
      wxData: [], // 部门数据
      wxDataCopy: [], // 本地搜索使用
      selectData: {},
      departObj: {},
      // 同步状态
      syncStatusData: {
        syncStatus: 0
      },
      syncTime: null
    };
  },

  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';
  },
  methods: {
    /**
     * @description: 获取同步状态
     * @author: 无尘
     */
    getSyncStatus() {
      const that = this;
      getSyncCheck({})
        .then(res => {
          that.syncStatusData = res.result || {};
          if (!res.result || (res.result.syncStatus !== 1 && res.result.syncStatus !== 2 && res.result.syncStatus !== 3)) {
            window.clearInterval(that.syncTime);
            that.syncTime = null;
          }
          if (res.result.syncStatus == 4) {
            that.getTableList();
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 选中搜索的部门
     * @param {Object} item
     * @author: 无尘
     */
    selectSearch(item) {
      const that = this;
      that.departObj = item;
    },
    /**
     * @description: 刷新企业成员
     * @author: 无尘
     */
    toRefreshMember: _debounce(function() {
      const that = this;
      that.refreshTag = true;
      refreshWx({})
        .then(res => {
          that.refreshTag = false;
          // 同步后需要刷新数据
          that.getSyncStatus();
          that.syncTime = null;
          that.syncTime = window.setInterval(() => {
            that.getSyncStatus();
          }, 3000);
          that.$once('hook:beforeDestroy', () => {
            clearInterval(that.syncTime);
          });
        })
        .catch(function(error) {
          that.refreshTag = false;
        });
    }, 500),

    /**
     * @description: 点击 tree 数据
     * @param {Object} data
     * @author: 无尘
     */
    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);
          }
        }
      }
    },
    /**
     * @description: 点击子部门触发
     * @param {Object} obj
     * @author: 无尘
     */
    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;
    },
    /**
     * @description: 修改部门名称触发
     * @param {String} name
     * @author: 无尘
     */
    resetData(name) {
      const that = this;
      that.selectData.departmentName = name;
      that.departObj.departmentName = name;
    },
    /**
     * @description: 组织架构管理
     * @author: 无尘
     */
    toManage() {
      const that = this;
      that.$router.push('/authMerchant');
    },
    /**
     * 每次选中一个树中节点，把当前数据返回，
     * @description: 获取选中部门/门店数据
     * @param {Object} obj
     * @author: 无尘
     */
    getSelectData(obj) {
      const that = this;
      that.selectData = obj;
      that.departObj = obj;
    },
    getSearchSelectData(obj) {
      const that = this;
      obj.loading = false;
      that.departObj = obj;
    },
    /**
     * @description: 路由跳转
     * @param {String} path
     * @author: 无尘
     */
    changeRoute(path) {
      this.$router.push(path);
    },
    /**
     * @description: 输入
     * @param {Object} e
     * @param {String} value
     * @author: 无尘
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      if (!that.searchInput) {
        return false;
      }
      that.searchData = [];
      that.getSearchData();
    }, 500),
    // 搜索清除
    clearInput() {
      const that = this;
      that.searchData = [];
    },
    /**
     * @description:获取搜索数据
     * @author: 无尘
     */
    getSearchData() {
      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;
    },
    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;
    },
    /**
     * @description: 获取列表数据
     * @author: 无尘
     */
    getTableList() {
      const that = this;
      that.loading = true;
      const para = {
        search: that.searchInput || '', // 搜索字段
        // wxEnterpriseId: that.wxEnterpriseId(避免多企业登录，去掉)
      };
      getCompanyDepartList(para)
        .then(async res => {
          let resultData = [];
          let defalutData = {};
          if (!!res.result && res.result.length) {
            res.result.forEach(ele => {
              ele.loading = false;
              ele.expand = false;
              ele.children = [];
              ele.label = ele.departmentName;
              if (ele.parentDepartmentId == 0) {
                defalutData = ele;
              }
            });
            resultData = await that.treeData(JSON.parse(JSON.stringify(res.result)));
            resultData[0].expand = true;
            that.wxDataCopy = JSON.parse(JSON.stringify(res.result)) || [];
          }
          that.loading = false;
          that.departObj = defalutData;
          that.wxData = resultData || [];
        })
        .catch(function(error) {
          that.loading = false;
        });
    }
  },
  watch: {
    $route: {
      handler: function(to, from) {
        const that = this;
        window.clearInterval(that.syncTime);
        that.syncTime = null;
      },
      // 深度观察监听
      deep: true
    }
  }

};
</script>
<style type="text/less" lang="less" scoped>

.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: 20px 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 {
  margin-top: 12px;
  background: #f5f7fa;
  line-height: 28px;
  padding: 0 10px;
  box-sizing: border-box;
  cursor: pointer;
  .font-12 {
    font-size: 12px;
  }
}
</style>
