<template>
  <div>
    <el-input placeholder="选择企业" :size="size" :disabled="true" :readonly="readonly" style="line-hight:40px"
      v-model="name" class="input-with-select">
      <el-button slot="append" :disabled="disabled" :readonly="readonly" @click="showUserSelect"
        icon="el-icon-search"></el-button>
    </el-input>
    <qySelect ref="qySelect" @doSubmit="selectQyToInput" :limit="limit" :selectData="selectData"></qySelect>
  </div>
</template>
<script>
import qySelect from './QySelectDialog'
import EnterpriseInfoService from '@/api/enterpriseinfo/enterpriseInfoService'

export default {
  data () {
    return {
      name: '',
      labelValue: this.value,
      selectData: [],
      isOnlyOne: false
    }
  },
  props: {
    limit: Number,
    value: String,
    size: {
      type: String,
      default: () => { return 'small' }
    },
    readonly: {
      type: Boolean,
      default: () => { return false }
    },
    disabled: {
      type: Boolean,
      default: () => { return false }
    }
  },
  components: {
    qySelect
  },
  enterpriseInfoService: null,
  beforeCreate () {
  },
  watch: {
    value: {
      handler (newVal) {
        if (!this.isOnlyOne) {
          this.selectData = []
          if (newVal) {
            newVal.split(',').forEach((id) => {
              if (EnterpriseInfoService) {
                EnterpriseInfoService.queryById(id).then(({data}) => {
                  if (!this.isOnlyOne) {
                    if (data && data.id !== '') {
                      this.selectData.push(data)
                    }
                  }
                })
              }
            })
          }
        }
      },
      immediate: true,
      deep: false
    },
    selectData: {
      handler (newVal) {
        this.name = newVal.map(site => { return site.name }).join(',')
      },
      immediate: false,
      deep: false
    }
  },
  mounted () {

  },
  methods: {
    selectQyToInput (sites) {
      console.log("GG:"+JSON.stringify(sites))
      this.selectData = sites
      this.$emit('valueChanges', this.selectData, this)
      this.labelValue = sites.map(site => { return site.id }).join(',')
      this.name = sites.map(site => { return site.name }).join(',')
      this.$emit('getValue', this.labelValue, this.name,
        sites
      )
      this.$emit('valueChange', this.selectData)
    },
    showUserSelect () {
      this.$refs.qySelect.init()
    }
  }
}
</script>
<style>
.el-form-item__content .el-input-group {
  vertical-align: middle;
}

.el-tag+.el-tag {
  margin-left: 5px;
  margin-bottom: 5px;
}
</style>
