<template>
  <el-dialog :title="$t('ec.common.relate') + $t('ec.tenant.relateTenant')" :visible.sync="visible"  top="4%"  width="40%">
    <el-form v-loading="loading">
      <el-form-item :label="$t('ec.tenant.relateTenant')" label-width="120px">
        <ec-select v-model="relationIds" :ec-data="tenantList" multiple :str-result="false" value-field="id" attr-name="name" />
      </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="saveTenantRelations">{{ $t('ec.table.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getTenantList, getTenantRelations, saveTenantRelations } from 'ecip-web/api/vue/tenant/saasTenantApi'
export default {
  name: 'TenantRelationModal',
  data() {
    return {
      visible: false,
      loading: false,
      saveLoading: false,
      record: {},
      relationIds: [],
      tenantList: []
    }
  },
  methods: {
    init(record) {
      this.visible = true
      this.record = record
      this.$nextTick(async() => {
        this.loading = true
        await this.getTenantList(record.id)
        await this.getTenantRelations(record.id)
        this.loading = false
      })
    },
    async getTenantRelations(recordId) {
      const { data } = await getTenantRelations(recordId)
      this.relationIds = data
    },
    async getTenantList(excludeId) {
      const { data } = await getTenantList({ id: excludeId })
      this.tenantList = data
    },
    saveTenantRelations() {
      this.$confirm(this.$t('ec.tenant.relateTenantConfirm'), 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 saveTenantRelations(this.record.id, this.relationIds)
          this.$notify.success(this.$t('ec.common.relate') + this.$t('ec.tenant.relateArea') + this.$t('ec.message.success'))
          this.$emit('refreshData')
          this.visible = false
        } finally {
          this.saveLoading = false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
