<!--站点选择组件-->
<template>
  <div class="zd-select-container">
    <el-form :inline="true">
      <el-form-item label="站点选择">
        <el-select v-model="id" placeholder="请选择换电站名称" :loading="loading" loading-text="正在加载数据" @change="onSubmit">
          <el-option :label="item.siteName" :value="item.siteId" v-for="(item,index) in siteList" :key="index+'zdxeSelect'"></el-option>
        </el-select>
      </el-form-item>
<!--      <el-form-item>-->
<!--        <el-button type="primary" :loading="searchLoading" @click="onSubmit">搜索</el-button>-->
<!--      </el-form-item>-->
    </el-form>
  </div>
</template>

<style scoped lang="scss">

</style>
<script>
import {getAllSites} from '@/api/ems/zddt'
import {mapGetters} from "vuex"
  export default {
    props:{
      getListByStore:{
        type:Boolean,
        default:false,
        required:false
      },
      defaultSiteId:{//默认展示的站点ID
        type:String,
        default:'',
        required:false
      }
    },
    data() {
      return {
        id:'',
        loading:false,
        searchLoading:false,
        siteList:[],
      }
    },
    computed:{
      ...mapGetters(["zdList"]),
    },
    methods:{
      onSubmit(){
        this.$emit('submitSite',this.id)
      },
      setDefaultSite(){
        const defaultSite = this.defaultSiteId
        if(defaultSite && this.siteList.find(item=>item.siteId === defaultSite)){
          this.id = defaultSite
        }else if(!defaultSite && this.siteList.length>0){
          this.id = this.siteList[0].siteId
        }
        this.$emit('submitSite',this.id)
      },
      getList(){
       return getAllSites().then(response => {
          this.siteList = response.data || []
          console.log("获取站点列表返回数据",response,this.siteList)
          this.setDefaultSite()
        }).finally(() => {this.loading=false;this.searchLoading=false})
      }
    },
    mounted(){
      this.loading=true
      this.searchLoading=true
      this.$nextTick(()=>{
        if(this.getListByStore){
          if(this.zdList.length === 0){
            this.getList().then(()=>{
              this.$store.commit('SET_ZD_LIST', this.siteList)
              console.log("从store中获取站点列表数据,但是store中的zdList=[]，所以从接口获取数据",this.zdList,this.siteList)
            })
          }else{
            this.siteList = this.zdList
            this.loading=false
            this.searchLoading=false
            console.log("从store中获取站点列表数据",this.zdList,this.siteList)
            this.setDefaultSite()
          }
        }else{
          this.getList()
        }
      })
    }
  }
</script>
