<template>
  <el-select :value="siteId" @change="siteChangeHandler" placeholder="请选择站点">
    <el-option
      v-for="item in siteList"
      :key="item.siteId"
      :label="item.siteName"
      :value="item.siteId">
    </el-option>
  </el-select>
</template>

<script>
import { listSite } from "@/api/site/site";
import { getSiteId, setSiteId } from "@/utils/cache/site";

export default {
  data() {
    return {
      siteId: '',
      siteList: [],
    }
  },
  mounted() {
    this.getSiteList();
  },
  methods: {
    getSiteList() {
      listSite({ page: 1, size: 1000 }).then(response => {
        const siteList = response.data.records || [];
        if (siteList.length === 0) {
          return;
        }
        this.siteList = siteList;
        const cachedSiteId = getSiteId();

        if (siteList.map(({siteId}) => siteId).includes(cachedSiteId)) {
          this.siteId = cachedSiteId;
        } else {
          this.siteId = siteList[0].siteId;
        }
      });
    },
    siteChangeHandler(v) {
      setSiteId(v);
      this.siteId = v;
    }
  },
  watch: {
    siteId(v) {
      this.$emit('change', v);
    }
  }
}
</script>

<style scoped>

</style>
