<template class="editor-workspace-el-row">
  <div class="fullQuickEditor">
    <div class="layout-row-main" style="min-height:40px;max-height:50px;overflow:hidden;margin:0;">
      <div class="layout-col-tree" style="background:inherit;margin:8px 0 0 10px;overflow:hidden;line-height:40px;">
        <el-col :span="8" style="text-align:center;">维度视图：
        </el-col>
        <el-col :span="16">
          <el-select placeholder="维度视图" style="width:100%;" v-model="dimensionId" @change="changeClickHandler">
            <el-option v-for="dimension in dimensions" :key="dimension.ID" :label="dimension.name" :value="dimension.ID">
            </el-option>
          </el-select>
        </el-col>
      </div>
      <div class="layout-col-detail"></div>
    </div>
  <div class="layout-row-main catalog-settings-tree">
    <div class="layout-col-tree">
      <div class="layout-left-top left-menu-toolbar">
          <el-input v-model="search.key" placeholder="请输入关键字" size="medium" @keyup.enter.native="searchClickHandler">
            <el-select placeholder="内容类型" class="search-catalog" clearable slot="prepend" v-model="search.contentType" @change="searchClickHandler">
              <el-option v-for="item in contentTypes" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-input>
          <span class="search-icon"><i class="fa fa-search" @click="searchClickHandler" title="搜索"></i></span>
      </div>
      <affix-viewport height="calc(100vh - 240px)" style="background-color: #fff;" v-loading="dataLoading">
        <catalog-tree v-if='dimensionId!=-1' :title="site.siteName" :data="catalogTrees" ref="ctree" :props="defaultProps" :lazy="loadNode" @current-change="handleNodeClick">
          <template slot="rootOprate">
            <span class="tree-node-oprates">
              <el-button type="text" class="btn-oprate" @click.stop.prevent="previewSite()"><i class="fa fa-eye" title="预览站点"></i></el-button>
              <el-button type="text" class="btn-oprate" @click.stop.prevent="browseSite()"><i class="fa fa-bolt" title="浏览站点"></i></el-button>
            </span>
          </template>
          <template slot="nodeOprate" slot-scope="{node}">
            <div class="tree-node-oparate-custom">
              <el-button type="text" class="btn-oprate" @click.stop.prevent="previewCatalog(node)"><i class="fa fa-eye" title="预览"></i></el-button>
              <el-button type="text" class="btn-oprate" @click.stop.prevent="browseCatalog(node)"><i class="fa fa-bolt" title="浏览"></i></el-button>
            </div>
          </template>
        </catalog-tree>
        <time-tree v-else :data='timeTrees' ref="ttree" :props="timeTreeProps" :nodeActive="timestr" @current-change="handleNodeClick"></time-tree>
      </affix-viewport>
    </div>
    <div class="layout-col-detail" style="min-height: calc(100vh - 200px);margin-top: -50px;">
      <router-view :catalogID="catalogID" :dimensionID="dimensionId" :timestr="timestr"></router-view>
    </div>
  </div>
  </div>
</template>

<script>
import CatalogTree from '@src/components/catalogTree/CatalogTree.vue'
import AffixViewport from '@src/components/affix-viewport.vue'
import TimeTree from './components/TimeTree.vue'

export default {
  name: 'editorWorkspace',
  components: {
    'catalog-tree': CatalogTree,
    'affix-viewport': AffixViewport,
    'time-tree': TimeTree
  },
  data() {
    const that = this
    return {
      dataLoading: false,
      catalogTrees: [], // 内容类型树形数据
      catalogID: 0,
      dimensionId: 1,
      timestr: '',
      dimensions: [{ID: 1, code: 'default', name: '默认分类'}],
      site: {},
      defaultProps: {
        children: 'children',
        label: 'name',
        key: 'ID',
        traceback: 'innerCode' // 可用来回溯父节点的属性
      },
      search: { key: '', contentType: '' }, //  查询栏目类型和关键字
      timeTrees: [],
      timeTreeProps: {
        children: 'children',
        label: 'name',
        key: 'name'
      },
      contentTypes: [],
      loadNode: async function(parentNode) {
        let res = await axios.get(`/ui/dimensions/${that.dimensionId}/catalogstree`, {
          params: {
            contentType: that.search.contentType,
            searchKeyWord: encodeURI(that.search.key),
            parentID: parentNode.ID
          }
        })
        return res.data.data
      }
    }
  },

  async created() {
    this.$root.getCurrentSite().then(res => {
      this.site = res
    })
    await this.getContentTypes()
    try {
      await this.getDimensions()
      if (this.dimensionId === -1) {
        await this.getTimeTree()
      } else {
        await this.getCatalogTree()
      }
    } catch (e) {
      console.error(e)
    }

    //  this.handOldCatalog(''true)
  },
  methods: {
    async getContentTypes() {
      let res = await axios.get('/ui/contentcore/contenttypes')
      this.contentTypes = res.data.data
    },
    // set为true自动设置栏目id，false缓存上次栏目
    handOldCatalog(data, set) {
      if (set) {
        if (this.dimensionId === -1) {
          let timestr = localStorage[this.dimensionId + '_timestr']
          let checkData = {
            name: timestr
          }
          this.handleNodeClick(checkData)
          return
        }
        if (localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_cid']) {
          let ID = parseInt(localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_cid'], 10)
          let innerCode = localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_innerCode']
          let checkData = {
            ID,
            innerCode,
            treeLevel: localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_treeLevel'],
            contentType: localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_contentType'],
            type: localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_type']
          }
          this.handleNodeClick(checkData)
          this.$refs['ctree'].setCurrentNode(ID)
          // this.$refs['ctree'].setCurrentNode({innerCode: innerCode})
        } else {
          let checkData = {
            ID: 0,
            treeLevel: 0,
            contentType: 'Article',
            type: 'Default'
          }
          this.handleNodeClick(checkData)
        }
      } else {
        if (this.dimensionId === -1) {
          localStorage['user_' + localStorage.userName + '_' + this.dimensionId + '_timestr'] = data.name
          return
        }
        if (typeof data === 'object' && data !== null) {
          localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_cid'] = data.ID
          localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_innerCode'] = data.innerCode
          localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_treeLevel'] = data.treeLevel ? data.treeLevel : 10
          localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_contentType'] = data.contentType || 'Article'
          localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_type'] = data.type || 'Default'
        }
      }
    },
    async getDimensions() {
      let res = await axios.get('/ui/dimensions')
      this.dimensions = res.data.data
      this.dimensions.push({ID: -1, code: 'time', name: '时间'})
      this.dimensionId = localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_ewdid'] ? parseInt(localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_ewdid']) : this.dimensions[0].ID
    },
    handleNodeClick(data) {
      if (this.dimensionId === -1) {
        this.timestr = data.name
      } else {
        if (data !== null) {
          this.catalogID = data.ID
        } else {
          this.catalogID = 0
        }
      }
      this.handOldCatalog(data, false)
    },
    // 栏目查询
    searchClickHandler() {
      this.getCatalogTree()
    },
    async getCatalogTree() {
      this.dataLoading = true
      let opts = {
        contentType: this.search.contentType,
        searchKeyWord: encodeURI(this.search.key),
        loadRoot: 'Y'
      }
      let res = await axios.get(`/ui/dimensions/${this.dimensionId}/catalogs`, {params: opts})
      this.catalogTrees = res.data.data
      this.dataLoading = false
      if (this.catalogTrees.length === 0) {
        this.catalogID = 0
        return
      }
      if (localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_cid']) {
        this.handOldCatalog('', true)
      } else {
        this.catalogID = this.catalogTrees[0].ID
        this.handleNodeClick(this.catalogTrees[0])
        this.$refs['ctree'].setCurrentNode(this.catalogID)
      }
    },
    async getTimeTree() {
      this.dataLoading = true
      let res = await axios.get('/ui/contentcore/timedimension/trees')
      this.timeTrees = res.data.data
      this.dataLoading = false
      if (localStorage['user_' + localStorage.userName + '_' + this.dimensionId + '_timestr']) {
        this.handOldCatalog('', true)
      } else {
        this.timestr = this.timeTrees[0].name
        this.handleNodeClick(this.timeTrees[0])
        this.$refs['ttree'].setCurrentNode(this.timestr)
      }
    },
    changeClickHandler(value) {
      this.dimensionId = value
      if (this.dimensionId !== -1) {
        this.getCatalogTree()
      } else {
        this.getTimeTree()
      }
      localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_ewdid'] = value
    },
    previewSite() {
      window.open(`preview.html?id=${this.$root.siteID}&type=site`)
    },
    browseSite() {
      window.open(`${this.$root.siteURL}`)
    },
    previewCatalog(node) {
      window.open(`preview.html?id=${node.ID}&type=catalog`)
    },
    browseCatalog(node) {
      window.open(`${this.$root.siteURL + node.path}`)
    }
  }
}
</script>

<style scoped>
.left-menu-toolbar {
  position: relative;
}
.catalog-settings-tree .layout-left-top { padding: 5px 0 1px;}
.catalog-settings-tree {border-bottom: none;padding-bottom:10px;margin-top:0px}
.catalog-settings-tree .layout-left-top  .search-icon {top: 22px;right: 22px;}
.catalog-settings-tree .layout-left-top .el-input {padding:10px 10px;}
.search-catalog {
  width:90px!important;
}

.editor-workspace-el-row {
  height: 100%;
}
.fullQuickEditor{
  max-width: 1280px;
  margin: auto;
}
.catalog-tree >>> .tree-node-oprates {
    /* display:none; */
    position: absolute;
    right: 35px;
    top: 5px;
  }
</style>
