<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-row>
          <el-col :span="19">
            <el-form class="userModal"
                     label-width="80px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="账户">
                    <el-input v-model="userTable.tableParams.form.userCode"
                              placeholder="请输入"
                              clearable
                              size="small"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="用户姓名">
                    <el-input v-model="userTable.tableParams.form.userName"
                              placeholder="请输入"
                              clearable
                              size="small"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所属机构">
                    <el-cascader clearable
                                 v-model="orgTree.items"
                                 size="small"
                                 :options="orgTree.tree"
                                 :change-on-select="true"
                                 :props="{value:'orgCode',label:'orgName'}"
                                 @change="selectOrg">
                    </el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系手机">
                    <el-input v-model="userTable.tableParams.form.mobile"
                              placeholder="请输入"
                              clearable
                              size="small"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-col>
          <el-col :span="5">
            <div style="text-align: right;margin-bottom:10px;">
              <el-button icon="el-icon-search"
                         type="primary"
                         size="small"
                         @click="search">查询</el-button>
            </div>
          </el-col>
        </el-row>
        <!--  -->
        <el-table ref="userTable"
                  v-loading="userTable.loading"
                  border
                  @filter-change="filterChange"
                  :height="userTable.height"
                  highlight-current-row
                  :data="userTable.list"
                  @row-click="userTableRowClick">
          <el-table-column :show-overflow-tooltip="true"
                           prop="userCode"
                           label="账户"
                           :filter-method="filterColumn"
                           min-width="150"></el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           prop="userName"
                           label="用户姓名"
                           :filter-method="filterColumn"
                           min-width="150"></el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           label="所属机构"
                           prop="orgCode"
                           :filter-method="filterColumn"
                           min-width="150">
            <template slot-scope="scope">
                <span>{{findOrgName(scope.row.orgCode)}}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="rolesManage-mainRight">
      <el-tabs class="right-tabs">
        <el-tab-pane label="功能权限">
          <!-- 功能权限 -->
          <div style="margin:20px; margin-top:0; overflow-y: auto;"
               :style="{height: dataTable.height + 'px'}">
            <el-tree ref="menuTree"
                     :data="menuTree.tree"
                     :props="menuTree.defaultProps"
                     node-key="menuId"
                     show-checkbox
                     :default-expanded-keys="menuTree.expandedKeys"
                     :expand-on-click-node="true">
            </el-tree>
          </div>
          <!-- /功能权限 -->
        </el-tab-pane>
        <!-- <el-tab-pane label="数据权限">
          数据权限
          <div style="margin:20px; overflow-y: auto;"
               :style="{height: dataTable.height + 'px'}">
            <el-table ref="dataTable"
                      v-loading="dataTable.loading"
                      border
                      :height="dataTable.height"
                      highlight-current-row
                      :data="dataTable.list">
              <el-table-column type="selection"
                               align="center"
                               fixed="left"></el-table-column>
              <el-table-column :show-overflow-tooltip="true"
                               prop="tableName"
                               label="表名"
                               min-width="150"></el-table-column>
              <el-table-column :show-overflow-tooltip="true"
                               prop="authDesc"
                               label="数据规则描述"
                               min-width="150"></el-table-column>
            </el-table>
          </div>
          /数据权限
        </el-tab-pane> -->
      </el-tabs>
    </div>

  </div>
</template>
<script>
import store from '@/store/index.js';
import { checkCharLength } from '@/utils/validator.js';
import { objAssign, dgTree } 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: []
      },
      //  用户列表
      userTable: {
        height: 600,
        loading: false,
        list: [],
        //  选中项
        items: [],
        item: {},
        tableParams: JSON.parse(JSON.stringify(store.state.tableParams))
      },
      //  菜单树
      menuTree: {
        tree: [],
        items: [],
        item: [],
        //  默认配置数据对应项
        defaultProps: {
          children: 'children',
          label: 'menuLabel'
        },
        //  默认展开的ID数组
        expandedKeys: [],
        //  角色菜单关联表数据
        authList: []
      },
      //  数据权限列表
      dataTable: {
        height: 600,
        loading: false,
        list: [],
        //  选中项
        items: [],
        item: {},
        //  角色与数据权限关联数据
        authList: []
      }
    }
  },
  watch: {
    filterText (val) {
      this.$refs.orgTree.filter(val);
    }
  },
  mounted () {
    //
    this.initData();
    //  设置树区域高度
    this.$nextTick(() => {
      this.treeHeight = this.getRoleHeight(this.$refs['orgTree'].$el) - 125;
      this.userTable.height = this.getRoleHeight(this.$refs['userTable'].$el) - 70;
    });
  },
  methods: {
    //  计算树区域高度
    getRoleHeight (dom) {
      return window.innerHeight - dom.offsetTop;
    },
    //  init
    initData () {
      //  取机构树
      this.getOrg();
      //  取用户列表
      this.getUser(this.userTable.tableParams.form);
      //  取菜单数据
      this.getMenu();
      //  取数据权限列表
      this.getDataRoles();
    },
    //  机构树点击
    orgNodeClick (item) {
      this.orgTree.item = item;
      //  查询用户
      this.userTable.tableParams = JSON.parse(JSON.stringify(store.state.tableParams));
      this.userTable.tableParams.form.orgCode = item.orgCode;
      //  取上级节点
      let items = [];
      this.dgPid(this.orgTree.tree, item.id, item => {
        items.push(item.orgCode);
      });
      this.orgTree.items = items.reverse();
      //  查询用户
      this.getUser(this.userTable.tableParams.form);
    },
    //  用户列表点击
    userTableRowClick (item) {
      let that = this;
      //  查询功能权限与数据权限
      this.getFindAuthorizeByUserId(item.userId).then(() => {
        //   选中项目
        //  数据整理
        //  菜单选中项
        let menuArr = [];
        //  数据权限选中项
        let dataArr = [];
        //
        for (let item of this.menuTree.authList) {
          //   resourceType ： 1 功能菜单权限 ， 2 数据权限
          try {
            if (item.resourceId && item.resourceType === '1' && that.$refs.menuTree.getNode(item.resourceId) && that.$refs.menuTree.getNode(item.resourceId).childNodes.length === 0) {
              menuArr.push(item.resourceId);
            } else if (item.resourceType === '2') {
              dataArr.push(item.resourceId);
            }
          } catch (error) {
          }
        }
        // 清空
        this.$refs['menuTree'].setCheckedKeys([]);
        //  菜单选中
        this.$refs['menuTree'].setCheckedKeys(menuArr);
        //  功能选中
        for (let item of this.dataTable.list) {
          for (let id of dataArr) {
            if (item.id === id) {
              this.$refs['dataTable'].toggleRowSelection(item, true);
              break;
            }
          }
        }
      });
      //
      //
      // this.userTable.item = item;
      // //  查询角色关联
      // this.getSysuserroles(item.userId).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);
      //   });
      // });
    },
    //
    getOrg () {
      //  查询机构树
      this.store.dispatch('system/organizManage/tree').then(res => {
        if (res.code === '0') {
          dgTree(res.data, 'children', item => {
            if ('children' in item && item.children.length < 1) {
              delete item.children;
            }
          });
          this.orgTree.tree = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //  取用户列表
    getUser (form) {
      let _this = this;
      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;
          _this.setFilterDatas(_this.$refs.userTable.columns, _this.userTable.list, ['userCode', 'userName', 'orgCode']);
        } else {
          this.$message.error(res.message);
          this.userTable.tableParams.form.pageNum = 1;
          this.userTable.tableParams.page.total = 0;
        }
      });
    },
    //  查询用户中间表
    async getFindAuthorizeByUserId (userId) {
      const promise = await this.store.dispatch('system/userAuth/findAuthorizeByUserId', userId).then(res => {
        if (res.code === '0') {
          this.menuTree.authList = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
      return promise;
    },
    //  取菜单
    async getMenu () {
      //  查询列表
      const promise = await this.store.dispatch('system/functionMain/menuTree').then(res => {
        if (res.code === '0') {
          this.menuTree.tree = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
      return promise;
    },
    //  取数据权限列表
    async getDataRoles () {
      //  查询列表
      const promise = await this.store.dispatch('system/rolesManage/dataRolesList').then(res => {
        if (res.code === '0') {
          this.dataTable.list = res.data.list;
        } else {
          this.$message.error(res.message);
        }
      });
      return promise;
    },
    //  点击查询用户
    search () {
      //  取用户列表
      this.getUser(this.userTable.tableParams.form);
    },
    //  找父节点
    dgPid (tree, id, cb) {
      dgTree(tree, '', item => {
        if (item.id === id) {
          cb(item);
          if (item.pId) {
            this.dgPid(tree, item.pId, cb);
          }
        }
      });
    },
    // 树形控件过滤数据
    filterOrgTree (value, data) {
      if (!value) return true;
      return data.orgName.indexOf(value) !== -1;
    },
    // 表格过滤
    filterChange (filters) {
      var _this = this;
      _this.setFilterDatas(_this.$refs.userTable.columns, _this.$refs.userTable.tableData, ['userCode', 'userName', 'orgCode']);
    },
    // 搜索选择机构
    selectOrg (value) {
      this.userTable.tableParams.form.orgCode = value.length >= 2 ? value[value.length - 1] : value[0];
    },
    // 查询子节点
    getOrgName (list, code) {
      var name = '';
      for (let i = 0; i < list.length; i++) {
        try {
          if (list[i].orgCode === code) {
            name = list[i].orgName
            return name
          } else if (list[i].children && list[i].children.length >= 1) {
            name = this.getOrgName(list[i].children, code);
            if (name) {
              return name
            }
          }
        } catch (error) {
          console.log(error)
        }
      }
      return name;
    }
  },
  computed: {
    findOrgName () {
      return function (code) {
        return this.getOrgName(this.orgTree.tree, code)
      }
    }
  }
}

</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;
  height: inherit;
}

.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>
