<template>
  <div class="rolesManage-main user-auth">
    <div class="rolesManage-mainLeft">
      <div class="public-function-div">机构树</div>
      <el-input placeholder="输入关键字进行过滤"
                class="filterTree"
                v-model="filterText">
      </el-input>
      <div style="width: 100%;padding: 20px 20px 0 20px;position: relative;">
        <el-tree class="org-tree"
                 ref="orgTree"
                 :data="orgTree.tree"
                 :props="orgTree.defaultProps"
                 highlight-current
                 node-key="orgId"
                 @node-click="orgNodeClick"
                 :expand-on-click-node="true"
                 :filter-node-method="filterOrgTree">
        </el-tree>
      </div>
    </div>

    <div class="rolesManage-mainLeft-mid">
      <div class="public-function-div">岗位列表</div>
      <div style="margin:20px">
        <el-table ref="postTable"
                  v-loading="postTable.loading"
                  border
                  :height="postTable.height"
                  highlight-current-row
                  :data="postTable.list"
                  @row-click="postTableRowClick">
          <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">
            <template slot-scope="scope">
              <span v-if="scope.row.cate === '1'">系统管理岗</span>
            </template>
          </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>
      </div>
    </div>

    <div class="rolesManage-mainRight">
      <div class="save">
        <el-button type="primary"
                   size="mini"
                   @click="rolesMenuDataSave">保存</el-button>
      </div>
      <el-tabs class="right-tabs">
        <el-tab-pane label="角色">

          <!-- 角色 -->
          <div style="margin:20px;">
            <el-tree ref="rolesTree"
                     :data="rolesTree.tree"
                     :props="rolesTree.defaultProps"
                     highlight-current
                     node-key="roleId"
                     :default-expanded-keys="rolesTree.expandedKeys"
                     default-expand-all
                     show-checkbox
                     :expand-on-click-node="true">
            </el-tree>
          </div>
          <!-- /角色 -->
        </el-tab-pane>
      </el-tabs>
    </div>

  </div>
</template>
<script>
import store from '@/store/index.js';
import { checkCharLength } from '@/utils/validator.js';
import { objAssign } from '@/utils/util.js';
export default {
  components: {
  },
  data () {
    return {
      filterText: '',
      store,
      treeHeight: 600,
      //  角色
      rolesTree: {
        tree: [],
        item: {},
        //  默认配置数据对应项
        defaultProps: {
          children: 'children',
          label: 'roleName'
        },
        //  默认展开的ID数组
        expandedKeys: [],
        //  用户与角色关联表
        authList: []
      },
      //  机构树
      orgTree: {
        tree: [],
        items: [],
        item: {},
        //  默认配置数据对应项
        defaultProps: {
          children: 'children',
          label: 'orgName'
        },
        //  默认展开的ID数组
        expandedKeys: []
      },
      // //  菜单树
      // menuTree: {
      //   tree: [],
      //   items: [],
      //   item: [],
      //   //  默认配置数据对应项
      //   defaultProps: {
      //     children: 'children',
      //     label: 'menuLabel'
      //   },
      //   //  默认展开的ID数组
      //   expandedKeys: [],
      //   //  角色菜单关联表数据
      //   authList: []
      // },
      // dialogRoles: {
      //   //  保存中
      //   loading: false,
      //   operate: 'add',
      //   show: false,
      //   title: '添加',
      //   //  编辑时选中
      //   item: {},
      //   form: {
      //     id: '',
      //     roleCode: '',
      //     roleName: '',
      //     pId: '',
      //     rank: '1',
      //     roleType: '',
      //     remark: ''
      //   },
      //   ruleValidate: {
      //     roleCode: [
      //       {required: true, message: '角色编码不能为空', trigger: 'change'},
      //       {validator: checkCharLength, max: 64, trigger: 'change'}
      //     ],
      //     roleName: [
      //       {required: true, message: '角色名称不能为空', trigger: 'change'},
      //       {validator: checkCharLength, max: 32, trigger: 'change'}
      //     ]
      //   }
      // },
      //  用户列表
      userTable: {
        height: 600,
        loading: false,
        list: [],
        //  选中项
        items: [],
        item: {},
        tableParams: JSON.parse(JSON.stringify(store.state.tableParams))
      },
      //  岗位列表
      postTable: {
        height: 600,
        loading: false,
        list: [],
        //  选中项
        items: [],
        item: {},
        //  用户与岗位关联数据
        authList: [],
        tableParams: JSON.parse(JSON.stringify(store.state.tableParams))
      }
    }
  },
  mounted () {
    //
    this.initData();
    //  设置树区域高度
    this.$nextTick(() => {
      this.treeHeight = this.getRoleHeight(this.$refs['orgTree'].$el) - 125;
      this.postTable.height = this.getRoleHeight(this.$refs['postTable'].$el) - 70;
    });
  },
  methods: {
    //  计算树区域高度
    getRoleHeight (dom) {
      return window.innerHeight - dom.offsetTop;
    },
    //  init
    initData () {
      //  取机构树
      this.getOrg();
      //  取角色数据
      this.getRoles();
      //  取岗位列表
      this.getPost(this.postTable.tableParams.form);
    },
    //  机构树点击
    orgNodeClick (item) {
      this.orgTree.item = item;
      //  查询
      this.postTable.tableParams.form.orgCode = item.orgCode;
      this.getPost(this.postTable.tableParams.form);
    },
    //  列表点击
    postTableRowClick (item) {
      //
      this.postTable.item = item;
      //  查询角色关联
      this.getSyspostroles(item.postId).then(() => {
        //  选中角色
        console.log(this.rolesTree.authList);
        let rolesIdArr = [];
        for (let item of this.rolesTree.authList) {
          rolesIdArr.push(item.roleId);
        }
        // 清空
        this.$refs['rolesTree'].setCheckedKeys([]);
        //
        this.$refs['rolesTree'].setCheckedKeys(rolesIdArr);
      });
      //  查询岗位关联
      // this.getSysuserposts(item.userId).then(() => {
      //   //  选中岗位
      //   let rowArr = [];
      //   this.postTable.list.forEach(row => {
      //     for (let item of this.postTable.authList) {
      //       if (row.postId === item.postId) {
      //         row.postType = item.postType;
      //         rowArr.push(row);
      //         break;
      //       }
      //     }
      //   });
      //   //  深拷贝数据
      //   let rowArr2 = JSON.parse(JSON.stringify(rowArr));
      //   //  表格重写
      //   this.postTable.list = [...this.postTable.list];
      //   //  选中
      //   this.$nextTick(() => {
      //     for (let item of rowArr) {
      //       this.$refs['postTable'].toggleRowSelection(item, true);
      //     }
      //     //  设置主副岗位
      //     setTimeout(() => {
      //       this.postTable.items = [...rowArr2];
      //     }, 100);
      //   });
      // });
    },
    //  岗位权限选中
    // postSelectChange (items) {
    //   // this.postTable.items = items;
    //   // let mainPost = this.postTable.items.filter(item => {
    //   //   if (item.postType === '1') {
    //   //     return true;
    //   //   } else {
    //   //     return false;
    //   //   }
    //   // });
    //   // //
    //   // for (let item of this.postTable.items) {
    //   //   item.postType = '2';
    //   // }
    //   // //
    //   // if (mainPost.length > 0) {
    //   //   mainPost[0].postType = '1';
    //   // } else if (this.postTable.items.length > 0) {
    //   //   this.postTable.items[0].postType = '1';
    //   // }
    // },
    //  保存配置
    rolesMenuDataSave () {
      if (Object.keys(this.postTable.item).length < 1) {
        this.$message.error('请选择岗位');
        return false;
      }
      //  取角色选中项
      let rolesIdArr = this.$refs['rolesTree'].getCheckedKeys();
      let items = [];
      for (let item of rolesIdArr) {
        items.push({
          roleId: item
        });
      }
      //  岗位分配角色权限
      this.setBatchInsertPostRoles(items);
    },
    getOrg () {
      //  查询机构树
      this.store.dispatch('system/organizManage/tree').then(res => {
        if (res.code === '0') {
          this.orgTree.tree = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //  取角色树
    async getRoles () {
      //
      const promise = await this.store.dispatch('system/rolesManage/list').then(res => {
        if (res.code === '0') {
          this.rolesTree.tree = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
      return promise;
    },
    //  取岗位
    async getPost (form) {
      form.pageSize = '100000';
      this.postTable.loading = true;
      //  查询岗位列表
      const promise = await this.store.dispatch('system/sysPosts/list', form).then(res => {
        this.postTable.loading = false;
        if (res.code === '0') {
          this.postTable.list = res.data.list;
        } else {
          this.$message.error(res.message);
        }
      });
      return promise;
    },
    // //  取用户列表
    // getUser (form) {
    //   form.pageSize = '1000000';
    //   this.store.dispatch('system/usersManage/list', form).then(res => {
    //     if (res.code === '0') {
    //       this.userTable.list = res.data.list;
    //       this.userTable.tableParams.form.pageNum = res.data.pageNum;
    //       this.userTable.tableParams.form.pageSize = res.data.pageSize;
    //       this.userTable.tableParams.page.total = res.data.total;
    //     } else {
    //       this.$message.error(res.message);
    //       this.userTable.tableParams.form.pageNum = 1;
    //       this.userTable.tableParams.page.total = 0;
    //     }
    //   });
    // },
    //  用户查角色
    // async getSysuserroles (userId) {
    //   const promise = await this.store.dispatch('system/userAuth/sysuserroles', {userId}).then(res => {
    //     if (res.code === '0') {
    //       this.rolesTree.authList = res.data.list;
    //     } else {
    //       this.$message.error(res.message);
    //     }
    //   });
    //   return promise;
    // },
    //  岗位查询用户角色ID
    async getSyspostroles (postId) {
      const promise = await this.store.dispatch('system/postsManage/syspostroles', { postId }).then(res => {
        if (res.code === '0') {
          this.rolesTree.authList = res.data.list;
        } else {
          this.$message.error(res.message);
        }
      });
      return promise;
    },
    //  设置用户权限
    // async setBatchInsert (rolesIdArr) {
    //   let form = {
    //     userId: this.userTable.item.userId,
    //     userCode: this.userTable.item.userCode,
    //     roleId: rolesIdArr.join(',')
    //   };
    //   //
    //   const promise = await this.store.dispatch('system/userAuth/batchInsert', form).then(res => {
    //     if (res.code === '0') {
    //       this.$message.success('设置成功');
    //     } else {
    //       this.$message.error(res.message);
    //     }
    //   });
    //   return promise;
    // },
    //  设置用户岗位
    async setBatchInsertPostRoles (items) {
      let form = {
        postId: this.postTable.item.postId,
        form: items
      }
      //
      const promise = await this.store.dispatch('system/postsManage/batchInsertPostRoles', form).then(res => {
        if (res.code === '0') {
          this.$message.success('设置成功');
        } else {
          this.$message.error(res.message);
        }
      });
      return promise;
    },
    // 树形控件过滤数据
    filterOrgTree (value, data) {
      if (!value) return true;
      return data.orgName.indexOf(value) !== -1;
    }
    //  设为主岗位
    // postMainClick (item) {
    //   for (let item of this.postTable.items) {
    //     item.postType = '2';
    //   }
    //   item.postType = '1';
    //   this.postTable.items = [...this.postTable.items];
    // }
  }
}

</script>
<style lang="less">
.user-auth {
  height: 100%;
  .right-tabs {
    .el-tabs__item {
      font-size: 16px;
      height: 42px;
      line-height: 42px;
    }
    .el-tabs__nav-wrap::after {
      height: 1px;
      background-color: rgb(213, 213, 213);
    }
    .el-tabs__active-bar {
      height: 1px;
    }
    .el-tabs__nav {
      margin-left: 20px;
    }
    .el-tabs__header {
      margin-bottom: 0;
    }
  }
  //
  .roles-tree-header {
    height: 42px;
  }
  //  保存
  .rolesManage-mainRight {
    position: relative;
    .save {
      position: absolute;
      right: 20px;
      top: 5px;
      z-index: 100;
    }
  }
  .rolesManage-mainLeft {
    width: 20%;
    height: inherit;
    //  机构树去掉下划线
    .org-tree {
      .el-tree-node__label {
        border-bottom: 0;
      }
    }
  }
  // 中间用户列表
  .rolesManage-mainLeft-mid {
    border-right: 1px solid #e0e0e0;
    float: left;
    overflow-x: hidden;
    width: 35%;
  }
  .rolesManage-mainRight {
    width: 45%;
  }
  //
  .public-function-div {
    font-size: 16px;
    padding: 10px 20px;
    border-bottom: 1px solid #d5d5d5;
  }
  //  设为主岗位
  .post-main-btn {
    padding: 3px 5px;
  }
}
.rolesManage-footer {
  background: #f5f5f5;
  margin: -12px -17px -11px -17px;
  height: 40px;
  text-align: center;
  vertical-align: middle;
}

.rolesManage-invite-agree {
  border: none;
  background: none;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  width: 100%;
  height: 100%;
}

.rolesManage-create-header {
  background-color: #f5f5f5;
  margin: -15px -15px 0 -15px;
}

.rolesManage-create-header-title {
  color: #666;
  font-size: 16px;
  text-align: center;
  height: 50px;
  line-height: 50px;
}

.rolesManage-mainLeft {
  width: 40%;
  border-right: 1px solid #e0e0e0;
  float: left;
  overflow-x: hidden;
}

.rolesManage-mainRight {
  width: 60%;
  float: left;
}

.mainRigh-function {
  padding: 13px 0 15px 20px;
  text-align: left;
  border-bottom: 1px solid #d5d5d5;
  position: relative;
}

.rolesManage-searchContent {
  text-align: left;
  position: relative;
  float: left;
  width: 50%;
  margin-left: 20px;
  margin-top: 5px;
  margin-bottom: 9px;
}

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