<template>
  <div v-if="isLoad">
    <el-form-item label="公共维度">
      <el-row>
        <el-col :span="12">
          <el-input v-model="commonContentDimCatalogNames"  placeholder="请选择分类" :disabled="true"></el-input>
        </el-col>
        <el-col :span="4">
          <el-button size="small" @click="selectDimensionCatalog">选择</el-button>
        </el-col>
      </el-row>
    </el-form-item>
    <el-dialog title="选择维度栏目" :visible.sync="showDialog" width="30%">
      <common-dimensions-selector ref="dimSelector" :site-id="commonSite.id" :checked-ids="selectCommonDimCatalogIDs" @on-change="update"></common-dimensions-selector>
    </el-dialog>
  </div>
</template>

<script>
import CommonDimensionsSelector from './DimensionCatalogSelectorDialog.vue'

export default {
  components: {
    'common-dimensions-selector': CommonDimensionsSelector
  },

  props: {
    content: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },

  data() {
    return {
      isLoad: false,
      contentID: 0,
      commonSite: {},
      commonContentDimCatalogNames: '',
      commonContentDimCatalogIDSet: '',
      selectCommonDimCatalogIDs: '',
      showDialog: false,
      dimensionCatalogData: []
    }
  },

  watch: {
    content: async function() {
      this.contentID = this.content.contentID || this.content.ID
      let res = await axios.get(`/ui/commondemension/init?catalogID=${this.content.catalogID}&contentID=${this.contentID}`)
      if (res.data.status === 1) {
        this.isLoad = res.data.data.isLoad
      }
      if (this.isLoad) {
        this.$emit('callback')
        await this.getCommonDimension()
      }
    }
  },

  methods: {
    async getCommonDimension() {
      let res = await axios.get(`/ui/commondemension?catalogID=${this.content.catalogID}&contentID=${this.contentID}`)
      if (res.data.status === 1) {
        this.commonSite = res.data.data.commonSite
        let isDefault = res.data.data.isDefaultDimCatalogMapping
        let data = null
        if (isDefault) {
          data = res.data.data.defaultDimensionCatalogMapping
        } else {
          data = res.data.data.contentDimensionCatalogMapping
        }
        this.commonContentDimCatalogNames = _.values(data).join(',')
        if (!isDefault) {
          this.commonContentDimCatalogIDSet = _.keys(data).join(',')
        }
        this.selectCommonDimCatalogIDs = _.keys(data).join(',')
      }
    },

    async selectDimensionCatalog() {
      this.showDialog = true
    },

    update(selectedNodes) {
      let names = []
      let ids = []
      selectedNodes.forEach(item => {
        names.push(item.name)
        ids.push(item.ID)
      })
      this.commonContentDimCatalogNames = names.join(',')
      this.commonContentDimCatalogIDSet = ids.join(',')
      this.content.commonContentDimCatalogNames = this.commonContentDimCatalogNames
      this.content.commonContentDimCatalogIDSet = this.commonContentDimCatalogIDSet
    }
  }
}
</script>
