<!-- 项目选择器（上拉加载） -->
<!-- change方法输出对象 { ProjectId, ProjectName } -->
<!--
<ProjectSelect v-model="searchParams.ProjectId" search-mode />
<ProjectSelect v-model="formData.ProjectName" @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="searchProject"
    @input="$emit('input', $event)"
    @change="handleProjectChange"
    @focus="searchProject()"
  >
    <el-option v-if="searchMode" value="" label="全部" />
    <el-option v-for="(opt, j) in list" :key="opt.projectNo" :label="opt.name" :value="opt.projectNo" />
  </el-select>
</template>
<script>
import {getProjectList} from '@/apiV2/projectManage'
import { debounce } from 'lodash'
export default {
  name: 'ProjectSelect',
  props: {
    value: {
      type: String,
      default: ''
    },
    searchMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      queryText: '',
      ProjectId: '',
      list: [],
      pageLoading: false,
      pageObj: { //列表(页码)
        size: 10,
        current: 1,
        pages: 1,
        total: 0
      }
    }
  },
  async created() {
  },
  methods: {
    searchProject: debounce(function(name) { // 搜索项目
      this.pageLoading = true
      this.pageObj.current = 1
      this.queryText = name
      this.getProjectList().finally(() => {
        this.pageLoading = false
      })
    }, 100, true),
    loadMore(isBottom) { // 上拉加载
      if (!isBottom) return
      if (this.pageObj.current + 1 > this.pageObj.pages) return
      this.pageObj.current++
      this.getProjectList()
    },
    async getProjectList() { // 获取项目列表
      const { current, size } = this.pageObj
      return getProjectList(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.list = this.pageObj.current === 1 ? res.data.records : [...this.list, ...res.data.records]
        }
      })
    },
    handleProjectChange(e) { // 选中项目
      const Project = this.list.find(item => item.id == e) || { id: null, name: null }
      console.log('ProjectInfo', Project, e)
      const { id, name } = Project
      this.$emit('change', { ProjectId: id, ProjectName: name })
    }
  }
}
</script>
<style lang="scss"></style>
