<template>
<div class="search-bar" v-if="dimInfo.enable">
  <span class="search-name">维度：</span>
  <el-select placeholder="维度视图" style="width:100%;" v-model="dimensionID" @change="changeClickHandler" >
    <span><el-option v-for="dimension in dimensions" :key="dimension.ID" :label="dimension.name" :value="dimension.ID">
      {{dimension.name}}
    </el-option></span>
  </el-select>
</div>
</template>
<script>
import emitter from '../mixins/emitter.js'
export default {
  mixins: [emitter],
  props: {
    type: {
      type: [String, Number],
      default: ''
    },
    dimInfo: {
      type: Object
    },
    isGetDimid: {
      type: Boolean
    },
    siteId: {
      type: [String, Number]
    }
  },
  data() {
    return {
      dimensionID: 1,
      dimensions: [{ID: 1, code: 'default', name: '默认分类'}],
      loading: false
    }
  },
  watch: {
    dimInfo(val) {
      this.loadAll()
    },
    siteId(val) {
      this.loading = false
      this.loadAll()
    }
  },
  async created() {
    this.loadAll()
  },
  methods: {
    async loadAll() {
      if (this.dimInfo.enable && !this.loading) {
        await this.getDimensions()
        await this.getOldDimension()
        if (this.isGetDimid){
          this.loading = true
          return
        }
        await this.getCatalogTree()
        this.loading = true
      }
    },
    async getOldDimension() {
      try {
        let resp = await axios.get('/ui/dimensions/diminfo', {params: this.dimInfo})
        if (resp.data.data.dimensionID) {
          this.dimensionID = resp.data.data.dimensionID
        }
      } catch (e) {
      }
    },
    async getDimensions() {
      let res = await axios.get('/ui/dimensions', {params: {siteID: this.siteId ? this.siteId : 0}})
      this.dimensions = res.data.data
      this.dimensionID = this.dimensions ? this.dimensions[0].ID : this.dimensionID
    },
    async getCatalogTree() {
      let res = await axios.get(`/ui/dimensions/${this.dimensionID}/catalogs`, {params: {contentType: this.dimInfo.contentType ? this.dimInfo.contentType : '', type: this.dimInfo.type ? this.dimInfo.type : '', treeLevel: 9999}})
      this.callback(res.data.data)
    },
    handleNodeClick(data) {
      this.catalogID = data.ID
    },
    changeClickHandler(value) {
      this.dimensionID = value
      if (this.isGetDimid){
        this.callback({dimensionID: this.dimensionID})
      } else {
        this.getCatalogTree()
      }
    },
    callback(val) {
      this.$emit('callback', val)
    }
  }

}
</script>
<style scoped>
.dim_select_name{
  vertical-align: middle
}
.search-bar {
  cursor: auto;
  width: 100%;
  padding: 5px;
  border-bottom: 1px solid #f5f5f5;
  /* background-color: #f5f5f5; */
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: nowrap;
}
.search-name {
  width: 52px;
}
</style>
