<template>
  <el-dialog :title="(role && role.roleName) + $t('ec.role.assign')" :visible.sync="visible"   top="4%" class="roleUser ">
    <el-form v-loading="loading">
      <el-form-item :label="$t('ec.role.user')" label-width="100px">
        <ec-user-modal v-model="roleUsers" multiple :queryTenant="enableTenant" />
        <!--        <el-select v-model="roleUserList" multiple clearable filterable placeholder="请选择">-->
        <!--          <el-option-->
        <!--            v-for="item in userList"-->
        <!--            :key="item.id"-->
        <!--            :label="item.realName"-->
        <!--            :value="item.id"-->
        <!--          />-->
        <!--        </el-select>-->
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('ec.table.cancel') }}</el-button>
      <el-button type="primary" :loading="saveLoading" @click="updateUser">{{ $t('ec.table.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { findRoleUsers as getRoleUser, saveRoleAppUsers as updateRoleUser } from 'ecip-web/api/vue/role/sysrRoleApi'
const enableTenant = window._CONFIG['enableTenant'] === undefined ? true : window._CONFIG['enableTenant']

export default {
  name: 'RoleUserModal',
  data() {
    return {
      enableTenant,
      visible: false,
      loading: false,
      saveLoading: false,
      appId: '',
      role: {},
      roleUsers: '',
      roleUserList: []
    }
  },
  watch: {
    roleUsers: {
      handler(val) {
        this.roleUserList = val.Split(',')
      },
      immediate: true
    }
  },
  methods: {
    init(appId, role) {
      this.appId = appId
      this.role = role
      this.visible = true
      this.$nextTick(() => {
        if (role && role.id) {
          this.roleUser(role.id)
        } else {
          this.roleUserList = []
          this.roleUsers = ''
        }
      })
    },
    async roleUser(id) {
      try {
        this.loading = true
        const { data } = await getRoleUser(id)
        this.roleUserList = data
        this.roleUsers = data.join()
      } finally {
        this.loading = false
      }
    },
    updateUser() {
      this.$confirm(this.$t('ec.role.assignConfirm') + this.role.roleName, this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        try {
          this.saveLoading = true
          await updateRoleUser(this.role.id, this.appId, this.roleUserList)
          this.$notify.success(this.$t('ec.role.assign') + this.$t('ec.message.success'))
          this.visible = false
        } finally {
          this.saveLoading = false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
