<template>
  <el-dialog :title="$t('ec.common.relate') + $t('ec.tenant.relateArea')" :visible.sync="visible"  top="4%"  width="40%">
    <el-form v-loading="loading">
      <el-form-item :label="$t('ec.tenant.relateArea')" label-width="120px">
        <ec-select v-model="relationIds" :ec-data="areaList" 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="saveAreaRelations">{{ $t('ec.table.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getAreaList, saveAreaList } from 'ecip-web/api/vue/tenant/saasTenantApi'
import { getProvince } from 'ecip-web/api/vue/area/sysrAreaApi'

export default {
  name: 'TenantAreaModal',
  data() {
    return {
      visible: false,
      loading: false,
      saveLoading: false,
      record: {},
      relationIds: [],
      areaList: []
    }
  },
  methods: {
    init(record) {
      this.visible = true
      this.record = record
      this.$nextTick(async() => {
        this.loading = true
        const province = await getProvince()
        this.areaList = province.data
        const relationIds = await getAreaList(record.id)
        this.relationIds = relationIds.data
        this.loading = false
      })
    },
    saveAreaRelations() {
      this.$confirm(this.$t('ec.tenant.relateAreaConfirm'), 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 saveAreaList(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>
