<!-- 企业选择器（上拉加载） -->
<!-- change方法输出对象 { companyId, companyName } -->
<!--
<CompanySelect v-model="searchParams.companyId" search-mode />
<CompanySelect v-model="formData.companyName" @change="Object.assign(formData, $event)" />
-->
<template>
  <el-select
    v-selectScroll="loadMore"
    v-bind="$attrs"
    :value="value"
    remote
    filterable
    clearable
    placeholder="请输入企业名称"
    class="bgimg_none"
    :loading="pageLoading"
    :remote-method="searchCompany"
    @input="$emit('input', $event)"
    @change="handleCompanyChange"
    @focus="searchCompany()"
  >
    <el-option v-if="searchMode" value="" label="全部" />
    <el-option v-for="(opt, j) in companyList" :key="opt.id" :label="opt.name" :value="opt.id" />
  </el-select>
</template>
<script>
import { getCompanyPage } from '@/apiV2/company'
import { debounce } from 'lodash'
export default {
  name: 'CompanySelect',
  props: {
    value: {
      type: String,
      default: ''
    },
    searchMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      queryText: '',
      companyId: '',
      companyList: [],
      pageLoading: false,
      pageObj: { // 企业列表(页码)
        size: 10,
        current: 1,
        pages: 1,
        total: 0
      }
    }
  },
  async created() {
  },
  methods: {
    searchCompany: debounce(function(name) { // 搜索企业
      this.pageLoading = true
      this.pageObj.current = 1
      this.queryText = name
      this.getCompanyList().finally(() => {
        this.pageLoading = false
      })
    }, 100, true),
    loadMore(isBottom) { // 上拉加载
      if (!isBottom) return
      if (this.pageObj.current + 1 > this.pageObj.pages) return
      this.pageObj.current++
      this.getCompanyList()
    },
    async getCompanyList() { // 获取企业列表
      const { current, size } = this.pageObj
      return getCompanyPage(Object.assign({ name: this.queryText }, { current, size })).then(res => {
        if (res.success) {
          this.pageObj.pages = res.data.pages
          this.pageObj.total = res.data.total
          this.companyList = this.pageObj.current === 1 ? res.data.records : [...this.companyList, ...res.data.records]
        }
      })
    },
    handleCompanyChange(e) { // 选中企业
      const company = this.companyList.find(item => item.id == e) || { id: null, name: null }
      console.log('companyInfo', company, e)
      const { id, name } = company
      this.$emit('change', { companyId: id, companyName: name })
    }
  }
}
</script>
<style lang="scss"></style>
