<template>
  <el-tabs class="my-tabs" v-model="activeName" type="card" @tab-click="handleClick">
    <el-tab-pane label="权限组列表" name="roleList">

      <div class="container">
        <div class="tab-header">
          <el-form ref="form" :inline="true" :model="page" label-width="80px">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="权限组名称">
                  <el-input v-model="page.params.groupName" clearable></el-input>
                </el-form-item>
                <el-button @click="getList(1)">查询</el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <!-- table -->
        <el-table :data="roleTable" border style="width: 100%;">
          <el-table-column label="序号" width="80px" type="index" align="center">
          </el-table-column>
          <el-table-column label="操作" width="220px" align="center">
            <template slot-scope="scope">
              <el-button @click="editRow(scope.row)" type="primary" size="mini"> 修改</el-button>
              <el-button @click="delRow(scope.row)" type="danger" size="mini"> 删除</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="groupName" label="权限组名称" align="center"></el-table-column>
          <el-table-column prop="groupCode" label="权限组编码" align="center"></el-table-column>
          <el-table-column prop="remarks" label="说明" align="center"></el-table-column>
        </el-table>
        <pagination :total="page.total" :page.sync="page.current" :limit.sync="page.size" @pagination="pagination" />

        <!-- 编辑权限组信息 -->
        <el-dialog :title="dialogTitle + '权限组信息'" :visible.sync="editDialog" width="40%">
          <table class="e-table" cellspacing="0">
            <tr>
              <td>权限组名称</td>
              <td>
                <el-input v-model="roleForm.groupName" style="width:300px"></el-input>
              </td>
            </tr>
            <tr>
              <td>权限组编码</td>
              <td>
                <el-input v-model="roleForm.groupCode" style="width:300px"></el-input>
              </td>
            </tr>
            <tr>
              <td>权限组说明</td>
              <td>
                <el-input v-model="roleForm.remarks" style="width:300px"></el-input>
              </td>
            </tr>
            <tr>
              <td>关联菜单列表</td>
              <td>
                <div style=" height: 300px;width:300px;overflow:auto;overflow-x:hidden;">
                  <el-tree v-loading="loading" :data="treedata" ref="Tree" show-checkbox node-key="sid"
                    :default-checked-keys="checkedId" :props="sourcedefaultProps" @check-change="checkchange">
                  </el-tree>
                </div>
              </td>
            </tr>
          </table>
          <div style="margin-top: 20px; text-align: center;">
            <el-button type="primary" @click="save()">保 存</el-button>
            <el-button @click="editDialog = false">关 闭</el-button>
          </div>
        </el-dialog>
      </div>
    </el-tab-pane>
    <!-- 新增权限组信息 -->
    <el-tab-pane label="新增权限组" name="addrole" class="listconadd">
      <el-card class="box-card">
        <table class="e-table" cellspacing="0">
          <tr>
            <td>权限组名称</td>
            <td>
              <el-input v-model="formBackup.groupName" style="width:300px"></el-input>
            </td>
          </tr>
          <tr>
            <td>权限组编码</td>
            <td>
              <el-input v-model="formBackup.groupCode" style="width:300px"></el-input>
            </td>
          </tr>
          <tr>
            <td>权限组说明</td>
            <td>
              <el-input v-model="formBackup.remarks" style="width:300px"></el-input>
            </td>
          </tr>
          <tr>
            <td>关联菜单列表</td>
            <td>
              <div style=" height: 300px;width:300px;overflow:auto;overflow-x:hidden;">
                <el-tree v-loading="loading" :data="treedata" ref="Tree2" show-checkbox node-key="sid"
                  :props="sourcedefaultProps" @check-change="checkchange">
                </el-tree>
              </div>
            </td>
          </tr>
        </table>
        <div style="margin-top: 20px; text-align: center;">
          <el-button type="primary" @click="add()">保 存</el-button>
        </div>
      </el-card>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
  import req from '@/api/system/purviewManage/purviewManage.js'
  import {
    pageList,
  } from '@/api/system/menu/index.js'
  export default {
    data() {
      return {
        dialogTitle: '',
        activeName: 'roleList',
        menusPage: {
          current: 1,
          size: 10,
          total: 0,
          params: {
            name: '',
            psid: '',
          }
        },

        roleForm: {
          sid: "",
          groupName: "",
          groupCode: '',
          remarks: '',
          list: []
        },
        formBackup: {
          sid: "",
          groupName: "",
          groupCode: '',
          remarks: '',
          list: []
        },
        page: {
          total: 0, // 默认数据总数
          current: 1, // 默认开始页面
          size: 10, // 每页的数据条数
          params: {
            groupName: '',
          },
        },
        roleTable: [],
        loading: false,
        checkedId: [],
        sourcedefaultProps: {
          children: 'children',
          label: 'name'
        },
        editDialog: false,
        checkStrictly: false,
        treedata: [],
        groupSid: ""
      };
    },
    mounted() {
      this.formBackup = Object.assign({}, this.roleForm),
        this.getList()
      this.roleMenus()
    },
    methods: {
      // 获取授权菜单树形
      roleMenus() {
        this.menusPage.params.orgSid = window.sessionStorage.getItem('orgSid')
        pageList(this.menusPage).then((res) => {
          this.treedata = res.data
        })
      },

      pagination(val) { // 分页函数
        this.page.current = val.pageNum
        this.page.size = val.pageSize
        this.getList()
      },
      // 分页列表
      getList(flag) {
        if (flag == '1') {
          this.page.current = 1
        }
        req.listPage(this.page).then(res => {
          this.page.total = res.data.total
          this.roleTable = res.data.records
        })
      },
      handleClick(tab, event) {
        if (tab.name == 'addrole') {
          this.dialogTitle = '新增'
        } else {
          this.getList()
        }
      },
      editRow(row) {
        this.dialogTitle = '编辑'
        this.editDialog = true
        this.roleForm = Object.assign({}, row)
        this.checkedId = []
        this.groupSid = row.sid

        this.$nextTick(() => {
          this.$refs.Tree.setCheckedKeys([]); //先清空之前选中的节点，再给赋值
        });

        for (var i = 0; i < row.list.length; i++) {
          var item = row.list[i]
          if (item.children == "1") {
            this.checkedId.push(item.menuSid)
          }

        }
        this.$nextTick(() => {
          this.$refs.Tree.setCheckedKeys(this.checkedId); //先清空之前选中的节点，再给赋值
        });


        console.log('checkedId', this.checkedId)

        // this.checkedId = this.recursiveFilter(row.list)
      },

      checkchange(data, checked, indeterminate) {
        console.log("checkchange", data);
      },


      // /**
      //  * 递归过滤嵌套数组（树形结构）
      //  * @param arr {Array}要过滤的原始数据
      //  * @param type {Boolean} 你要过滤的关键词
      //  *
      //  */
      // recursiveFilter(arr, type) {
      //   let data = arr.filter(item => item.checked == type).map((item) => {
      //     item = Object.assign({}, item)
      //     if (item.children) {
      //       //递归循环
      //       item.children = that.recursiveFilter(item.children, type)
      //     }
      //     return item.sid
      //   })

      //   console.log('recursiveFilter', data)

      //   return data
      // },
      delRow(row) {
        this.$confirm('确定要删除该权限组吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          req.deleteBySid([row.sid]).then(res => {
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          })
        })
      },
      // 保存权限组
      save() {

        if (this.roleForm.groupName == '') {
          this.$message({
            message: '权限组名称不能为空',
            type: 'warning'
          })
          return
        }

        if (this.roleForm.groupCode == '') {
          this.$message({
            message: '权限组编码不能为空',
            type: 'warning'
          })
          return
        }

        let roleMenus = []
        roleMenus = this.$refs.Tree.getCheckedNodes(false, true)
        // roleMenus = this.$refs.Tree.getCheckedKeys()
        console.log('已选节点、半选节点node', roleMenus)
        this.roleForm.list = []
        for (var i = 0; i < roleMenus.length; i++) {
          var item = roleMenus[i]
          this.roleForm.list.push({
            groupSid: this.groupSid,
            sourceSid: item.sourceSid,
            menuSid: item.sid,
            menuName: item.name,
            children: item.children.length > 0 ? "0" : "1"
          })
        }
        console.log('已选节点、半选节点sid', this.roleForm.list)

        if (this.roleForm.list.length == 0) {
          this.$message({
            message: '关联菜单不能为空',
            type: 'warning'
          })
          return
        }

        req.savePurviewManage(this.roleForm).then(res => {
          if (res.code == '200') {
            this.getList()
            this.reset()
            this.editDialog = false
            this.$message({
              message: res.msg,
              type: 'success'
            })

            this.$refs.Tree.setCheckedKeys([])
          }
        })

      },

      // 新增权限组
      add() {

        if (this.formBackup.groupName == '') {
          this.$message({
            message: '权限组名称不能为空',
            type: 'warning'
          })
          return
        }

        if (this.formBackup.groupCode == '') {
          this.$message({
            message: '权限组编码不能为空',
            type: 'warning'
          })
          return
        }

        let roleMenus = []
        roleMenus = this.$refs.Tree2.getCheckedNodes(false, true)
        // roleMenus = this.$refs.Tree.getCheckedKeys()
        console.log('已选节点、半选节点node', roleMenus)
        this.formBackup.list = []
        for (var i = 0; i < roleMenus.length; i++) {
          var item = roleMenus[i]
          this.formBackup.list.push({
            groupSid: "",
            sourceSid: item.sourceSid,
            menuSid: item.sid,
            menuName: item.name,
            children: item.children.length > 0 ? "0" : "1"
          })
        }
        console.log('已选节点、半选节点sid', this.formBackup.list)

        if (this.formBackup.list.length == 0) {
          this.$message({
            message: '关联菜单不能为空',
            type: 'warning'
          })
          return
        }

        req.savePurviewManage(this.formBackup).then(res => {
          if (res.code == '200') {
            this.getList()
            this.reset()
            this.editDialog = false
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$refs.Tree2.setCheckedKeys([])
            this.activeName = 'roleList'
          }
        })

      },

      reset() {
        this.roleForm = {
          sid: "",
          groupName: "",
          groupCode: '',
          remarks: '',
          list: []
        };
        this.formBackup = {
          sid: "",
          groupName: "",
          groupCode: '',
          remarks: '',
          list: []
        };
        this.page = {
          total: 0, // 默认数据总数
          current: 1, // 默认开始页面
          size: 10, // 每页的数据条数
          params: {
            groupName: '',
          },
        }
      },

    }
  };
</script>

<style scoped>
  .el-select>.el-input {
    display: block;
    width: 300px;
  }

  /deep/ .tab-header .el-select {
    width: 180px;
  }

  .my-tabs {
    margin-top: 10px;
  }
</style>
