<template>
  <div>
    <el-row :gutter="20" style="background: #fff; padding: 20px">
      <el-col :span="12">
        <div style="margin-bottom: 20px">
          <selectoption></selectoption>
          <el-input v-model="query.name" size="small" placeholder="登录账号" class="handle-input mr10" :clearable="true">
          </el-input>
          <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch" style="background: #FA8E00; border: none;">搜索</el-button>
        </div>
        <div class="container">
          <el-table :data="tableData" border class="table" ref="multipleTable" highlight-current-row
            header-cell-class-name="table-header" @row-click="handleSelectionChange">
            <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
            <el-table-column prop="username" label="登录账号"></el-table-column>
            <el-table-column prop="type" label="分类"></el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template #default="scope">
                <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)">
                  删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
              :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="prever"><el-button type="primary" size="small" @click="bindUser" style="background: #FA8E00; border: none;">保存设置</el-button></div>
        <div class="treediv">
          <el-tree :data="treedata" :default-checked-keys="defaultkeys" show-checkbox node-key="id" default-expand-all
            ref="tree" :props="defaultProps" @check="handleCheckChange">
          </el-tree>
        </div>
      </el-col>
    </el-row>
    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" v-model="editVisible" width="30%">
      <el-form ref="form" :model="form" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="form.name" :clearable="true"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-input v-model="form.address" :clearable="true"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" v-model="editVisible1" width="30%">
      <el-form ref="form" :model="form1" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="form1.name" :clearable="true"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="value" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form-item label="默认角色">
        <el-radio-group v-model="radio">
          <el-radio v-model="radio" :label="1">是</el-radio>
          <el-radio v-model="radio" :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit1">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import {
    httpPost,
    httpGet
  } from "../api/index";
  export default {
    inject: ['reload'],
    name: "basetable",
    data() {
      return {
        selectoption: [],
        selectoptionValue: '',
        defaultkeys: [],
        query: {
          address: "",
          name: "",
          pageIndex: 1,
          pageSize: 5,
          options: [{
            value: "xaxqgy",
            label: "雄安新区XXX公寓",
            children: [],
          }, ],
        },
        radio: 1,
        treedata: [],
        defaultProps: {
          children: "children",
          label: "label",
        },
        options: [{
            value: "选项1",
            label: "超级系统管理员",
          },
          {
            value: "选项2",
            label: "业务员",
          },
        ],
        value: "",
        tableData: [],
        multipleSelection: [],
        delList: [],
        editVisible: false,
        editVisible1: false,
        pageTotal: 0,
        form: {},
        form1: {},
        idx: -1,
        id: -1,
        tableRowClassName: "",
        selectedstyle: "",
        pageNum:1,
        userInfo: {
          type: ''
        }
      };
    },
    created() {
      this.userInfo = JSON.parse(localStorage.getItem('info'))
      this.getUserID();
      this.getUserList();
      this.selectoption = JSON.parse(localStorage.getItem('selectoption'))
      this.selectoptionValue = localStorage.getItem('tenantId')
    },
    methods: {
      selectTenantId(e) {
        localStorage.setItem('tenantId', e)
        this.reload()
      },
      // 勾选角色
      handleCheckChange() {
        let authoritieslist = this.$refs.tree.getCheckedNodes();
        let authorities = [];
        for (var i in authoritieslist) {
          // 判断子节点是否存在子节点 如果存在直接请求并且提示 false
          if (!authoritieslist[i].hasOwnProperty("children")) {
            // 判断是否只选择一个 如果存在直接请求并且提示 false
            authoritieslist.map((li) => {
              authorities.push(li.id);
            });
            this.authorities = authorities;
            // if (authoritieslist.length == 1) {
            //   console.log(authoritieslist);

            // } else {
            //   this.$message.error("只选择一个节点");
            //   this.$refs.tree.setCheckedKeys([]);
            //   return
            // }
          } else {
            this.$message.error("只能选择当前分类最后的子分类");
            this.$refs.tree.setCheckedKeys([]);
            return
          }
        }
      },
      // 用户绑定角色
      bindUser() {
        var data = {
          userId: this.userId,
          roleIds: this.authorities || [],
        };
        httpPost(data, this.$api.bindRole).then((res) => {
          if (res.success) {
            this.$message.success('添加成功')
          } else {
            this.$message.error('添加失败')
          }
        });
      },
      // 获取用户列表
      getUserList() {
        var info = localStorage.getItem('info')
        var q = {}
        if (JSON.parse(info).type == 0) {
          q = {
            username: this.query.name
          }
        } else {
          q = {
            username: this.query.name,
            enterpriseId: JSON.parse(info).enterpriseId
          }
        }
        var data = {
          q: JSON.stringify(q),
          pageNum: this.pageNum,
          pageSize: 5,
        };
        httpGet(data, this.$api.getUserList).then((res) => {
          if (res.success) {
            var dt = res.data.list;
            dt.map((li, index) => {
              li.index = "";
              li.index = index;
            });
            this.tableData = dt;
            this.pageTotal = res.data.total;
          } else {
            this.$message.error('获取失败')
          }
        });
      },
      // 获取角色id
      getUserID() {
        var data = {
          pageNum: 1,
          pageSize: 100,
        };
        httpGet(data, this.$api.getRoleList).then((res) => {
          var obj = [];
          res.data.list.map((li) => {
            var str = {
              id: li.id,
              label: li.name,
            };
            obj.push(str);
          });
          this.treedata = obj;
        });
      },
      handleChange(value) {
        console.log(value);
      },
      // 触发搜索按钮
      handleSearch() {
        this.$set(this.query, "pageIndex", 1);
        this.$store.commit('increment', 1)
        this.getData();
      },
      getData() {
        var info = localStorage.getItem('info')
        var q = {}
        if (JSON.parse(info).type == 0) {
          q = {
            username: this.query.name
          }
        } else {
          q = {
            username: this.query.name,
            enterpriseId: JSON.parse(info).enterpriseId
          }
        }
        var data = {
          q: JSON.stringify(q),
          pageNum: this.pageNum,
          pageSize: 5,
        };
        httpGet(data, this.$api.getUserList).then((res) => {
          var dt = res.data.list;
          dt.map((li, index) => {
            li.index = "";
            li.index = index;
          });
          this.$store.commit('increment', 1)
          this.tableData = dt;
          this.pageTotal = res.data.total;
        });
      },
      // 删除操作
      handleDelete(index) {
        // 二次确认删除
        this.$confirm("确定要删除吗？", "提示", {
            type: "warning",
          })
          .then(() => {
            this.$message.success("删除成功");
            this.tableData.splice(index, 1);
          })
          .catch(() => {});
      },
      // 多选操作
      handleSelectionChange(val) {
        this.getIndex = val.index;
        this.userId = val.id;
        this.getroleId(val.id)
      },
      getroleId(id) {
        var data = {
          userId: id
        };
        httpGet(data, this.$api.getRolesByUser).then((res) => {
          if (res.success) {
            if (res.data.length > 0) {
              var defaultkeys = []
              this.$refs.tree.setCheckedKeys([]);
              res.data.map(li => {
                defaultkeys.push(li.id)
              })
              // defaultkeys.push(res.data[0].id)
              console.log(defaultkeys)
              this.defaultkeys = defaultkeys
            } else {
              this.defaultkeys = []
              this.$refs.tree.setCheckedKeys([]);
            }
          } else {
            this.$message.error('获取失败')
          }
        })
      },
      delAllSelection() {
        const length = this.multipleSelection.length;
        let str = "";
        this.delList = this.delList.concat(this.multipleSelection);
        for (let i = 0; i < length; i++) {
          str += this.multipleSelection[i].name + " ";
        }
        this.$message.error(`删除了${str}`);
        this.multipleSelection = [];
      },
      // 编辑操作
      handleEdit(index, row) {
        this.idx = index;
        this.form = row;
        this.editVisible = true;
      },
      // 保存编辑
      saveEdit() {
        this.editVisible = false;
        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
        this.$set(this.tableData, this.idx, this.form);
      },
      // 编辑操作
      handleEdit1() {
        this.editVisible1 = true;
      },
      // 保存编辑
      saveEdit1() {
        this.editVisible1 = false;
      },
      // 分页导航
      handlePageChange(val) {
        this.pageNum=val
        this.getUserList(val);
      }
    },
  };
</script>

<style scoped>
  .handle-box {
    margin-bottom: 20px;
  }

  .handle-select {
    width: 120px;
  }

  .handle-input {
    width: 300px;
    display: inline-block;
  }

  .table {
    width: 100%;
    font-size: 14px;
  }

  .red {
    color: #ff0000;
  }

  .mr10 {
    margin-right: 10px;
  }

  .mright {
    margin-right: 10px;
    display: inline-block;
  }

  .table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
  }

  .elrow {
    margin-bottom: 20px;
  }

  .grid-content {
    position: relative;
    z-index: 99;
    display: flex;
    align-items: center;
    overflow: hidden;
    justify-content: space-around;
    -webkit-box-align: center;
  }

  /* 加的 */
  .colposition {
    display: flex;
    align-items: center;
    position: relative;
    box-sizing: border-box;
    border: 2px solid hsla(0, 0%, 100%, 0.2);
    /* width: 100%; */
  }

  .grid-cont-right {
    flex: 1;
    text-align: left;
    padding-left: 20px;
    box-sizing: border-box;
    font-size: 16px;
    color: #666;
    font-size: 14px;
    line-height: 32px;
  }

  .grid-num {
    font-size: 24px;
  }

  .grid-con-icon {
    font-size: 50px;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
    color: #fff;
  }

  .grid-con-1 {
    position: relative;
  }

  .grid-con-1::before {
    position: absolute;
    content: "";
    top: 50%;
    right: 0;
    width: 1px;
    transform: translateY(-50%);
    height: 70px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border-left: 1px dashed #666;
  }

  .grid-con-1 .grid-con-icon {
    background: rgb(45, 140, 240);
  }

  .grid-con-1 .grid-num {
    /* color: rgb(45, 140, 240); */
    color: #333;
  }

  .grid-con-2 .grid-con-icon {
    background: rgb(100, 213, 114);
  }

  .grid-con-2 .grid-num {
    /* color: rgb(45, 140, 240); */
    color: #333;
  }

  .grid-con-3 .grid-con-icon {
    background: rgb(242, 94, 67);
  }

  .grid-con-3 .grid-num {
    color: rgb(242, 94, 67);
  }

  .treediv {
    border: 1px solid #d1dbe5;
    height: 512px;
    overflow: auto;
  }

  .prever {
    margin-bottom: 20px;
    cursor: pointer;
  }
</style>
<style>
  .el-table__body tr.current-row>td {
    background-color: yellow !important;
    /* color: #f19944; */
    /* 设置文字颜色，可以选择不设置 */
  }

  /* 用来设置当前页面element全局table 鼠标移入某行时的背景色*/
  /* .el-table--enable-row-hover .el-table__body tr:hover>td { */
  /* background-color:yellow; */
  /* color: #f19944; */
  /* 设置文字颜色，可以选择不设置 */
  /* } */
</style>
