<template>
  <el-select v-loading="loading" filterable :value="value" @input="$emit('input', $event)">
    <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
  </el-select>
</template>

<script>
import { createService } from '@/utils/apiService'
import service from '@/utils/apiService'
import { isExternal } from '@/utils/validate'
export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    dataUrl: {
      type: String,
      default: ''
    },
    projectId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      options: []
    }
  },
  watch: {
    dataUrl(url) {
      this.loadOptions()
    }
  },
  created() {
    this.loadOptions()
  },
  methods: {
    loadOptions() {
      if (this.dataUrl) {
        var url = this.dataUrl
        url = url.replace('{projectId}', this.projectId)
        if (isExternal(url)) {
          this.loading = true
          createService()({
            url: url,
            method: 'get'
          }).then(res => {
            this.options = res
          }).finally(() => {
            this.loading = false
          })
        } else {
          if (!url.startsWith('/')) {
            url = '/' + url
          }
          this.loading = true
          service({
            url: url,
            method: 'get'
          }).then(res => {
            this.options = res
          }).finally(() => {
            this.loading = false
          })
        }
      }
    }
  }
}
</script>
