<!--
 * @Descripttion : 当前组件信息
 * @Author       : 无尘
 * @Date         : 2020-02-13 14:02:22
 * @LastEditors: 无尘
 * @LastEditTime: 2020-05-19 15:06:22
 * @FilePath     : \Hapi-demoj:\公司\haoban-3\src\components\company\depart-list.vue
 -->
<!--
  <depart-list :departObj="departObj" @resetData="resetData" @changeDepart="changeDepart" @addDepart="addDepart"></depart-list>
  import departList from '@/components/company/depart-list.vue';
 -->
<template>
  <div class="depart-list-body">
    <div class="depart-name-wrap m-b-20">
      <div class="flex flex-space-between">
        <div>
          <div aria-label="Breadcrumb" role="navigation" class="el-breadcrumb m-b-10">
            <span class="el-breadcrumb__item" v-for="(item, index) in navData" :key="index + 'nav'"
              ><span role="link" class="el-breadcrumb__inner is-link" @click="changeDepart(item, index)"
                ><span class="el-breadcrumb__inner is-link font-12  color-606266">
                  {{ item.departmentName }}
                </span></span
              ><i v-if="index != navData.length - 1" class="el-breadcrumb__separator el-icon-arrow-right"></i
            ></span>
          </div>
          <div class="depart-name">
            <span class="font-16 color-303133 font-w-600">{{ departObj.departmentName }}</span>
            <el-popover v-if="!departObj.bindFlag" placement="top" style="min-width: 192px" v-model="nameVisible">
              <limitInput :inputWidth="180" :inputValue.sync="departmentName" :holder="'请输入部门名称'" :getByType="'char'" :maxLength="32"> </limitInput>
              <div style="text-align: right; margin: 12px 0 0 0">
                <el-button size="mini" type="text" @click="cancelMod">取消</el-button>
                <el-button type="primary" size="mini" @click="toMod">确定</el-button>
              </div>
              <span slot="reference"><span class="cursor-pointer iconfont iconchangyongicon- color-909399"></span></span>
            </el-popover>
          </div>
          <div class="depart-id font-12 color-909399">ID：{{ departObj.departmentId }}</div>
        </div>
        <div class="to-log flex m-t-20">
          <el-tooltip content="通讯录日志" placement="top">
            <div class="log-icon flex flex-align-center flex-pack-center cursor-pointer " @click="toLog"><span class="font-14 iconfont icontongxunlu color-909399"></span></div>
          </el-tooltip>
          <div class="to-log-btn font-12 color-2f54eb cursor-pointer" @click="toShowTip">查看帮助提示</div>
        </div>
      </div>
    </div>
    <div class="depart-children-list border-box m-t-18">
      <div class="depart-children-title"><span class="iconfont iconbumen color-303133"></span><span class="font-16 color-303133 font-w-600 p-l-5">下级部门</span></div>
      <div class="depart-condition-wrap flex flex-space-between m-t-20">
        <el-input placeholder="请输入部门名称/ID" v-model="searchInput" class="w-274" @keyup.native="value => toInput(value, searchInput)" clearable @clear="clearInput"></el-input>
        <el-button type="primary" @click="addChildPart">新建子部门</el-button>
      </div>
      <div class="m-t-20">
        <el-table class="select-table" ref="multipleTable" :data="tableData" tooltip-effect="dark" :style="{ width: '100%', minHeight: tableH }">
          <el-table-column class="cursor-pointer" label="部门名称" show-overflow-tooltip>
            <template slot-scope="scope"
              ><div class="cursor-pointer" @click="getChildren(scope.row)">{{ scope.row.departmentName || '--' }}（{{ scope.row.staffCount }}）</div></template
            >
          </el-table-column>
          <el-table-column class="cursor-pointer" prop="" label="企业微信部门ID" show-overflow-tooltip>
            <template slot-scope="scope">
              <div class="cursor-pointer" @click="getChildren(scope.row)">{{ scope.row.wxDepartmentId || '--' }}</div></template
            >
          </el-table-column>
          <el-table-column class="cursor-pointer" prop="" label="" show-overflow-tooltip>
            <template slot-scope="scope">
              <div class="cursor-pointer" @click="getChildren(scope.row)"><span class="iconfont iconnavigate_next inline-block cursor-pointer"></span></div>
            </template>
          </el-table-column>
        </el-table>
        <div class="block common-wrap__page text-right m-t-24" v-if="tableData.length != 0">
          <dm-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout="total,  prev, pager, next, jumper" :total="total"> </dm-pagination>
        </div>
      </div>
    </div>
    <!-- 新增子部门 -->
    <el-dialog width="600px" title="新增子部门" :visible.sync="partVisible" append-to-body :before-close="handleClose">
      <el-form :model="partForm" :rules="rules" ref="form" label-width="100px" class="dialog-form">
        <el-form-item label="部门名称" prop="departmentName">
          <limitInput :inputWidth="440" :inputValue.sync="partForm.departmentName" :holder="'请输入部门名称'" :getByType="'char'" :maxLength="32"> </limitInput>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取消</el-button>
        <el-button type="primary" @click="submitForm('form')">确定</el-button>
      </div>
    </el-dialog>
    <help-tip v-if="tipShow" @toCloseTip="toCloseTip"></help-tip>
  </div>
</template>
<script>
import helpTip from '@/components/company/help-tip.vue';
import { _debounce } from '@/common/js/public';
import { getRequest, postRequest } from '@/api/api';
import errMsg from '@/common/js/error';
import showMsg from '@/common/js/showmsg';
import limitInput from '@/components/limit-input.vue';
export default {
  name: 'depart-list',
  components: {
    limitInput,
    helpTip
  },
  props: {
    departObj: {
      type: Object,
      default() {
        return {
          departmentId: '',
          departmentName: '',
          wxDepartmentId: '',
          parentId: '',
          isStore: '',
          staffCount: '',
          bindFlag: ''
        };
      }
    }
  },
  data() {
    return {
      nameVisible: false,
      departmentName: this.departObj.departmentName || '',
      searchInput: '',
      // 分页参数
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      // 新增
      partVisible: false,
      rules: {
        departmentName: [
          {
            required: true,
            message: '请输入部门名称',
            trigger: 'blur'
          }
        ]
      },
      partForm: {
        departmentName: ''
      },
      tipShow: false,
      navData: []
    };
  },
  methods: {
    changeDepart(item, index) {
      const that = this;
      if (index == that.navData.length - 1) {
        return false;
      }
      that.$emit('changeDepart', item);
    },
    /**
     * 获取面包屑
     */
    toGetNavData() {
      const that = this;
      let params = {
        departmentId: that.departObj.departmentId
      };
      postRequest('/haoban-manage3-web/department-chain', params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.navData = resData.result || [];
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取同步状态
     */
    getStatus() {
      const that = this;
      return new Promise((resolve, reject) => {
        let para = {};
        getRequest('/haoban-manage3-web/department-sync-check', para)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              resolve(resData.result);
              return false;
            }
            resolve(false);
            errMsg.errorMsg(resData);
          })
          .catch(function(error) {
            resolve(false);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },
    toLog() {
      window.open('/haoban-3/#/syncLog');
    },
    toShowTip() {
      const that = this;
      that.tipShow = true;
    },
    toCloseTip() {
      const that = this;
      that.tipShow = false;
    },
    /**
     * 取消
     */
    cancelMod() {
      const that = this;
      that.departmentName = '';
      that.nameVisible = false;
    },
    async toMod() {
      const that = this;
      const tag = await that.getStatus();
      if (!!tag && (tag.syncStatus == 0 || tag.syncStatus == 1 || tag.syncStatus == 2 || tag.syncStatus == 3 || tag.syncStatus == 5)) {
        showMsg.showmsg('通讯录同步中，暂无法操作', 'warning');
        return false;
      }
      if (!that.departmentName) {
        showMsg.showmsg('请输入部门名称！', 'warning');
        return false;
      }
      // let obj = JSON.parse(JSON.stringify(that.departObj));
      // obj.departmentName = that.departmentName;
      const flag = await that.postMod();
      if (!flag) {
        return false;
      }
      that.$emit('resetData', that.departmentName);
      that.nameVisible = false;
    },
    postMod() {
      const that = this;
      let params = {
        parentId: that.departObj.parentDepartmentId,
        departmentId: that.departObj.departmentId,
        departmentName: that.departmentName
      };

      return new Promise((resolve, reject) => {
        postRequest('/haoban-manage3-web/department-edit', params)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              resolve(true);
              showMsg.showmsg('修改成功！', 'success');
              return false;
            }
            resolve(false);
            errMsg.errorMsg(resData);
          })
          .catch(function(error) {
            resolve(false);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },

    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    }, 500),
    // 搜索清除
    clearInput() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     * 获取子部门
     */
    getChildren(item) {
      const that = this;
      that.$emit('changeDepart', item);
      // that.currentPage = 1;
      // that.getTableList();
    },

    handleClose(done) {
      const that = this;
      that.$refs['form'].resetFields();
      that.partVisible = false;
      done();
    },
    cancel() {
      const that = this;
      that.$refs['form'].resetFields();
      that.partVisible = false;
    },

    /**
     * 新建子部门
     */
    async addChildPart(item) {
      const that = this;
      const tag = await that.getStatus();
      if (!!tag && (tag.syncStatus == 0 || tag.syncStatus == 1 || tag.syncStatus == 2 || tag.syncStatus == 3 || tag.syncStatus == 5)) {
        showMsg.showmsg('通讯录同步中，暂无法操作', 'warning');
        return false;
      }
      that.partVisible = true;
    },
    /**
     * 确定授权
     */
    submitForm(form) {
      const that = this;
      that.$refs[form].validate(valid => {
        if (valid) {
          that.toAddPost();
        } else {
          return false;
        }
      });
    },
    toAddPost() {
      const that = this;
      let params = {
        parentId: that.departObj.departmentId,
        departmentName: that.partForm.departmentName
      };
      postRequest('/haoban-manage3-web/department-add', params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('添加成功', 'success');
            that.currentPage = 1;
            that.getTableList();
            // 是否需要更新左侧 tree
            that.partVisible = false;
            resData.result.children = [];
            resData.result.expand = false;
            resData.result.level = that.departObj.level + 1;
            resData.result.label = resData.result.departmentName;
            that.$emit('addDepart', resData.result);
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 分页---页码变化
     */
    handleSizeChange(val) {
      const that = this;
      that.currentPage = 1;
      that.pageSize = val;
      that.getTableList();
    },

    /**
     * 分页---当前页变化
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.getTableList();
    },
    /**
     * 获取列表数据
     */
    getTableList() {
      const that = this;
      let para = {
        parentId: that.departObj.departmentId,
        isStore: that.departObj.isStore,
        keyWord: that.searchInput || '', // 搜索字段
        pageNum: that.currentPage, // 当前页
        pageSize: that.pageSize // 一页显示个数
      };
      getRequest('/haoban-manage3-web/department-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.tableData = resData.result.list || [];
            that.total = resData.result.total;
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    departObj(newData, oldData) {
      const that = this;
      if (Object.keys(newData)) {
        that.departmentName = newData.departmentName || '';
        that.currentPage = 1;
        that.getTableList();
        that.toGetNavData();
      }
    }
  },
  mounted() {
    const that = this;
    if (Object.keys(that.departObj)) {
      that.currentPage = 1;
      that.getTableList();
      that.toGetNavData();
    }
  }
};
</script>
<style lang="less" scoped>
.m-b-10 {
  margin-bottom: 10px;
}
.el-breadcrumb__inner.is-link:hover,
.el-breadcrumb__inner a:hover {
  color: #2f54eb;
}
.log-icon {
  width: 28px;
  height: 28px;
  border-radius: 2px;
  margin-right: 15px;
  span {
    color: #c0c4cc;
  }
  &:hover {
    background: rgba(240, 245, 255, 1);
    span {
      color: #909399;
    }
  }
}
.to-log-btn {
  width: 102px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  background: rgba(245, 247, 250, 1);
  &:hover {
    color: #597ef7;
  }
}
.w-274 {
  width: 274px;
}
.iconchangyongicon- {
  &:hover {
    background: #eaedfd;
    border-radius: 2px;
  }
}

.depart-list-body {
  .depart-id {
    margin-top: 5px;
  }
  .depart-children-list {
    padding: 16px 10px;
    background: #f5f7fa;
  }
}
</style>
