<template>
  <ele-modal
    :visible.sync="visible"
    title="IP 查询"
    width="500px"
    append-to-body
    @close="cancel"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="create-form"
    >
      <el-form-item label="IP:" prop="ip">
        <el-input v-model="form.ip" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="地址:" prop="result">
        <el-input v-model="form.result" placeholder="展示查询 IP 结果" readonly />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save" :loading="loading">
        确定
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
import * as AreaApi from '@/api/config/elencoRegionale'

const defForm = {
  ip: '',
  result: ''
}

export default {
  name: 'AreaForm',
  data() {
    return {
      visible: false,
      loading: false,
      form: { ...defForm },
      rules: {
        ip: [{ required: true, message: 'IP 地址不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    /** 打开弹窗 */
    open() {
      this.form = { ...defForm }
      this.visible = true
    },

    /** 取消 */
    cancel() {
      this.form = { ...defForm }
      this.visible = false
    },

    /** 保存 */
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          const data = { ip: this.form.ip.trim() }
          AreaApi.getAreaByIp(data.ip)
            .then((res) => {
              console.log(res)
              if(res.code == 0) {
                this.form.result = res.data
                this.$message.success('查询成功')
              } else {
                this.$message.error(res.message)
              }
              
            })
            .catch((e) => {
              console.error(e)
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
