<template>
  <el-select
    v-model="selecteValue"
    :loading="loading"
    :disabled="disabled"
    style="width: 100%;"
    :multiple="multiple"
    :multiple-limit="multipleLimit"
    :filterable="filterable"
    :clearable="clearable"
    :placeholder="placeholder"
    @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.regionName" />
  </el-select>
</template>

<script>
import { regionConfigTable } from '@/api/sys'
export default {
  name: 'SelectSystemRegion',
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    sysOrigin: {
      type: String,
      require: true,
      default: ''
    },
    placeholder: {
      type: String,
      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 {
      listCacheData: {},
      list: [],
      loading: false,
      selecteValue: ''
    }
  },

  watch: {
    sysOrigin: {
      handler(newVal) {
        if (newVal) {
          const cacheData = this.listCacheData[newVal]
          if (!cacheData) {
            this.listCacheData[newVal] = {
              loading: false,
              finish: false,
              list: []
            }
          }

          this.list = []
          this.loading = false
          this.loadRegin()
        }
      },
      immediate: true
    }
  },
  created() {
  },
  methods: {
    clearValue() {
      this.selecteValue = ''
      this.selectChanged('')
    },
    loadRegin() {
      const that = this
      const cacheData = this.listCacheData[that.sysOrigin]
      if (cacheData.finish === true) {
        that.list = cacheData.list
        that.loading = cacheData.loading
        return
      }
      cacheData.loading = true
      that.loading = true
      regionConfigTable({
        sysOrigin: that.sysOrigin
      }).then(res => {
        cacheData.loading = false
        that.loading = false
        cacheData.list = res.body || []
        cacheData.finish = true
        that.list = cacheData.list
        that.$nextTick(() => {
          that.selecteValue = that.value
          this.emitInput(that.selecteValue)
        })
      }).catch(er => {
        that.loading = false
        cacheData.loading = false
      })
    },
    selectChanged(val) {
      this.emitInput(val)
      const item = this.list.filter((item) => item.id === val)
      if (item) {
        this.emitChange(val, item[0])
      }
    },
    emitInput(val) {
      this.$emit('input', val)
    },
    emitChange(val, item) {
      this.$emit('change', val, item)
    }
  }
}
</script>
