<!--站点选择组件-->
<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="change">
          <el-option :label="item.siteName" :value="item.id" v-for="(item,index) in siteList" :key="index+'zdxeSelect'"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @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|Number,
        default:'',
        required:false
      }
    },
    data() {
      return {
        id:'',
        loading:false,
        siteList:[],
      }
    },
    computed:{
      ...mapGetters(["zdList"]),
    },
    methods:{
      onSubmit(){
        this.$emit('submitSite',this.id)
      },
      change(id){
        this.$emit('changeSite',id)
      },
      setDefaultSite(){
        const defaultSite = parseInt(this.defaultSiteId)
        if(defaultSite && this.siteList.find(item=>item.id === defaultSite)){
          this.id = defaultSite
        }else if(!defaultSite && this.siteList.length>0){
          this.id = this.siteList[0].id
        }
        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})
      }
    },
    mounted(){
      this.loading=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
            console.log("从store中获取站点列表数据",this.zdList,this.siteList)
            this.setDefaultSite()
          }
        }else{
          this.getList()
        }
      })
    }
  }
</script>
