<!--
 * @Descripttion : 当前组件信息
 * @Author       : 无尘
 * @Date         : 2020-02-13 14:02:22
 * @LastEditors  : 无尘
 * @LastEditTime : 2020-02-21 10:50:36
 * @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="depart-name">
        <span class="font-16 color-303133 font-w-600">{{ departObj.departmentName }}</span>
        <el-popover placement="top" style="min-width: 192px" v-model="nameVisible">
          <limitInput :inputWidth="180" :inputValue.sync="departmentName" :holder="'请输入部门名称'" :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="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 label="部门名称" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.departmentName || '--' }}({{ scope.row.staffCount }})</template>
          </el-table-column>
          <el-table-column prop="" label="企业微信部门ID" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.wxDepartmentId || '--' }}</template>
          </el-table-column>
          <el-table-column prop="" label="ERP CODE" show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="iconfont iconnavigate_next inline-block cursor-pointer" @click="getChildren(scope.row)"></span>
            </template>
          </el-table-column>
        </el-table>
        <div class="block common-wrap__page text-right m-t-24" v-if="tableData.length != 0">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 40, 60, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-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="'请输入部门名称'" :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>
  </div>
</template>
<script>
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
  },
  props: {
    departObj: {
      type: Object,
      default() {
        return {
          departmentId: '',
          departmentName: '',
          wxDepartmentId: '',
          parentId: '',
          isStore: '',
          staffCount: '',
          bindFlag: ''
        };
      }
    }
  },
  data() {
    return {
      nameVisible: false,
      departmentName: '',
      searchInput: '',
      // 分页参数
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      // 新增
      partVisible: false,
      partForm: {
        departmentName: ''
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入部门名称',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  methods: {
    /**
     * 取消
     */
    cancelMod() {
      const that = this;
      that.departmentName = '';
      that.nameVisible = false;
    },
    async toMod() {
      const that = this;
      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();
      done();
    },
    cancel() {
      const that = this;
      that.$refs['form'].resetFields();
    },

    /**
     * 新建子部门
     */
    addChildPart(item) {
      const that = this;
      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) {
            that.currentPage = 1;
            that.getTableList();
            // 是否需要更新左侧 tree
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 分页---页码变化
     */
    handleSizeChange(val) {
      const that = this;
      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.currentPage = 1;
        that.getTableList();
      }
    }
  },
  mounted() {
    const that = this;
    if (Object.keys(that.departObj)) {
      that.currentPage = 1;
      that.getTableList();
    }
  }
};
</script>
<style lang="less" scoped>
.w-274 {
  width: 274px;
}

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