<template>
  <div class="fullQuickEditor detail-content-box scroll" v-loading="dataLoading">
    <component v-bind:is="currentComp" :content.sync="content" :showButton="false" :site-config="siteConfig" @refreshlist="getContentList"  @catalog-change="catalogChange" @loaded="dataLoading = false" :content-id="nid" :catalog-id="ncid">
    <!-- 组件在 vm.currentview 变化时改变！ -->
    </component>
  </div>
</template>
<script>
import ArticleDetail from '../article/articleEditor.vue'
import FileDetail from '../media/components/FileDetail.vue'
import ImageGroup from '../media/components/ImageGroupDetail.vue'
import AudioDetail from '../media/components/AudioDetail.vue'
import VideoDetail from '../media/components/VideoDetail.vue'
import VideoGroup from '../media/components/VideoGroupDetail.vue'
import ContentDetail from './components/ContentDetail.vue'
const contentTypes = ['article', 'file', 'image', 'audio', 'video', 'videogroup', 'content']
export default {
  Name: 'ContentEditor',
  componentName: 'ContentEditor',
  components: {
    'article-detail': ArticleDetail,
    'file-detail': FileDetail,
    'image-detail': ImageGroup,
    'audio-detail': AudioDetail,
    'video-detail': VideoDetail,
    'videogroup-detail': VideoGroup,
    'content-detail': ContentDetail
  },
  provide() {
    return {
      loadContent: this.initContent
    }
  },
  props: {
    contentType: {
      type: String,
      default: ''
    },
    contentId: {
      type: [Number, String],
      default: ''
    },
    catalogId: {
      type: [Number, String],
      default: ''
    }
  },
  data() {
    return {
      siteConfig: {},
      content: {
        titleStyle: { color: '' },
        shortTitleStyle: { color: '' },
        subTitleStyle: { color: '' },
        logoFile: '',
        bodyText: ''
      },
      ntype: this.contentType,
      ncid: this.$route.query.cid,
      nid: this.contentId,
      dataLoading: false,
      siteID: 0
    }
  },
  filters: {
    changeType: function(val) {
      switch (val) {
        case 'Article':
          return 'article-detail'
        case 'File':
          return 'file-detail'
        case 'Image':
          return 'image-group-detail'
        case 'Audio':
          return 'audio-detail'
        case 'Video':
          return 'video-detail'
        case 'VideoGroup':
          return 'video-group'
        default:
          return 'content-detail'
      }
    }
  },
  computed: {
    currentComp () {
      let compName = this.ntype.toLowerCase()
      if (contentTypes.includes(compName)) {
        return compName + '-' + 'detail'
      } else {
        return 'content-detail'
      }
    }
  },
  beforeCreate() {
    // UEditor影响到了editormd的渲染导致行标处出现问题，暂未找到更合适的方法解决
    if (this.$route.query.format === 'Markdown' && window.UE) {
      location.reload()
    }
    if (window.DetailComponents && window.DetailComponents.length > 0) {
      for (let compIdx in window.DetailComponents) {
        let comp = window.DetailComponents[compIdx]
        if (comp.name && comp.component) {
          contentTypes.push(comp.name.toLowerCase())
          Vue.component(comp.name.toLowerCase() + '-detail', comp.component)
        }
      }
    }
  },
  created() {
    if (this.$route.query.type === 'Article') {
      this.dataLoading = true
    }
    this.siteID = this.$root.siteID
    this.initParams()
  },
  mounted() {
    this.getSiteConfig()
    this.initContent()

    this.$on('load-content', () => {
      this.initContent()
    })
    this.$on('content-list', (val) => {
      this.getContentList(val)
    })
  },
  methods: {
    async catalogChange(catalog, article) {
      this.ncid = catalog.ID
      this.catalogID = catalog.ID
      article && Object.assign(this.content, article)
      this.$router.replace(`${this.$route.path}?type=${this.ntype}&cid=${this.ncid}`)
    },
    initParams() {
      let id = this.$route.params.id && this.$route.params.id !== 'new' ? this.$route.params.id : ''
      this.nid = id || this.contentId
      let query = this.$route.query
      this.ncid = query.cid ? query.cid : this.catalogId
      this.ntype = query.type ? query.type : this.contentType
      if (!this.nid) {
        this.content.logoFile = ''
      }
    },
    async initContent() {
      this.initParams()
      if (this.ntype) {
        let type = this.nid ? this.nid : 'init'
        let resp = await axios.get(`/ui/contentcore/contents/${type}`, {params: {contentType: this.ntype, catalogID: this.ncid}})
        if (resp.data.status === 1) {
          this.content = Object.assign(
            {
              titleStyle: { color: '' },
              subTitleStyle: { color: '' },
              shortTitleStyle: { color: '' },
              bodyText: ''
            },
            resp.data.data
          )
          // 新建文章时，避免重复保存内容
          if (type === 'init' & resp.data.data.method === 'ADD'){
            this.content.addContentID = resp.data.data.contentID
          }
          this.content.bodyText = this.content.bodyText || ''
        }
      } else {
        this.content = {
          titleStyle: { color: '' },
          subTitleStyle: { color: '' },
          shortTitleStyle: { color: '' },
          ID: this.nid,
          catalogID: this.catalogId,
          contentTypeID: this.contentType,
          templateFlag: 'N'
        }
      }
      let dimInfo = Object.assign(
        {},
        {
          enable: true,
          catalogId: this.content.catalogID,
          contentId: this.content.ID,
          contentType: this.content.contentTypeID,
          dimensonID: this.content.dimensionID
        }
      )
      this.content = Object.assign({}, this.content, { dimInfo: dimInfo })
      this.loadUserPreferences()
    },
    loadUserPreferences() {
      let userPreferences = JSON.parse(localStorage.userPreferences)
      if (!this.nid) {
        let autoFillEditor = userPreferences.autoFillContentEditor === 'Y'
        let autoFillAuthor = userPreferences.autoFillContentAuthor === 'Y'
        let userName = localStorage.realName || localStorage.userName
        if (autoFillEditor) {
          this.content.editor = userName
        }
        if (autoFillAuthor) {
          this.content.author = userName
        }
      }
      this.content.showSubTitleAndShortTitle = userPreferences.showSubTitleAndShortTitle === 'Y'
    },
    getContentList(val) {
      val && this.initContent()
      // 全局刷新列表
      // if (window.refreshContentList) {
      //   window.refreshContentList()
      // }
    },
    async getSiteConfig() {
      let res = await axios.get(`/ui/sites/${this.siteID}/extends`)
      if (res.data.status === 1) {
        this.siteConfig = res.data.data
        // 获取数据后存 localStorage，编辑器中需要的地方直接从 localStorage 中取
        localStorage.ContentQuickEditor_siteConfig = JSON.stringify(this.siteConfig)
      }
    }
  }
}
</script>
<style scoped>
.fullQuickEditor {
  max-width: 1280px;
  margin: 0 auto;
}
.fullQuickEditor >>> .btn-move-catalog {
  position: absolute;
  right: 2px;
  top: 5px;
  padding: 8px 4px;
}
</style>
