<template>
  <div class="user-auth">
    <div class="rolesManage-mainLeft">
      <!-- 下拉选择公司 -->
      <!-- <div class="company-select" v-if="companys !== '' && companys.length > 1">
                <el-dropdown
                    trigger="click"
                    @command="selectComPany"
                >
                    <span class="el-dropdown-link">
                        {{companyName}}<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <div v-for="item in companys" :key="item.id">
                            <el-dropdown-item :command="item">{{item.companyName}}</el-dropdown-item>
                        </div>
                    </el-dropdown-menu>
                </el-dropdown>
            </div> -->
      <div class="public-function-div">
        机构树
        <el-button
          @click="setCheckedNodes"
          type="success"
          size="small"
          class="refresh"
          >展开</el-button
        >
        <el-button
          @click="setCheckedKeys"
          type="success"
          size="small"
          class="refresh2"
          >收起</el-button
        >
      </div>
      <el-input
        style="padding: 0 20px"
        placeholder="输入关键字进行过滤"
        class="userAuth-filterTree"
        v-model="filterText"
      >
      </el-input>
      <div style="width: 100%; padding: 0 20px; position: relative">
        <el-tree
          class="org-tree"
          ref="orgTree"
          v-loading="treeLoading"
          :data="orgTree.tree"
          :props="orgTree.defaultProps"
          highlight-current
          node-key="orgId"
          :style="{ height: treeHeight + 'px' }"
          @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-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="账户">
            <el-input
              v-model="formInline.form.userCode"
              placeholder="请输入账户"
              size="mini"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input
              v-model="formInline.form.userName"
              placeholder="请输入姓名"
              clearable
              size="mini"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" size="mini"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          ref="userTable"
          v-loading="userTable.loading"
          @filter-change="filterChange"
          border
          :height="userTable.height"
          highlight-current-row
          :data="userTable.list"
          @selection-change="handleSelectionChange"
          @row-click="userTableRowClick"
        >
          <el-table-column type="selection" align="center" width="30">
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="userCode"
            label="账户"
            align="center"
            :filter-method="filterColumn"
            width="100"
          ></el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="userName"
            label="姓名"
            align="center"
            :filter-method="filterColumn"
            width="100"
          ></el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="orgName"
            label="所属机构"
            align="center"
            :filter-method="filterColumn"
            min-width="150"
          >
          </el-table-column>
        </el-table>
        <div class="foot-style">
          <el-pagination
            @size-change="pageSizeChange"
            @current-change="pageCurrentChange"
            :current-page="formInline.form.pageNum"
            :page-sizes="[10, 20, 50, 100, 200]"
            :page-size="formInline.form.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="formInline.page.total"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <div class="rolesManage-mainRight">
      <div class="save">
        <el-button
          type="primary"
          size="mini"
          :loading="saveLoading"
          v-privilege="activeMenu + 'SAVE'"
          @click="rolesMenuDataSave"
          >保存</el-button
        >
      </div>
      <el-tabs class="right-tabs">
        <el-tab-pane label="角色">
          <!-- 角色 -->
          <div style="margin: 20px; margin-top: 0; max-height: 700px">
            <el-input
              placeholder="输入关键字进行过滤"
              class="userAuth-filterTree"
              v-model="filterrolesTxt"
            >
            </el-input>
            <el-tree
              ref="rolesTree"
              :data="rolesTree.tree"
              v-loading="rolesTree.loading"
              :props="rolesTree.defaultProps"
              :style="{ height: treeHeight + 'px' }"
              highlight-current
              node-key="roleId"
              :default-expanded-keys="rolesTree.expandedKeys"
              default-expand-all
              show-checkbox
              :expand-on-click-node="true"
              :filter-node-method="filterRulesTree"
            >
            </el-tree>
          </div>
          <!-- /角色 -->
        </el-tab-pane>
        <!-- 岗位暂时去掉 -->
        <!-- <el-tab-pane label="岗位">
          <div style="margin:20px; overflow-y: auto;max-height:700px;">
            <el-table ref="postTable"
                      v-loading="postTable.loading"
                      row-key="postId"
                      border
                      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="70"></el-table-column>
              <el-table-column :show-overflow-tooltip="true"
                               prop="postName"
                               label="岗位名称"
                               min-width="120"></el-table-column>
              <el-table-column :show-overflow-tooltip="true"
                               prop="postName"
                               label="岗位类型"
                               min-width="120">
                <template slot-scope="scope">
                  <template>
                    <template v-for="item in postTable.items"
                              v-if="item.postId === scope.row.postId">
                      <span :key="item.postId"
                            v-if="item.postType === '1'">主岗位</span>
                      <span :key="item.postId"
                            v-if="item.postType === '2'">副岗位</span>
                      <el-button :key="item.postId + 'btn'"
                                 class="post-main-btn"
                                 v-if="item.postType === '2'"
                                 @click="postMainClick(item)"
                                 type="primary"
                                 plain
                                 size="mini">设为主岗位</el-button>
                    </template>
                  </template>
                </template>
              </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 } from "@/utils/util.js";
export default {
  components: {},
  data() {
    return {
      companys: [], // 用户公司列表
      companyId: "", // 选择公司Id
      companyName: "", // 选择公司名称
      saveLoading: false,
      filterrolesTxt: "",
      filterText: "",
      store,
      treeHeight: 600,
      userRoles: [], // 用户与角色关联信息
      treeLoading: false,
      //  角色
      rolesTree: {
        loading: false,
        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: {
          form: {
            companyId: "",
            pageNum: 1,
            pageSize: 20,
            userCode: '',
            userName: ''
          },
          //  返回分页数据
          page: {
            total: 0,
          },
        },
      },
      //  岗位列表
      postTable: {
        loading: false,
        list: [],
        //  选中项
        items: [],
        item: {},
        //  用户与岗位关联数据
        authList: [],
        tableParams: JSON.parse(JSON.stringify(store.state.tableParams)),
      },
      multipleSelection: [],
      activeMenu: "",
      formInline: {
        form: {
          // account: '',
          // name: '',
          pageNum: 1,
          pageSize: 20,
          companyId: "",
        },
        //  返回分页数据
        page: {
          total: 0,
        },
      },
    };
  },
  created() {
    this.activeMenu = window.top.localStorage.getItem("activeMenu");
  },
  mounted() {
    // 获取公司信息
    this.companys = JSON.parse(window.top.localStorage.getItem("companys"));
    this.companyId = window.top.localStorage.getItem("companyId");
    if (this.companyId !== "" && this.companyId !== null) {
      this.companyName = this.companys.find(
        (x) => x.id === this.companyId
      ).companyName;
    }
    this.userTable.tableParams.form.companyId = this.companyId;
    this.formInline.form.companyId = this.companyId;
    //
    this.initData();
    //  设置树区域高度
    this.$nextTick(() => {
      this.treeHeight = this.getRoleHeight(this.$refs["orgTree"].$el) - 170;
      this.userTable.height =
        this.getRoleHeight(this.$refs["userTable"].$el) - 70;
      //   this.postTable.height = this.getRoleHeight(this.$refs['postTable'].$el) - 70;
    });
  },
  watch: {
    filterText(val) {
      this.$refs.orgTree.filter(val);
    },
    filterrolesTxt(val) {
      this.$refs.rolesTree.filter(val);
    },
  },
  methods: {
    pageSizeChange(size) {
      this.formInline.form.pageSize = size;
      this.formInline.form.companyId = this.companyId;
      if(this.userTable.tableParams.form.orgCode) {
        this.formInline.form.orgCode = this.userTable.tableParams.form.orgCode;
      }
      this.getUser(this.formInline.form);
    },
    pageCurrentChange(index) {
      this.formInline.form.pageNum = index;
      this.formInline.form.companyId = this.companyId;
      if(this.userTable.tableParams.form.orgCode) {
        this.formInline.form.orgCode = this.userTable.tableParams.form.orgCode;
      }
      this.getUser(this.formInline.form);
      // if (this.icoreFilterFlag) {
      //     this.icoreFilterFlag = false;
      // }
    },
    //用户列表搜索
    onSubmit() {
      this.formInline.form.pageSize = 20;
      this.formInline.form.companyId = this.companyId;
      this.getUser(this.formInline.form);
    },
    //  计算树区域高度
    getRoleHeight(dom) {
      return window.innerHeight - dom.offsetTop;
    },
    //  init
    initData() {
      this.treeLoading = true;
      this.userTable.loading = true;
      this.rolesTree.loading = true;
      //  取机构树
      this.getOrg();
      //  取角色数据
      this.getRoles();
      //  取岗位列表
      //   this.getPost(this.postTable.tableParams.form);
      //  取数据权限列表
      // this.getDataRoles();
    },
    //  机构树点击
    orgNodeClick(item) {
      this.orgTree.item = item;
      //  查询用户
      this.userTable.tableParams.form.orgCode = item.orgCode;
      this.formInline.form = {
            userCode: '',
            userName: '',
            pageSize: 20
      }
      this.getUser(this.userTable.tableParams.form);
    },
    //  用户列表点击
    userTableRowClick(item) {
      let that = this;
      this.userTable.item = item;
      //  查询角色关联
      // this.setRow(item);
      this.rolesTree.loading = true;
      this.getUserRole(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);
        that.rolesOrd(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);
      //     });
      //   });
    },
    // 勾选角色排序靠前
    rolesOrd(item) {
      let that = this;
      let temp = [];
      for (let i = 0; i < that.rolesTree.tree.length; i++) {
        temp.push(that.rolesTree.tree[i]);
      }
      for (let i = 0; i < item.length; i++) {
        for (let b = 0; b < temp.length; b++) {
          try {
            if (item[i] === temp[b].id) {
              if (temp[b].pid) {
                that.isPid(temp[b]);
              } else {
                let obj = temp[b];
                temp.splice(b, 1);
                temp.unshift(obj);
                break;
              }
            }
          } catch (err) {
            // debugger
          }
        }
      }
      that.rolesTree.tree = temp;
    },
    // 判断是否有Pid
    isPid(row) {
      let that = this;
      if (row.pId) {
        for (let i = 0; i < that.rolesTree.tree.length; i++) {
          if (row.pid === that.rolesTree.tree[i].id) {
            if (that.rolesTree.tree[i].pid) {
              that.isPid(that.rolesTree.tree[i]);
            } else {
              let obj = that.rolesTree.tree[i];
              that.rolesTree.tree.splice(i, 1);
              that.rolesTree.tree.unshift(obj);
              break;
            }
          }
        }
      }
    },
    //  岗位权限选中
    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";
      }
    },
    //  保存配置
    async rolesMenuDataSave() {
      let that = this;
      if (this.multipleSelection.length < 1) {
        if (
          !this.userTable.item ||
          JSON.stringify(this.userTable.item) === "{}"
        ) {
          this.$message.error("请选择用户");
          return false;
        } else {
          this.saveLoading = true;
          this.rolesTree.loading = true;
          //  取角色选中项
          let rolesIdArr = this.$refs["rolesTree"].getCheckedKeys();
          if (rolesIdArr && rolesIdArr.length > 0) {
            //  分配角色
            this.setBatchInsert(rolesIdArr);
          } else {
            if (that.userRoles.length > 0) {
              let index = 0;
              for (let item of that.userRoles) {
                that.axios
                  .delete("pass/v1/sysuserroles/" + item.id)
                  .then((res) => {
                    if (res.code === "0") {
                      index++;
                    }
                    if (index === that.userRoles.length) {
                      this.$message({
                        type: "success",
                        message: "操作成功!",
                      });
                      this.saveLoading = false;
                      this.rolesTree.loading = false;
                    }
                    // do somthing
                  })
                  .catch((err) => {
                    console.log(err);
                    return false;
                  });
              }
            } else {
              this.$message({
                type: "warning",
                message: "你当前操作的用户角色已为空，无需反复清空!",
              });
              this.saveLoading = false;
              this.rolesTree.loading = false;
            }
          }
        }
      } else if (this.multipleSelection.length === 1) {
        this.saveLoading = true;
        this.rolesTree.loading = true;
        //  取角色选中项
        let rolesIdArr = this.$refs["rolesTree"].getCheckedKeys();
        if (rolesIdArr && rolesIdArr.length > 0) {
          //  分配角色
          this.setBatchInsert(rolesIdArr);
        } else {
          that.axios
            .get(
              "pass/v1/sysuserroles/?userId=" +
                this.multipleSelection[0].userId +
                "&pageNum=1&pageSize=100"
            )
            .then((result) => {
              if (result.data.list.length > 0) {
                let index = 0;
                for (let item of result.data.list) {
                  that.axios
                    .delete("pass/v1/sysuserroles/" + item.id)
                    .then((res) => {
                      if (res.code === "0") {
                        index++;
                      }
                      if (index === result.data.list.length) {
                        this.$message({
                          type: "success",
                          message: "操作成功!",
                        });
                        this.saveLoading = false;
                        this.rolesTree.loading = false;
                      }
                      // do somthing
                    })
                    .catch((err) => {
                      console.log(err);
                      return false;
                    });
                }
              } else {
                this.$message({
                  type: "warning",
                  message: "你当前操作的用户角色已为空，无需反复清空!",
                });
                this.saveLoading = false;
                this.rolesTree.loading = false;
              }
            });
        }
      } else {
        //  取角色选中项
        let rolesIdArr = this.$refs["rolesTree"].getCheckedKeys();
        //  取岗位选中项
        // let tempArr = this.postTable.items;
        // let postArr = [];
        // for (let item of tempArr) {
        //     postArr.push(item.postId);
        // }
        if (rolesIdArr && rolesIdArr.length > 0) {
          this.saveLoading = true;
          this.rolesTree.loading = true;
          //  分配角色
          this.setBatchInsert(rolesIdArr);
        } else {
          this.$confirm("您将清空已勾选的多条用户下的角色, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.saveLoading = true;
              this.rolesTree.loading = true;
              let userIndex = 0;
              for (let user of this.multipleSelection) {
                that.axios
                  .get(
                    "pass/v1/sysuserroles/?userId=" +
                      user.userId +
                      "&pageNum=1&pageSize=100"
                  )
                  .then((result) => {
                    if (result.code === "0") {
                      userIndex++;
                    }
                    if (result.data.list.length > 0) {
                      let index = 0;
                      for (let item of result.data.list) {
                        that.axios
                          .delete("pass/v1/sysuserroles/" + item.id)
                          .then((res) => {
                            if (res.code === "0") {
                              index++;
                            }
                            if (
                              userIndex === this.multipleSelection.length &&
                              index === result.data.list.length
                            ) {
                              this.$message({
                                type: "success",
                                message: "操作成功!",
                              });
                              this.saveLoading = false;
                              this.rolesTree.loading = false;
                            }
                          })
                          .catch((err) => {
                            console.log(err);
                            return false;
                          });
                      }
                    } else {
                      if (userIndex === this.multipleSelection.length) {
                        this.$message({
                          type: "success",
                          message: "操作成功!",
                        });
                        this.saveLoading = false;
                        this.rolesTree.loading = false;
                      }
                    }
                  })
                  .catch((err) => {
                    console.log(err);
                    return false;
                  });
              }
            })
            .catch((err) => {
              console.log(err);
              this.$message({
                type: "info",
                message: "已取消操作",
              });
              this.saveLoading = false;
              this.rolesTree.loading = false;
            });
        }
      }
      //  分配岗位
      //   this.setInsertUserPosts();
    },
    // 获取当前用户角色
    async getUserRole(userid) {
      let that = this;
      const promise = await that.axios
        .get(
          "pass/v1/sysuserroles/?userId=" + userid + "&pageNum=1&pageSize=100"
        )
        .then((res) => {
          if (res.code === "0") {
            that.userRoles = res.data.list; // 获取用户角色关联信息
            that.rolesTree.authList = res.data.list;
            this.rolesTree.loading = false;
          } else {
            that.$message.err(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      return promise;
    },
    getOrg() {
      this.treeLoading = true;
      //  查询机构树
      this.store
        .dispatch("system/organizManage/tree", this.companyId)
        .then((res) => {
          if (res.code === "0") {
            this.orgTree.tree = res.data;
            this.treeLoading = false;
            //  取用户列表
            this.getUser(this.userTable.tableParams.form);
          } else {
            this.$message.error(res.message);
          }
        });
    },
    //  取角色树
    async getRoles() {
      //
      this.rolesTree.loading = true;
      const promise = await this.store
        .dispatch("system/rolesManage/list", { companyId: this.companyId })
        .then((res) => {
          if (res.code === "0") {
            this.rolesTree.tree = res.data;
            this.rolesTree.loading = false;
          } 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;
            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;
          }
        });
      return promise;
    },
    //  取用户列表
    getUser(form) {
      let _this = this;
      _this.userTable.loading = true;
      // form.pageSize = "1000000";
      this.store
        .dispatch("system/usersManage/list", form)
        .then((res) => {
          if (res.code === "0") {
            this.userTable.list = res.data.list;
            this.userTable.listBack = 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.formInline.page.total = res.data.total;
            for (let a = 0; a < this.userTable.list.length; a++) {
              this.userTable.list[a].orgName = this.getOrgName(
                this.orgTree.tree,
                this.userTable.list[a].orgCode
              );
              this.userTable.listBack[a].orgName = this.getOrgName(
                this.orgTree.tree,
                this.userTable.list[a].orgCode
              );
            }
            // 设置过滤数据 setFilterDatas(列数组对象, 数据, 需要过滤的字段, 列名转义对象)
            _this.setFilterDatas(
              _this.$refs.userTable.columns,
              _this.userTable.list,
              ["userCode", "userName", "orgName"]
            );
            _this.userTable.loading = false;
          } else {
            this.$message.error(res.message);
            this.userTable.tableParams.form.pageNum = 1;
            this.userTable.tableParams.page.total = 0;
          }
        })
        .catch((err) => {
          this.$message.error("操作失败");
          console.log(err);
        });
    },
    // 下拉选择公司
    selectComPany(command) {
      this.treeLoading = true;
      this.userTable.loading = true;
      this.rolesTree.loading = true;
      this.companyId = command.id;
      this.companyName = command.companyName;
      this.userTable.tableParams.form.companyId = this.companyId;
      this.getRoles();
      // this.getMenu();
      // this.getDataRoles();
      this.getOrg();
    },
    // 遍历树获取相应公司菜单
    getTreeAll(tree, id) {
      let arr = [];
      if (!!tree && tree.length !== 0) {
        tree.forEach((item) => {
          let obj = {};
          obj = { ...item };
          if (obj.hasOwnProperty("companyId") && obj.companyId === id) {
            obj.children = this.getTreeAll(item.children);
            arr.push(obj);
          }
        });
      }
      return arr;
    },
    //  用户查角色
    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;
    },
    //  用户查岗位
    async getSysuserposts(userId) {
      const promise = await this.store
        .dispatch("system/userAuth/sysuserposts", { userId })
        .then((res) => {
          if (res.code === "0") {
            this.postTable.authList = res.data.list;
          } else {
            this.$message.error(res.message);
          }
        });
      return promise;
    },
    //  设置用户权限
    async setBatchInsert(rolesIdArr) {
      let idArr = [];
      let code = [];
      if (this.multipleSelection) {
        for (let i = 0; i < this.multipleSelection.length; i++) {
          idArr.push(this.multipleSelection[i].userId);
          code.push(this.multipleSelection[i].userCode);
        }
      }
      let form = {
        userId:
          this.multipleSelection && this.multipleSelection.length > 0
            ? idArr.join(",")
            : this.userTable.item.userId,
        userCode:
          this.multipleSelection && this.multipleSelection.length > 0
            ? code.join(",")
            : this.userTable.item.userCode,
        roleId: rolesIdArr.join(","),
      };
      this.axios
        .post(
          "pass/v1/sysuserroles/addUserroles?userId=" +
            form.userId +
            "&userCode=" +
            form.userCode +
            "&roleId=" +
            form.roleId
        )
        .then((res) => {
          if (res.code === "0") {
            this.$message.success("操作成功");
            this.saveLoading = false;
            this.rolesTree.loading = false;
          } else {
            this.$message.error(res.message);
          }
        })
        .catch(() => {
          this.$message.error("操作失败");
        });
    },
    //  设置用户岗位
    async setInsertUserPosts() {
      let form = {
        userId: this.userTable.item.userId,
        form: [],
      };
      //  整理数据  岗位类型：1-主岗位 2-兼岗位
      for (let item of this.postTable.items) {
        form.form.push({
          postId: item.postId,
          postType: item.postType,
        });
      }
      //
      const promise = await this.store
        .dispatch("system/userAuth/insertUserPosts", form)
        .then((res) => {
          if (res.code === "0") {
            this.$message.success("设置成功");
          } else {
            this.$message.error(res.message);
          }
        });
      return promise;
    },
    //  设为主岗位
    postMainClick(item) {
      for (let item of this.postTable.items) {
        item.postType = "2";
      }
      item.postType = "1";
      this.postTable.items = [...this.postTable.items];
    },
    // 树形控件过滤数据
    filterOrgTree(value, data) {
      if (!value) return true;
      return data.orgName.indexOf(value) !== -1;
    },
    filterRulesTree(value, data) {
      if (!value) return true;
      return data.roleName.indexOf(value) !== -1;
    },
    // 表格过滤
    filterChange(filters) {
      var _this = this;
      _this.setFilterDatas(
        _this.$refs.userTable.columns,
        _this.$refs.userTable.tableData,
        ["userCode", "userName", "orgName"]
      );
    },
    // 查询机构名称
    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;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    setCheckedKeys() {
      this.defaultExpand = false;
      for (var i = 0; i < this.$refs.orgTree.store._getAllNodes().length; i++) {
        this.$refs.orgTree.store._getAllNodes()[
          i
        ].expanded = this.defaultExpand;
      }
    },
    setCheckedNodes() {
      this.defaultExpand = true; // 展开所有节点
      for (var i = 0; i < this.$refs.orgTree.store._getAllNodes().length; i++) {
        this.$refs.orgTree.store._getAllNodes()[
          i
        ].expanded = this.defaultExpand;
      }
    },
    setRow(item) {
      this.$refs.userTable.toggleRowSelection(item);
    },
  },
};
</script>
<style lang="less">
.user-auth {
  height: 100%;
  position: relative;
  min-width: 1090px;
  .right-tabs {
    .el-checkbox {
      margin-right: 10px;
    }
    .el-tree-node__expand-icon {
      display: none;
    }
    .el-tabs__item {
      font-size: 16px;
      height: 45px;
      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: 8px;
      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: hidden;
    width: 35%;
    .foot-style {
      width: 100%;
      overflow-x: scroll;
      overflow-y: hidden;
    }
    .el-form {
      .el-input {
        width: 105px;
      }
    }
  }
  .el-tree {
    overflow-x: hidden !important;
  }
  .rolesManage-mainRight {
    width: 45%;
  }
  .company-select {
    padding: 10px 15px 9px 15px;
    border-bottom: 1px solid #d5d5d5;
    .el-dropdown {
      font-weight: bold;
      font-size: 14px;
      cursor: pointer;
    }
  }
  .el-dropdown-menu {
    overflow-y: scroll;
    max-height: 200px;
  }
  .public-function-div {
    font-size: 16px;
    padding: 10px 20px;
    border-bottom: 1px solid #d5d5d5;
    position: relative;
  }
  //  设为主岗位
  .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;
}
.userAuth-filterTree {
  width: 100%;
  margin: 20px 0;
}
.public-function-div .refresh {
  position: absolute;
  right: 15px;
  top: 10px;
}
.public-function-div .refresh2 {
  position: absolute;
  right: 80px;
  top: 10px;
}
</style>
