<template>
  <div class="organizManage-main">
    <div class="organizManage-mainLeft">
      <div class="public-function-div">机构树</div>
      <el-input placeholder="输入关键字进行过滤"
                class="filterTree"
                v-model="filterText">
      </el-input>
      <el-tree ref="orgTree"
               :data="orgTree.tree"
               :props="orgTree.defaultProps"
               highlight-current
               node-key="id"
               @node-click="orgNodeClick"
               :expand-on-click-node="true"
               :style="{height: treeHeight + 'px'}"
               :render-content="renderContent"
               :filter-node-method="filterOrgTree">
      </el-tree>
    </div>
    <div class="organizManage-mainRight">
      <div class="public-function-div">岗位列表</div>
      <div class="post-m">
        <div style="text-align: right;margin-bottom:10px;">
          <el-button size="small"
                    icon="el-icon-circle-plus-outline"
                     @click="operate('add',{})">新增</el-button>
          <el-button type="warning"
                     size="small"
                     icon="el-icon-delete"
                     @click="delAllPost">批量删除</el-button>
        </div>
        <el-table v-loading="postTable.loading"
                  border
                  individual-columns="individual-organizManage-table-columns"
                  :individual-info="individualInfo"
                  drag-column="individual-organizManage-table"
                  :height="postTable.height"
                  highlight-current-row
                  :data="postTable.list"
                  @selection-change="postSelectChange">
          <el-table-column type="selection"
                           align="center"
                           fixed="left"></el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           prop="postCode"
                           label="岗位编码"
                           min-width="100"></el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           prop="postName"
                           label="岗位名称"
                           min-width="150"></el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           prop="cate"
                           label="岗位类别"
                           min-width="80"></el-table-column>
          <!-- <el-table-column :show-overflow-tooltip="true" prop="level" label="岗位级别"
          min-width="150"></el-table-column> -->
          <el-table-column :show-overflow-tooltip="true"
                           prop="postDesc"
                           label="职责描述"
                           min-width="150"></el-table-column>
          <el-table-column fixed="right"
                           label="操作"
                           align="center"
                           width="130">
            <template slot-scope="scope">
              <el-button @click.stop="openUserTable(scope.row)"
                         type="text"
                         size="small">
                人员
              </el-button>
              <el-button @click.stop="operate('edit', scope.row)"
                         type="text"
                         size="small">
                修改
              </el-button>
              <el-button @click.stop="operate('del', scope.row)"
                         type="text"
                         size="small">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="yt-table-page">
          <el-pagination :current-page="postTable.tableParams.form.pageNum"
                         :page-sizes="[10, 20, 30, 40]"
                         :page-size="postTable.tableParams.form.pageSize"
                         layout="total, sizes, prev, pager, next"
                         :total="postTable.tableParams.page.total"
                         @size-change="postPageSizeChange"
                         @current-change="postPageCurrentChange">
          </el-pagination>
        </div>
      </div>
      <!--  用户列表  -->
      <div class="post-m"
           v-show="userTable.show">
        <div class="ytg-ps-title">绑定用户列表</div>
        <div style="text-align: right;margin-bottom:10px;">
          <el-button size="small"
                     @click="postAddUser">选择</el-button>
        </div>
        <el-table v-loading="userTable.loading"
                  border
                  :height="userTable.height"
                  highlight-current-row
                  :data="userTable.list"
                  @selection-change="userSelectChange">
          <el-table-column :show-overflow-tooltip="true"
                           prop="userCode"
                           label="账户"
                           min-width="100"></el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           prop="userName"
                           label="用户姓名"
                           min-width="150"></el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           prop="onlineStatus"
                           label="在线状态"
                           min-width="80">
            <template slot-scope="scope">
              <span class="color-success"
                    v-if="scope.row.onlineStatus==='1'">在线</span>
              <span class="color-danger"
                    v-else-if="scope.row.onlineStatus!=='1'">离线</span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           prop="tel"
                           label="联系手机"
                           min-width="80"></el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           prop="homeAddr"
                           label="联系地址"
                           min-width="80"></el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           prop="qq"
                           label="QQ号"
                           min-width="80"></el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           prop="status"
                           label="状态"
                           min-width="80">
            <template slot-scope="scope">
              <span class="color-success"
                    v-if="scope.row.status==='1'">启用</span>
              <span class="color-danger"
                    v-else-if="scope.row.status==='0'">停用</span>
              <span v-else></span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加/修改 -->
    <el-dialog :title="dialogPost.title"
               :visible.sync="dialogPost.show"
               ref="dialogPost"
               :rules="dialogPost.ruleValidate"
               width="400px"
               center
               @close="dialogReset">
      <el-form ref="dialogPost"
               :model="dialogPost.form"
               :rules="dialogPost.ruleValidate"
               label-width="80px"
               class="FormorganizManage-main">
        <el-row>
          <el-col :span="24">
            <el-form-item label="机构"
                          prop="orgCode">
              <el-input v-model="dialogPost.form.orgCode"
                        disabled
                        size="small"
                        placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="岗位编码"
                          prop="postCode">
              <el-input v-model="dialogPost.form.postCode"
                        size="small"
                        placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="岗位名称"
                          prop="postName">
              <el-input v-model="dialogPost.form.postName"
                        size="small"
                        placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="岗位类别"
                          prop="cate">
              <el-select v-model="dialogPost.form.cate"
                         placeholder="请输入"
                         style="width: 100%;"
                         size="small">
                <el-option label="系统管理岗"
                           value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="职责描述"
                          prop="postDesc">
              <el-input v-model="dialogPost.form.postDesc"
                        type="textarea"
                        :autosize="{minRows: 3,maxRows: 5}"
                        style="width:100%"
                        size="small"
                        placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogPost.show = false"
                   size="small">取 消</el-button>
        <el-button type="primary"
                   :loading="dialogPost.loading"
                   @click="dialogPostOk"
                   size="small">确 定</el-button>
      </div>
    </el-dialog>

    <!--  选择用户   -->
    <user-selector v-show="table2User.show"
                   :items="userTable.list"
                   @on-then="table2Then"
                   @on-select-user="selectUser"></user-selector>
    <icore-individual uiId="organizManage-main" indexClass="organizManage-main"></icore-individual>
  </div>

</template>
<script>
import store from '@/store/index.js';
import { checkCharLength, checkCharLength2, checkCharNoChinese } from '@/utils/validator.js';
import { objAssign } from '@/utils/util.js';
import userSelector from './userSelector.vue';
export default {
  components: {
    userSelector
  },
  data () {
    return {
      individualInfo: {},
      filterText: '',
      store,
      treeHeight: 600,
      tableHeight: 300,
      operateStatus: 'add',
      //  机构树
      orgTree: {
        tree: [],
        items: [],
        item: {},
        tableParams: JSON.parse(JSON.stringify(store.state.tableParams)),
        //  默认配置数据对应项
        defaultProps: {
          children: 'children',
          label: 'orgName'
        },
        //  默认展开的ID数组
        expandedKeys: []
      },
      //  岗位列表
      postTable: {
        height: 300,
        loading: false,
        list: [],
        //  选中项
        items: [],
        item: {},
        tableParams: JSON.parse(JSON.stringify(store.state.tableParams))
      },
      // ============= user =========
      //  绑定的用户列表
      userTable: {
        loading: false,
        height: 300,
        show: false,
        list: [],
        //  选中项
        items: [],
        item: {},
        tableParams: JSON.parse(JSON.stringify(store.state.tableParams))
      },
      // ============= /user =======
      table2User: {
        show: false
      },
      // ============= //add user =====
      //  添加表单
      dialogPost: {
        loading: false,
        'title': '添加',
        'show': false,
        'form': {
          'orgCode': '',
          'postId': '',
          'postCode': '',
          'postName': '',
          'cate': '',
          'postDesc': ''
        },
        ruleValidate: {
          orgCode: [
            { required: true, message: '机构编码不能为空', trigger: 'change' },
            { validator: checkCharLength, max: 32, trigger: 'change' }
          ],
          postCode: [
            { required: true, message: '岗位编码不能为空', trigger: 'change' },
            { validator: checkCharLength, max: 32, trigger: 'change' },
            { validator: checkCharNoChinese, trigger: 'change' }
          ],
          postName: [
            { required: true, message: '岗位名称不能为空', trigger: 'change' },
            { validator: checkCharLength, max: 64, trigger: 'change' }
          ],
          postDesc: [
            { validator: checkCharLength2, max: 100, trigger: 'change' }
          ]
        }
      }
    }
  },
  computed: {
  },
  watch: {
    filterText (val) {
      this.$refs.orgTree.filter(val);
    }
  },
  mounted () {
    this.initData();
    //  设置树区域高度
    this.treeHeight = this.getTreeHeight(this.$refs['orgTree'].$el);
    //
    this.tableHeight = this.getTableHeight(this.$refs['orgTree'].$el);
  },
  methods: {
    initData () {
      //  查询机构树
      this.getOrg();
      //  取岗位列表
      this.getList(this.postTable.tableParams.form);
    },
    //  取机构树
    getOrg () {
      //  查询机构树
      this.store.dispatch('system/organizManage/tree').then(res => {
        if (res.code === '0') {
          //
          this.orgTree.tree = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //  取岗位列表
    getList (form) {
      this.postTable.loading = true;
      //  查询岗位列表
      this.store.dispatch('system/sysPosts/list', form).then(res => {
        this.postTable.loading = false;
        if (res.code === '0') {
          this.postTable.list = res.data.list;
          this.postTable.tableParams.form.pageNum = res.data.pageNum;
          this.postTable.tableParams.form.pageSize = res.data.pageSize;
          this.postTable.tableParams.page.total = res.data.total;
        } else {
          this.$message.error(res.message);
          this.postTable.tableParams.form.pageNum = 1;
          this.postTable.tableParams.page.total = 0;
        }
      });
    },
    //  点击树事件
    orgNodeClick (item) {
      //  放入
      this.orgTree.item = item;
      //  取岗位列表
      this.postTable.tableParams.form.orgCode = item.orgCode;
      this.getList(this.postTable.tableParams.form);
      //
      this.userTable.show = false;
    },
    //  计算树区域高度
    getTreeHeight (dom) {
      return window.innerHeight - dom.offsetTop;
    },
    //  计算table高度
    getTableHeight (dom) {
      return ((window.innerHeight - dom.offsetTop) - 100) / 2;
    },
    renderContent (h, { node, data, store }) {
      return h('span',
        {
          style: {
            position: 'relative',
            width: '100%',
            fontSize: '12px'
          },
          class: 'og-st-ellipsis'
        },
        [
          h('span', node.label),
          h('span', {
            style: {
              position: 'absolute',
              right: '0px'
            }
          })
        ]);
    },
    //  table选中
    postSelectChange (items) {
      this.postTable.items = items;
    },
    //  删除岗位
    delPost (itemArr) {
      this.store.dispatch('system/sysPosts/delPost', itemArr).then(res => {
        if (res.code === '0') {
          this.$message.success('删除成功');
          // 刷新
          this.getList(this.postTable.tableParams.form);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //  批量删除
    delAllPost () {
      //
      this.$confirm('确定要删除已选择的记录吗？确定请选是，取消选否。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delPost(this.postTable.items);
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    //  打开弹窗
    operate (str, item) {
      //
      switch (str) {
        case 'add':
          if (Object.keys(this.orgTree.item).length < 1) {
            this.$message.error('请选择机构树');
            return false;
          }
          this.operateStatus = str;
          this.dialogPost.show = true;
          this.dialogPost.title = '添加';
          this.dialogPost.form.orgCode = this.orgTree.item.orgCode;
          break;
        case 'edit':
          this.operateStatus = str;
          this.dialogPost.show = true;
          this.dialogPost.title = '修改';
          //  加入表单
          this.dialogPost.form = objAssign(this.dialogPost.form, item);
          break;
        case 'del':
          this.$confirm('确定要删除记录吗？确定请选是，取消选否。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.delPost([item]);
          }).catch(() => {
            this.$message.info('已取消操作');
          });
          break;
      }
    },
    //  清空弹窗
    dialogReset () {
      this.$refs['dialogPost'].resetFields();
    },
    //  弹窗点击确定
    dialogPostOk () {
      let bol = false;
      this.$refs['dialogPost'].validate((valid) => {
        if (!valid) {
          bol = true;
        }
      });
      //
      if (bol) {
        return false;
      }
      //
      this.dialogPost.loading = true;
      //
      if (this.operateStatus === 'add') {
        //
        this.dialogPost.form.orgCode = this.orgTree.item.orgCode;
        //  添加
        this.store.dispatch('system/sysPosts/addPost', this.dialogPost.form).then(res => {
          this.dialogPost.loading = false;
          if (res.code === '0') {
            this.$message.success('添加成功');
            // 刷新
            this.getList(this.postTable.tableParams.form);
            //
            this.dialogPost.show = false;
          } else {
            this.$message.error(res.message);
          }
        });
      } else if (this.operateStatus === 'edit') {
        // 修改
        this.store.dispatch('system/sysPosts/editPost', { id: this.dialogPost.form.postId, form: this.dialogPost.form }).then(res => {
          this.dialogLoading = false;
          if (res.code === '0') {
            this.$message.success('修改成功');
            // 刷新
            this.getList(this.postTable.tableParams.form);
            //
            this.dialogPost.show = false;
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    //
    postPageSizeChange (size) {
      this.postTable.tableParams.form.pageSize = size;
      this.getList(this.postTable.tableParams.form);
    },
    //
    postPageCurrentChange (index) {
      this.postTable.tableParams.form.pageNum = index;
      this.getList(this.postTable.tableParams.form);
    },
    // =============================  人员 ==================
    // 打开用户列表
    openUserTable (item) {
      // 显示
      this.userTable.show = true;
      this.userTable.item = item;
      //
      this.userTable.tableParams.form.postId = item.postId;
      //  查询数据
      this.getUserList(this.userTable.tableParams.form);
    },
    //  取用户列表
    getUserList (form) {
      form.pageSize = '1000000';
      this.userTable.loading = true;
      //  查询岗位列表
      this.store.dispatch('system/sysPosts/userList', form).then(res => {
        this.userTable.loading = false;
        if (res.code === '0') {
          this.userTable.list = res.data.list;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //  修改岗位绑定的用户
    addInsertPostUser (postItem, items) {
      let form = {
        id: postItem.postId,
        form: []
      }
      //
      for (let item of items) {
        form.form.push({
          userId: item.userId,
          postType: '1'
        });
      }
      //
      this.store.dispatch('system/sysPosts/insertPostUser', form).then(res => {
        if (res.code === '0') {
          this.$message.success('配置成功');
          //  刷新用户列表
          this.getUserList(this.userTable.tableParams.form);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //
    userSelectChange () {

    },
    //
    userPageSizeChange (size) {
      this.userTable.tableParams.form.pageSize = size;
      this.getUserList(this.userTable.tableParams.form);
    },
    //
    userPageCurrentChange (index) {
      this.userTable.tableParams.form.pageNum = index;
      this.getUserList(this.userTable.tableParams.form);
    },
    //  关闭
    table2Then (str, item) {
      this.table2User.show = false;
    },
    //  用户选择
    selectUser (items) {
      //  提交用户选择修改
      this.addInsertPostUser(this.userTable.item, items);
    },
    //  打开选择用户
    postAddUser () {
      this.table2User.show = true;
    },
    // 树形控件过滤数据
    filterOrgTree (value, data) {
      if (!value) return true;
      return data.orgName.indexOf(value) !== -1;
    }
    // =================== /user ==================
  }
}
</script>
<style>
.og-st-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: keep-all;
  padding-right: 60px;
}

.organizManage-main {
  height: 600px;
}

.public-function-div {
  font-size: 16px;
  padding: 10px 20px;
  border-bottom: 1px solid #d5d5d5;
}

.organizManage-mainLeft {
  width: 30%;
  border-right: 1px solid #e0e0e0;
  float: left;
  overflow-x: hidden;
  height: inherit;
}

.organizManage-mainRight {
  width: 70%;
  float: left;
}

.FormorganizManage-main {
  margin: 20px 20px;
}
.post-m {
  margin: 20px;
}

.filterTree {
  width: 95%;
  margin: 10px 2.5%;
}
</style>
