<template>
  <div v-if="isRouterAlive">
    <el-row :gutter="20" class="gridBox" style="background: #fff; padding: 20px">
      <div class="container">
        <div class="handle-box">
          <selectoption></selectoption>
          <el-button type="primary" size="small" @click="handleEdit1" style="background: #FA8E00; border: none;">添加角色</el-button>
        </div>
        <div class="">
          <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
            highlight-current-row @row-click="handleSelectionChange" height="500">
            <el-table-column type="selection" width="55" align="center" v-if="selectstatus">
            </el-table-column>
            <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
            <el-table-column prop="name" 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-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>
      </div>
      <div class="perverBox">
        <div class="prever">
          <el-button type="primary" size="small" @click="preservation" style="background: #FA8E00; border: none;">保存设置</el-button>
        </div>
        <div class="treediv">
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div class="elTree">
              <div class="treeitem" v-for="(item,index) in  i18n.items" :key="index" v-show="item.status !=-1">
                <div class="trli"><i class="el-icon-caret-bottom" v-show="item.subs"></i>
                  <el-checkbox :label="item.key"><span>{{item.title}}</span> </el-checkbox>
                </div>
                <ul v-show="item.subs" class="treeli1">
                  <li v-for="(item1,index) in item.subs" :key="index" v-show="item1.status !=-1">
                    <div class="trli"><i class="el-icon-caret-bottom" v-show="item1.subs"></i>
                      <el-checkbox :label="item1.key"><span>{{item1.title}}</span> </el-checkbox>
                    </div>
                    <ul v-show="item1.subs" class="treeli1">
                      <li v-for="(item2,index) in item1.subs" :key="index" v-if="item2.status !=-1">
                        <div class="trli"><i class="el-icon-caret-bottom" v-show="item2.subs"></i>
                          <el-checkbox :label="item2.key"><span>{{item2.title}}</span> </el-checkbox>
                        </div>
                      </li>
                    </ul>
                  </li>
                </ul>
              </div>
            </div>
          </el-checkbox-group>
        </div>
      </div>
    </el-row>
    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <el-form ref="form" :model="form" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-input v-model="form.address"></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="编辑" :visible.sync="editVisible1" width="30%">
      <el-form ref="form" :model="form1" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="form1.name"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="value" placeholder="请选择">
            <el-option v-for="item in yhsflist" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="默认权限">
          <el-radio-group v-model="radio">
            <el-radio label="1">是</el-radio>
            <el-radio label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <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: '',
        checkList: [],
        i18n: [],
        selectstatus: false,
        isRouterAlive: true,
        query: {
          address: "",
          name: "",
          pageIndex: 1,
          pageSize: 10,
          options: [],
        },
        radio: "1",
        treedata: [{
            id: "STATISTICAL_ANALYSIS",
            label: "数据汇总",
            status: 0,
            children: [{
              id: "HOME_PAGE",
              label: "首页",
              status: 0
            }, {
              id: "Datavisualization",
              label: "大屏展示",
              status: 0
            }, ],
          },
          {
            id: "AREA_MANAGEMENT",
            label: "房源管理",
            status: 0,
            children: [{
              id: "STUDENT_DORMITORY",
              label: "房源列表",
              status: 0
            }, ],
          },
          {
            id: "OPERATIONS_MANAGEMENT",
            label: "业务管理",
            status: 0,
            children: [{
              id: "ACCOMMODATION_OPERATION",
              label: "门锁业务",
              status: 0,
              children: [{
                  id: "ACCOMMODATION_REGISTER",
                  label: "入住办理",
                  status: 0
                },
                {
                  id: "CHECK_OUT_MANAGEMENT",
                  label: "退住管理",
                  status: 0
                },
                {
                  id: "RENEWAL_HANDLING",
                  label: "续住管理",
                  status: 0
                },
              ],
            }, {
              id: "DOORMAGNETICSERVICE",
              label: "门磁业务",
              status: 0,
              children: [{
                id: "LINKMAN",
                label: "接警联系人",
                status: 0
              }],
            }, ],
          },
          {
            id: "PERSONNEL_MANAGEMENT",
            label: "人员管理",
            status: 0,
            children: [{
                id: "STUDENT_INFORMATION",
                label: "人员列表",
                status: 0
              },
              {
                label: "凭证管理",
                id: "RENT_SURRENDER_MANAGEMENT",
                status: 0
              },
              {
                label: "信息库",
                id: "INFORMATIONBASE",
                status: 0
              },
            ],
          },
          {
            id: "DEVICE_MANAGEMENT",
            label: "设备管理",
            status: 0,
            children: [{
              id: "DOOR_LOCK_DEVICE",
              label: "门锁设备",
              status: 0
            }, {
              id: "EQUIPMENTLIST",
              label: "门磁设备",
              status: 0
            }, ],
          },
          {
            id: "USER_MANAGEMENT",
            label: "用户管理",
            status: 0,
            children: [{
                id: "ACCOUNT_MANAGEMENT",
                label: "登录账号",
                status: 0
              },
              {
                id: "ROLE_PERMISSIONS",
                label: "角色权限",
                status: 0
              },
              {
                id: "BOUND_ROLE",
                label: "绑定角色",
                status: 0
              },
            ],
          },
          {
            id: "LOG_MANAGEMENT",
            label: "日志管理",
            status: 0,
            children: [{
                id: "journal",
                label: "系统日志",
                status: 0
              },
              {
                id: "DOORLOCKLOG",
                label: "门锁日志",
                status: 0,
                children: [{
                    id: "UnlockRecord",
                    label: "开锁记录",
                    status: 0
                  },
                  {
                    id: "warningLog",
                    label: "警告日志",
                    status: 0
                  },
                  {
                    id: "DeviceFeedbackLog",
                    label: "设备反馈日志",
                    status: 0
                  },
                ]
              },
              {
                id: "DOORMAGNETICLOG",
                label: "门磁日志",
                status: 0,
                children: [{
                  id: "ALARMRECORD",
                  label: "报警日志",
                  status: 0
                }]
              },
            ],
          },
        ],
        defaultProps: {

          children: "children",
          label: "label",
        },
        options: [{
            value: "选项1",
            label: "超级系统管理员",
          },
          {
            value: "选项2",
            label: "业务员",
          },
        ],
        yhsflist: [{
            value: 0,
            label: "超级管理员"
          },
          {
            value: 1,
            label: "高级管理员"
          },
          {
            value: 2,
            label: "中级管理员"
          },
          {
            value: 3,
            label: "低级管理员"
          },
        ],
        authorities: [],
        authorities1: [],
        authoritiesName: [],
        value: "",
        tableData: [],
        multipleSelection: [],
        delList: [],
        editVisible: false,
        editVisible1: false,
        pageTotal: 0,
        form: {},
        form1: {},
        idx: -1,
        id: -1,
        userInfo: {
          type: ''
        }
      };
    },
    created() {
      this.userInfo = JSON.parse(localStorage.getItem('info'))
      this.getUserID()
      this.getmenu()
      this.selectoption = JSON.parse(localStorage.getItem('selectoption'))
      this.selectoptionValue = localStorage.getItem('tenantId')
    },
    methods: {
      selectTenantId(e) {
        localStorage.setItem('tenantId', e)
        this.reload()
      },
      getmenu() {
        httpGet('', this.$api.userInfo).then(res3 => {
          var authorities = res3.data.authorities
          localStorage.setItem('info', JSON.stringify(res3.data))
          if (res3.data.type == 0) {
            this.i18n = this.$language.cn.i18n;
          } else {
            var i18n = this.$language.cn.i18n.items
            for (var i = 0; i < i18n.length; i++) {
              if (i18n[i].subs) {
                const Index1 = authorities.findIndex((item) => {
                  return item == i18n[i].key
                })
                if (Index1 == -1) {
                  i18n[i].status = -1
                }
                for (var j = 0; j < i18n[i].subs.length; j++) {
                  const Index = authorities.findIndex((item) => {
                    return item == i18n[i].subs[j].key
                  })
                  if (Index == -1) {
                    i18n[i].subs[j].status = -1
                    console.log(i18n[i].subs[j])
                  } else {
                    i18n[i].status = 0
                  }
                }
              } else {
                const Index = authorities.findIndex((item) => {
                  return item == i18n[i].key
                })
                if (Index == -1) {
                  i18n[i].status = -1
                }
              }
            }
            this.i18n = this.$language.cn.i18n;
            this.$nextTick(() => {
              this.i18n.items = i18n
              console.log(this.i18n.items)
            });
          }
        })
      },
      // 修改角色权限
      preservation() {
        var data = {
          roleId: this.roleId,
          authorities: this.authorities,
        };
        httpPost(data, this.$api.updateRole).then((res) => {
          if (res.code == 200) {
            this.$message.success("更新成功");
            this.isRouterAlive = false;
            this.$nextTick(function() {
              this.getUserID();
              this.editVisible1 = false;
              this.isRouterAlive = true;
            });
          }
        });
      },
      // 获取角色id
      getUserID() {
        var data = {
          pageNum: 1,
          pageSize: 100,
        };
        httpGet(data, this.$api.getRoleList).then((res) => {
          this.tableData = res.data.list;
          this.pageTotal = res.data.total || 10;
        });
      },
      getCheckedKeys(e) {
        console.log(e);
      },
      // 勾选权限
      handleCheckChange() {
        // var authoritieslist = this.$refs.tree.getCheckedNodes();
        var authoritieslist = this.checkList;
        var authorities = [],
          authoritiesName = [];
        // authoritieslist.map((li) => {
        //   authorities.push(li.id);
        //   authoritiesName.push(li.label);
        // });
        // this.authoritiesName = authoritiesName;
        this.authorities = authoritieslist;
        // console.log(this.treedata)
      },
      // 数组去重
      unique(arr) {
        let newArr = [];
        let len = arr.length;
        for (let i = 0; i < len; i++) {
          if (newArr.indexOf(arr[i]) == -1) {
            newArr.push(arr[i]);
          }
        }
        return newArr;
      },
      // 获取用户列表
      getUserList() {
        // var data={
        //   name:"zw001"
        // }
        httpGet("", this.$api.getUserList).then((res) => {
          this.tableData = res.data.list;
          this.pageTotal = res.data.total || 50;
        });
      },
      handleChange(value) {
        console.log(value);
      },
      // 获取 easy-mock 的模拟数据
      getData() {
        httpPost().then((res) => {
          this.tableData = res.list;
          this.pageTotal = res.pageTotal || 50;
        });
      },
      // 触发搜索按钮
      handleSearch() {
        // this.$set(this.query, "pageIndex", 1);
        // this.getData();

      },
      // 删除操作
      handleDelete(index, row) {
        var roleIds = [row.id];
        var data = {
          roleIds: roleIds,
        };
        this.$confirm("确定要删除吗？", "提示", {
            type: "warning",
          })
          .then(() => {
            httpPost(data, this.$api.deleteRole).then((res) => {
              this.$message.success("删除成功");
              this.tableData.splice(index, 1);
            });
          })
          .catch(() => {});
      },
      // 多选操作
      handleSelectionChange(val) {
        this.authorities1 = [];
        // this.$refs.tree.setCheckedKeys([]);
        this.authorities1 = JSON.parse(val.authorities);
        this.checkList = this.authorities1 || []
        this.roleId = val.id;
        // this.multipleSelection = val;
      },
      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() {
        var data = {
          name: this.form1.name,
          type: this.value,
        };
        httpPost(data, this.$api.addRole).then((res) => {
          if (res.code == 200) {
            console.log("11111111111111");
            this.$message.success(res.message);
            this.editVisible1 = false;
            this.isRouterAlive = false;
            this.$nextTick(function() {
              this.getUserID();
              this.editVisible1 = false;
              this.isRouterAlive = true;
            });
          }
        });
      },
      // 分页导航
      handlePageChange(val) {
        this.$set(this.query, "pageIndex", val);
        this.getData();
      },
    },
  };
</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);
  }
  .perverBox{
    border: 1px solid #d1dbe5;
    box-sizing: border-box;
    padding: 30px;
  }
  .treediv {
    height: 500px;
    overflow-y: auto;
    padding: 10px 0;
    border-top: 1px dashed #ccc;
    border-bottom: 1px dashed #ccc;
  }

  .prever {
    margin-bottom: 20px;
  }

  .current-row {
    background: #000;
    color: #fff;
  }

  .elTree {
    padding: 10px;
  }

  .treeli1 {
    padding-left: 30px;
  }

  .el-icon-caret-bottom {
    color: #999;
    font-size: 12px;
    margin-right: 4px;
  }

  .trli {
    height: 24px;
  }
  .gridBox{
    display: -ms-grid;
    display: -webkit-grid;
    grid-template-columns:0 2fr 2fr 0;
    vertical-align: top;
    display: grid;
  }
  .gridBox>div{
    box-sizing: border-box;
    margin: 0 10px;
  }
</style>
