<template>
  <cy-dialog ref="changeRole" :title="info ? '编辑角色' : '新增角色'">
    <el-form ref="roleForm" :model="roleForm" :rules="roleRules" label-width="120px" label-position="left" v-loading="isLoading">
      <el-form-item label="角色名称：" prop="name">
        <el-input
          v-model="roleForm.name"
          placeholder="请输入角色名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="分组到：" prop="type" v-if="!info || info.parent.id !== 1">
        <el-select v-model="roleForm.type" placeholder="请选择分组">
          <el-option
            v-for="item in roleList"
            :key="item.id + '_type'"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择权限" prop="ids" style="width: 100%;" :show-message="false" class="permission-role-tree">
        <el-tree
          :data="permissionList"
          show-checkbox
          node-key="id"
          ref="permissionTree"
          :default-checked-keys="roleForm.ids"
          :props="defaultProps">
        </el-tree>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button type="primary" @click="confirm('roleForm')">保存</el-button>
      <el-button type="normal" @click="$refs.changeRole.show = false">取消</el-button>
    </template>
  </cy-dialog>
</template>

<script>
import request from '@/utils/request'
export default {
  data() {
    return {
      roleList: [],
      permissionList: [],
      roleForm: {
        name: '',
        type: '',
        ids: []
      },
      roleRules: {
        name: [{ required: true, trigger: 'blur', message: '请输入角色名称' }],
        type: [{ required: true, trigger: 'change', message: '请选择分组' }],
        ids: [{ required: true, trigger: 'change', message: '请选择权限' }]
      },
      defaultProps: {
        children: 'childPermission',
        label: 'cname'
      },
      isLoading: false
    }
  },
  props: ['info'],
  mounted() {
    this.getAllPermission()
  },
  methods: {
    getTypeList() {
      request({
        url: '/role/findGroupRole',
        method: 'get'
      }).then(({ data }) => {
        this.roleList = data || []
      })
    },
    getAllPermission() {
      request({
        url: '/permission/findPermisionTree',
        method: 'get'
      }).then(({ data }) => {
        this.permissionList = data || []
      })
    },
    confirm() {
      this.roleForm.ids = this.$refs.permissionTree.getCheckedNodes(false, true).length ? this.$refs.permissionTree.getCheckedNodes(false, true).map(item => {
        return item.id
      }) : []
      this.$refs.roleForm.validate(flag => {
        if(flag) {
          this.submit()
        } else {
          this.$message.error('必填项不能为空')
        }
      })
    },
    submit() {
      this.isLoading = true
      let data = new FormData()
      if(this.info) {
        data.append('id', this.info.id)
      }
      data.append('name', this.roleForm.name)
      data.append('parent.id', this.roleForm.type)
      this.roleForm.ids.forEach((item, index) => {
        data.append(`permissions[${index}].id`, item)
      })
      request({
        url: this.info ? '/role/do_update' : '/role/do_add',
        method: 'post',
        data
      }).then(() => {
        this.isLoading = false
        this.$message.success(this.info ? '编辑成功' : '新增成功')
        this.$refs.changeRole.show = false
        let info = null
        if(this.info) {
          info = {...this.info, tempTime: Math.random()}
          info.parent.id = this.roleForm.type
        }
        this.$emit('close', info)
      })
    },
    openDialog() {
      if(this.info) {
        this.getRolePermission(this.info.id)
      }
      this.roleForm.name = this.info ? this.info.name : ''
      this.roleForm.type = this.info ? this.info.parent.id : ''
      this.roleForm.ids = []
      this.getTypeList()
      this.$refs.changeRole.show = !this.$refs.changeRole.show
    },
    getRolePermission(id) {
      this.isLoading = true
      request({
        url: '/role/do_get',
        method: 'get',
        params: {
          id
        }
      }).then(({ data }) => {
        this.roleForm.ids = data.permissions ? data.permissions.reduce((total, item) => {
          if(item.icon !== '1') {
            total.push(item.id)
          }
          return total
        }, []) : []
        // this.roleForm.ids = data.permissions ? data.permissions.map(item => {
        //   return item.id
        // }) : []
        this.isLoading = false
      }, err => {
        this.isLoading = false
      })
    },
  }
}
</script>

<style lang="scss">
.permission-role-tree .el-form-item__content {
    height: 200px;
    overflow: auto;
  }
</style>