<template>
  <el-dialog
    :title="$t('pages.appManager.authDialog.dialog.title')"
    :visible="true"
    width="400px"
    :before-close="handleClose"
  >

    <el-form ref="form" :model="form">
      <el-checkbox-group v-model="form.resourceList" size="small" class="flex-l flex-wrap">
        <el-checkbox v-for="item in sysResourceList" :key="item.id" style=" margin-bottom:20px" :label="item.id">{{ item.resourceName }}
        </el-checkbox>
      </el-checkbox-group>
    </el-form>

    <div slot="footer">
      <el-button type="primary" @click="submit()">{{ $t('common.submit') }}</el-button>
    </div>
  </el-dialog>

</template>

<script>

import { getSysAdministratorAuthResourceByUserId, getAdministratorAuthTable, deleteAndAddAdministratorAuth } from '@/api/app-user'

export default {
  name: 'AdministratorAuth',
  props: {
    userId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      sysResourceList: [],
      activeUserId: '',
      listLoading: false,
      form: {
        userId: '',
        resourceList: []
      }
    }
  },
  watch: {
    userId: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal) {
          this.form.userId = newVal
          return
        }
      }
    }
  },
  created() {
    this.AdministratorAuthTable()
    this.renderData()
  },
  methods: {
    handleClose() {
      this.$emit('close')
    },
    AdministratorAuthTable() {
      const that = this
      that.listLoading = true
      getAdministratorAuthTable().then(res => {
        that.listLoading = false
        that.sysResourceList = res.body || []
      }).catch(er => {
        console.error(er)
        that.listLoading = false
      })
    },
    renderData() {
      const that = this
      that.listLoading = true
      getSysAdministratorAuthResourceByUserId(that.form.userId).then(res => {
        that.listLoading = false
        that.form.resourceList = res.body || []
      }).catch(er => {
        console.error(er)
        that.listLoading = false
      })
    },
    submit() {
      const that = this
      that.listLoading = true
      deleteAndAddAdministratorAuth(that.form).then(res => {
        that.listLoading = false
        that.$opsMessage.success()
        that.$emit('success', Object.assign({}, that.form))
        that.handleClose()
      }).catch(err => {
        that.listLoading = false
        that.$emit('fial', err)
        that.handleClose()
      })
    },
    accountHandleSuccess(data) {
      this.$message({
        message: this.$t('pages.appManager.administrator.message.success'),
        type: 'success'
      })
    }
  }
}
</script>
