<template>
<el-dialog
  v-loading="loading"
  :show-close="false"
  :close-on-click-modal="false"
  :visible.sync="isShow"
  :title="this.curObj && this.curObj.id ? '编辑角色' : '添加角色'"
  :fullscreen="false"
  width="470px"
  custom-class="xl-dialog"
  center>
  <base-form style="width:400px" :data="formData" ref="ruleForm" :isInline="false" labelWidth="80px">
    <div slot="otherItem" class="scoped-tree">
      <!-- check-strictly -->
      <el-tree
        :data="curData"
        show-checkbox
        node-key="id"
        :default-expanded-keys="checkedIds"
        :default-checked-keys="checkedIds"
        ref="menuTree"
        :props="defaultProps">
      </el-tree>
    </div>
    <div slot="footer">
      <el-button class="xl-form-btn t2" @click="close">关 闭</el-button>
      <el-button class="xl-form-btn t1" @click="close('confirm')">确定</el-button>
    </div>
  </base-form>
</el-dialog>
</template>
<script>
export default {
  props: {
    isShow: Boolean,
    curObj: Object
  },
  mixins,
  data() {
    return {
      formData: [],
      curData: [],
      checkedIds: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      loading: true,
    }
  },
  watch: {
    isShow: function(val) {
      if (val) {
        let params = {...this.curObj}
        this.checkedIds = params.permissions_ids || []
        this.formData = [
          {label: '角色名称', key: 'name', rules: 1},
          {label: '角色描述', key: 'description', rules: 1},
        ]
        this.setDefaultValue(params)
      }
    }
  },
  created () {
    this.getMenu()
  },
  methods: {
    getMenu () {
      this.$api.base.admpermissionslist().then(res => {
        this.curData = [...res]
      })
    },
    systemChange (val) {
      // console.log(val)
    },
    close (str) {
      if (str === 'confirm') {
        this.$refs['ruleForm'].$refs['baseForm'].validate((valid) => {
          if (valid) {
            const oldform = this.$refs.ruleForm.baseForm
            let params = {...oldform}
            let str = 'admrolesadd'
            if(this.curObj && this.curObj.id) {
              params.id = this.curObj.id
              str = 'admrolesedit'
            }
            const resIds = this.$refs.menuTree.getCheckedNodes(false, false).map(item=> {
              return item.id
            })
            params.node = resIds.join(',')
            this.$api.base[str](params).then(data => {
              this.$msgs('保存成功!')
              this.$emit('close', params)
              // this.setDefaultValue()
            })
          }
        })
      } else {
        this.$emit('close')
        this.setDefaultValue()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .scoped-tree {
  height: 300px;
  overflow-y: auto;
  .el-tree {
    background: #f7f7f7;
  }
}
</style>