<template>
  <div class="global">
    <div class="mainContainer">
      <div class="title">{{ title }}角色</div>
      <el-form  ref="ruleForm"  :model="roleGroup"  :rules="rules"  label-width="100px"  class="demo-ruleForm">
        <el-form-item label="角色组名:" prop="rname">
          <el-input v-model="roleGroup.rname" />
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="roleGroup.rremark" />
        </el-form-item>
      </el-form>
      <div class="tree">
        <div class="treeLabel">功能:</div>
        <div class="treeShow">
          <el-tree
            ref="resourseTree"
            :data="data"
            show-checkbox
            node-key="resourceCode"
            :props="defaultProps"
            :default-checked-keys="checkedKeysResourceCodes"
          />
        </div>
      </div>
      <div  class="btns">
        <el-button type="success" plain @click="cancel()">取消</el-button>
        <el-button type="success" @click="btnSave('ruleForm')">保存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
// 引入接口
import {
  resourcesTree,
  getUserInfo,
  addUserInfo,
  updateUserInfo,
  roleIsExit,
  checkUserInfo,
  editResourcesTree,
  loadResourceDefine
} from '@/api/system/userManagement/role'
export default {
  name: 'AddRole',
  data() {
    var checkRname = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入角色组'))
      } else {
        if(value == this.copyRname){
          callback()
        }else{
          let params = {
            rName: value
          }
          roleIsExit(params).then((res) => {
            if (res.code == 200) {
              if (res.data > 0) {
                callback(new Error('该角色组已存在'))
              } else {
                callback()
              }
            } else {
              callback(new Error(res.msg))
            }
          })
        }
      }
    }
    return {
      checkedKeysResourceCodes: [],
      // 标题
      title: '',
      // 参数id
      id: '',
      // 按钮类型
      type: '',
      // 校验规则
      rules: {
        rname: [{ required: true, trigger: 'blur', validator: checkRname }]
      },

      // 初始化数据
      roleGroup: {
        rname: '',
        rremark: ''
      },
      defaultProps: {
        children: 'children',
        label: 'resourceName'
        // id:'resourceCode'
      },
      data: [],
      copyRname:''
    }
  },

  mounted() {
    var routeParams = this.$route.query
    console.log(routeParams, 'routeParams')
    this.id = routeParams.id

    this.type = routeParams.type
    console.log(this.id)
    // 对表单进行重置
    this.$nextTick(() => {
      this.$refs['ruleForm'].resetFields()
    })
    if (this.type == 2) {
      this.title = '新增'
    } else if (this.type == 3) {
      this.title = '修改'

      this.checkList()
      this.editTreeInfo()
      console.log('//////')
    }

    this.getTreeInfo()
  },
  methods: {
    // 获取资源树接口
    getTreeInfo() {
      resourcesTree()
        .then((res) => {
          if (res.code == 200) {
            this.data = res.data
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },

    // 修改资源数
    editTreeInfo() {
      var params = {
        id: this.id
      }

      editResourcesTree(params).then((res) => {
        if (res.code == 200) {
          if (res.data != null) {
            for (let index = 0; index < res.data.length; index++) {
              const ele = res.data[index]
              console.log(ele, 'ele.....')
              this.checkedKeysResourceCodes.push(ele)
            }
            //  this.roleGroup.resourceCodes=this.checkedKeysResourceCodes;
            console.log(this.checkedKeysResourceCodes, 'this.checkedKeysResourceCodes')
            this.getTreeInfo()
          }
        }
      })
    },

    // 新增接口
    addList() {
      var data = this.roleGroup
      addUserInfo(data).then((res) => {
        console.log(data, '新增data')
        if (res.code == 200) {
          loadResourceDefine().then(response => {
            if(response.code == 200){
              this.$message.success('新增成功')
              this.$router.push({
                path: '/systemManagement/user/roleManagement',
                query: {
                  name:'RoleManagement'
                }
              })
            }else{
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          })
        }
      })
    },

    // 修改接口
    updateList() {
      var data = this.roleGroup
      updateUserInfo(data)
        .then((res) => {
          if (res.code == 200) {
            loadResourceDefine().then(response => {
              if(response.code == 200){
                this.$message.success('修改成功')
                this.$router.push({
                  path: '/systemManagement/user/roleManagement',
                  query: {
                    name:'RoleManagement'
                  }
                })
              }else{
                this.$message({
                  type: 'error',
                  message: response.msg
                })
              }
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },

    // 查看接口
    checkList() {
      var id = this.id
      checkUserInfo(id)
        .then((res) => {
          if (res.code == 200) {
            this.roleGroup = res.data
            this.copyRname = res.data.rname
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },

    // // 取消按钮
    cancel() {
      this.$router.push({
        path: '/systemManagement/user/roleManagement',
        query: {
          name:'RoleManagement'
        }
      })
    },

    // 点保存按钮
    btnSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // this.addList();
          console.log(this.type, 'this.type..')

          console.log(this.$refs.resourseTree.getCheckedNodes(), '资源树')
          var checkedNodes = this.$refs.resourseTree.getCheckedNodes()
          var resourceCodes = []
          for (let index = 0; index < checkedNodes.length; index++) {
            const ele = checkedNodes[index]
            resourceCodes.push(ele.resourceCode)
          }
          console.log(resourceCodes, '......')
          resourceCodes = resourceCodes.join(',')
          console.log(resourceCodes, '数组')
          this.roleGroup.resourceCodes = resourceCodes
          console.log(
            this.roleGroup.resourceCodes,
            'this. roleGroup.resourceCodes'
          )

          if (this.type == 2) {
            this.addList()
          } else if (this.type == 3) {
            this.updateList()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.btns{
    text-align:right;
}
.title {
  margin-bottom: 20px;
}
.tree {
  display: flex;
  .treeLabel {
    width: 120px;
    text-align: right;
  }
  .treeShow {
    width: 600px;
    // height: 400px;
    // max-height: 100px;
    // overflow-y:scroll ;
    margin-left: 20px;
    // background:rgb(244, 240, 240);
  }
}
</style>
<style scoped>
.el-input {
  width: 20%;
}
.el-tree {
  background: rgb(245, 243, 243);
}
</style>
