<template>
  <div class="mainBox">
    <!--搜索功能 start------------------------------------------------------------>
    <div class="layerBoxNoBg">
      <div>
        <el-button type="primary" @click="openWindow()">添加角色</el-button>
      </div>
    </div>
    <!--搜索功能 end------------------------------------------------------------>

    <!--表格内容 start------------------------------------------------------------>
    <div class="layerBox">
      <tableTitle :name="tableDivTitle"/>
      <el-row>
        <template>
          <el-table :data="tableData" style="width: 100%">
            <el-table-column fixed prop="id" label="编号" width="50"></el-table-column>
            <el-table-column prop="role_name" label="角色名称"></el-table-column>
            <el-table-column prop="remark" label="职能描述"></el-table-column>
            <el-table-column prop="users_count" label="成员数量"></el-table-column>
            <el-table-column prop="sort" label="排序"></el-table-column>
            <el-table-column prop="created_at" label="添加时间"></el-table-column>
            <el-table-column fixed="right" label="操作" width="200" header-align="center">
              <template slot-scope="scope">
                <div class="listBtnBox">
                  <div v-if="scope.row.id !== 1" class="listDeleteBtn" @click="deleteRow(scope.row.id)"><i class="el-icon-edit-outline"></i>删除</div>
                  <div class="listEditBtn" @click="editRow(scope.row.id)"><i class="el-icon-edit-outline"></i>编辑</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-row>
    </div>

    <!--分页 start------------------------------------------------------------>
    <div class="alignBox">
      <el-row>
        <el-col :span="24">
          <el-pagination :current-page="getApiData.page" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-size="10" layout="total, prev, pager, next, jumper" :total="allCount"></el-pagination>
        </el-col>
      </el-row>
    </div>
    <!--分页 end------------------------------------------------------------>
    <!--表格内容 end------------------------------------------------------------>

    <!--弹出框 start------------------------------------------------------------>
    <el-dialog :title="editId ? '编辑角色' : '添加角色'" :visible.sync="windowStatus" :close-on-click-modal="false">
      <el-form :model="form" ref="form" :rules="formRules" autocomplete="off" label-position="left">
        <div class="formDiv">
          <el-form-item label="角色名称：" :label-width="formLabelWidth" prop="role_name" class="custom-align-right">
            <el-input v-model="form.role_name" autocomplete="off" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item label="职能描述：" :label-width="formLabelWidth" prop="remark" class="custom-align-right">
            <el-input type="textarea" v-model="form.remark" class="custom-textarea" placeholder="请输入职能描述"></el-input>
          </el-form-item>
          <el-form-item label="排序：" :label-width="formLabelWidth" prop="" class="custom-align-right">
            <el-input v-model="form.sort" autocomplete="off" placeholder="请输入排序"></el-input>
          </el-form-item>
          <el-form-item label="权限：" :label-width="formLabelWidth" prop="rule" class="custom-align-right">
            <div class="treeBox" v-loading="loading">
              <el-tree
                ref="tree"
                :data="roleData"
                show-checkbox
                node-key="id"
                :default-expanded-keys="expandedKeys"
                :default-checked-keys="checkedKeys"
                :props="defaultProps">
              </el-tree>
              <!--没有被选中的父级在halfCheckedNodes,halfCheckedKeys属性中-->
            </div>
          </el-form-item>
          <input type="hidden" v-model="form.rule" />
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div>
          <el-button @click="closeWindow">取 消</el-button>
          <el-button type="primary" @click="addData" v-if="editId==0">提交</el-button>
          <el-button type="primary" @click="editData" v-else>修改</el-button>
        </div>
      </div>
    </el-dialog>
    <!--弹出框 end------------------------------------------------------------>

  </div>
</template>

<script>
//引入公用样式
import '@/styles/global.less';
//表格标题
import tableTitle from './components/tableTitle';

export default {
  components: {
    tableTitle,//表格标题
  },
  data() {
    //0.全局操作 start ------------------------------------------------------------>
    //表单验证
    const validateEmpty = (rule,value,callback) => {
      if (value.length == 0) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    //数组不能为空
    const validateArray = (rule,value,callback) => {
      if (value.length == 0) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    //0.全局操作 end ------------------------------------------------------------>

    return {
      //1.列表和分页相关 start ------------------------------------------------------------>
      tableDivTitle:"角色管理",
      tableData: [],//列表
      allCount:0,//总条数
      editId:0,//要修改的网站id
      getApiData:{
        page:1,//当前是第几页
        pageSize:10,//一共多少条
      },
      //分页相关 end ------------------------------------------------------------>

      //2.弹出框设置 start ------------------------------------------------------------>
      //是否显示弹出窗口
      windowStatus:false,
      formLabelWidth: '120px',
      isShowTable:1,//是否显示表格
      //弹出框设置 end ------------------------------------------------------------>

      //3.搜索相关 start ------------------------------------------------------------>
      //搜索相关 end ------------------------------------------------------------>

      //3.弹出框中的表单设置 start ------------------------------------------------------------>
      //3.1 表单收集的数据
      form: {
        role_name:"",//角色名称
        rule:[],//权限
        remark:"",//职能描述
        sort:0//排序
      },
      expandedKeys:[],//展开的节点  
      checkedKeys:[],//选中的节点 
      roleData:[],//菜单树
      loading:true,//加载中
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      //3.2表单验证规则
      formRules: {
        //角色名称不能为空
        role_name:[{required:true,trigger:'blur',validator:validateEmpty}],
        //职能描述不能为空
        remark:[{required:true,trigger:'blur',validator:validateEmpty}],
        //排序不能为空
        //sort:[{required:true,trigger:'blur',validator:validateEmpty}],
        //权限不能为空
        rule:[{required:true,trigger:'blur',validator:validateArray}],
      },
      //弹出框中的表单设置 end ------------------------------------------------------------>
    }
  },
  methods: {
    //1.列表和分页相关 start ------------------------------------------------------------>
    //1.1 获取内容
    getData(){
      this.$store.dispatch('userRole/roleList',this.getApiData).then(res=> {
        this.allCount = res.data.count;
        this.tableData = res.data.rows;
      })
    },
    //1.2 列表内容分页
    //直接跳转
    handleSizeChange(val) {
      this.getApiData.page = val;
      this.getData();
    },
    //1.3 点击分页
    handleCurrentChange(val) {
      this.getApiData.page = val;
      this.getData();
    },
    //1.4 获取菜单树
    getAllMenuList(){
      this.$store.dispatch('userRole/getAllMenuList').then(res=> {
        console.log(res)
        this.roleData = res.data;
      })  
    },
    //1.5 删除角色
    deleteRow(id){
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("当前删除：" + id)
        this.$store.dispatch('userRole/delRole',{id:id}).then(res=> {
          this.getData();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'warning',
            message: '网络错误，请重试！'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消删除'
        });
      });
    },
    //列表和分页相关 end ------------------------------------------------------------>

    //2.弹出框设置 start ------------------------------------------------------------>
    //2.1 打开弹出框
    openWindow() {
      this.form.role_name = "";
      this.form.remark = "";
      this.form.sort = "";
      this.loading = false;
      //清空弹出框
      // this.$nextTick(() => {
      //   //请空选中的节点
      //   this.$refs.tree.setCheckedKeys([]);
      //   //还原搜索的状态
      //   this.$refs.tree.root.childNodes.forEach((e) => {
      //     e.expanded = false;
      //   });
      //   // 收回树中所有展开的节点
      //   this.collapseAllNodes(this.$refs.tree.root.childNodes);
      this.getAllMenuList();
      //this.clearToServe();
      this.windowStatus = true;
      //this.$refs.form.clearValidate();
    },
    //2.2 关闭弹出框
    closeWindow(){
      this.windowStatus = false;
      this.clearToServe();
      this.$refs.form.clearValidate();
    },
    //2.3 清空提交窗口
    clearToServe(){
      //重置窗口
      this.editId = "";
      this.expandedKeys = [];
      //this.checkedKeys = [];
      this.$nextTick(() => {
        //请空选中的节点
        this.$refs.tree.setCheckedKeys([]);
        //还原搜索的状态
        this.$refs.tree.root.childNodes.forEach((e) => {
          e.expanded = false;
        });
      });
      this.form.role_name = "";
      this.form.remark = "";
      this.form.sort = "";
    },
    //弹出框设置 end ------------------------------------------------------------>

    //4.添加 start ------------------------------------------------------------>
    addData(){
      this.form.id = this.editId;
      //如果排序不填，默认排序传递数字
      if(this.form.sort == ""){
        this.form.sort = 0;
      }
      //半选的节点
      let supplement = [];
      let allKeys = this.$refs.tree.getHalfCheckedNodes();
      if(allKeys.length > 0){
        for(let i = 0; i < allKeys.length; i++){
          supplement.push(allKeys[i].id);
        }
      }
      console.log(supplement)
      //选中的节点
      let checkedArr = this.$refs.tree.getCheckedKeys();
      this.form.rule = checkedArr;
      console.log(checkedArr)
      //合并节点
      this.form.rule = [...new Set([...supplement, ...checkedArr])];
      console.log(this.form.rule)
      //提交数据
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$store.dispatch('userRole/addRole',this.form).then(res=> {
            this.$message({
              type: 'success',
              message: '已成功添加角色！'
            });
            console.log(res)
            this.closeWindow();
            this.getData();
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })

    },
    //添加 end ------------------------------------------------------------>

    //4.编辑 start ------------------------------------------------------------>
    //回显数据
    editRow(id){
      this.openWindow();
      this.loading = true;
      //设置要编辑的id
      this.editId = id;
      this.$store.dispatch('userRole/roleInfo',{id:id}).then(res=> {
        console.log(res)
        // this.$nextTick(() => {
        //   //请空选中的节点
        //   this.$refs.tree.setCheckedKeys([]);
        //   //还原搜索的状态
        //   this.$refs.tree.root.childNodes.forEach((e) => {
        //     e.expanded = false;
        //   });
        // });

        //回显用户权限
        // this.expandedKeys = res.data.rule;
        // this.checkedKeys = res.data.rule;
        //  this.isCheck = false;
        //  this.$nextTick(() => {
        //    this.isCheck = false;
        // })

        //加1秒延迟等待dom加载
        let that = this;
        setTimeout(() => {
          res.data.rule.forEach((i,n) => {
            var node = that.$refs.tree.getNode(i);
            //console.log(node)
            if(node){
              if(node.isLeaf){
                that.$refs.tree.setChecked(node,true);
              }
            }
          });
          that.loading = false;
        },1000)
        
        //回显用户名称
        this.form.role_name = res.data.role_name;
        //回显职能描述
        this.form.remark = res.data.remark;
        //回显排序
        this.form.sort = res.data.sort;
      }).catch(() => {
        this.$message.error('网络错误，请重试！');
      })
    },
    //提交编辑
    editData(){
      this.form.id = this.editId;
      //如果排序不填，默认排序传递数字
      if(this.form.sort == ""){
        this.form.sort = 0;
      }
      //半选的节点
      let supplement = [];
      let allKeys = this.$refs.tree.getHalfCheckedNodes();
      if(allKeys.length > 0){
        for(let i = 0; i < allKeys.length; i++){
          supplement.push(allKeys[i].id);
        }
      }
      console.log(supplement)
      //选中的节点
      let checkedArr = this.$refs.tree.getCheckedKeys();
      this.form.rule = checkedArr;
      console.log(checkedArr)
      //合并节点
      this.form.rule = [...new Set([...supplement, ...checkedArr])];
      console.log(this.form.rule)

      //提交数据
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$store.dispatch('userRole/updateRole',this.form).then(res=> {
            console.log(res)
            this.closeWindow();
            this.$message({
              type: 'success',
              message: '修改成功！'
            });
            this.getData();
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    },
    //编辑 end ------------------------------------------------------------>

    //5.tree start ------------------------------------------------------------>
    checkChange(data) {
      const node = this.$refs.tree.getNode(data.id);
      this.setNode(node);
    },
    setNode(node) {
      console.log(node, "node");
      if (node.checked) {
        //如果当前是选中checkbox,则递归设置父节点和父父节点++选中
        this.setParentNode(node);
      } else {
        //当前是取消选中,将所有子节点都取消选中
        this.setChildenNode(node);
      }
    },
    setParentNode(node) {
      if (node.parent) {
        for (const key in node) {
          if (key === "parent") {
            node[key].checked = true;
            this.setParentNode(node[key]);
          }
        }
      }
    },
    setChildenNode(node) {
      let len = node.childNodes.length;
      for (let i = 0; i < len; i++) {
        node.childNodes[i].checked = false;
        this.setChildenNode(node.childNodes[i]);
      }
    },
    //5.tree end ------------------------------------------------------------>

  },
  mounted(){
    //获取页面列表
    this.getData();
    //获取菜单树
    this.getAllMenuList();
  } 
}
</script>

<style scoped lang="less">
.layerBoxNoBg {
  padding: 30px 0 0 0;
}
//表单微调 start------------------------------------------------------------>*/
::v-deep .custom-form-item > .el-form-item__label {
  line-height: 140px !important;
}
::v-deep .custom-textarea .el-textarea__inner {
  resize: none; /* 禁止用拖拽调整大小 */
}
::v-deep .custom-align-right .el-form-item__label {
  text-align: right; /* 设置标签文字右对齐 */
}
::v-deep .el-select-group__title {
  color: #909399;
}
::v-deep .el-select {
  width: 100% !important;
}
</style>
