<template>
  <el-select
    v-model="selecteValue"
    :loading="loading"
    :disabled="disabled"
    style="width: 100%;"
    :multiple="multiple"
    :multiple-limit="multipleLimit"
    :filterable="filterable"
    :clearable="clearable"
    @change="selectChanged"
  >
    <el-input v-model="selecteValue" style="display:none;" />

    <el-option v-for="(item, index) in list" :key="index" :value="item.id" :label="item.aliasName || item.countryName">
      <div class="flex-l">
        <img :src="item.nationalFlag" alt="" width="18">
        <span style="padding: 0px 5px;"> {{ (item.aliasName || item.countryName) }}</span>
      </div>
    </el-option>
  </el-select>
</template>

<script>
import { getCountryAlls } from '@/api/sys'
export default {
  name: 'ContrySelect',
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    multipleLimit: {
      type: Number,
      default: 0
    },
    filterable: {
      type: Boolean,
      default: true
    },
    clearable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      list: [],
      cacheList: [],
      selecteValue: ''
    }
  },
  created() {
    this.loadCountry()
  },
  methods: {
    loadCountry() {
      const that = this
      that.loading = true
      getCountryAlls().then(res => {
        that.loading = false
        that.list = res.body || []
        that.$nextTick(() => {
          that.selecteValue = that.value
        })
      }).catch(er => {
        that.loading = false
      })
    },
    selectChanged(val) {
      const item = this.list.filter((item) => item.id === val)
      if (item) {
        const contry = item[0]
        this.$emit('change', val, {
          id: contry.id,
          code: contry.alphaTwo || contry.alphaThree,
          name: contry.aliasName || contry.countryName,
          phonePrefix: contry.phonePrefix,
          nationalFlag: contry.nationalFlag
        })
      }
      this.$emit('input', val)
    }

  }
}
</script>
