<template>
    <div class="layout-row-main catalog-settings-tree">
      <div :style="{overflow: affixWidth=='auto'?'auto':'visible',flexBasis: affixWidth=='auto'?'' : affixWidth}" class="layout-col-tree">
        <div class="layout-left-top left-menu-toolbar">
            <el-toolbar>
              <c-add-button @callback="loadCatalogTree" :dimension-id="dimensionId" :parent-catalog="currentCatalog"></c-add-button>
            </el-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 ref="affixTree" height="calc(100vh - 240px)" :width="affixWidth" style="background-color: #fff;box-shadow: 0 1px 1px rgba(99,99,99,.05);border-radius:4px;" v-loading="treeLoading">
          <catalog-tree :data="catalogTrees" :title="site.siteName" ref="ctree" :props="defaultProps" @current-change="handleNodeClick" :lazy="loadNode">
            <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>
        </affix-viewport>
      </div>
      <div class="layout-col-detail" style="min-height: calc(100vh - 200px);margin-top: -50px;">
          <catalog-info @callback="loadCatalogTree"  :dimension-id="dimensionId" :site-id="`${this.$root.siteID}`" :parent-id.sync="parentID" :catalog-id.sync="catalogID" :type.sync="type" :content-type.sync="contentType"></catalog-info>
      </div>
    </div>
</template>

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

export default {
  components: {
    'catalog-tree': CatalogTree,
    'affix-viewport': AffixViewport,
    'c-add-button': CatalogAddButton,
    'catalog-info': CatalogInfo
  },
  props: {
    dimensionId: {
      type: Number,
      default: 1
    }
  },
  data() {
    const that = this
    return {
      catalogTrees: [], // 内容类型树形数据
      catalogID: 0,
      parentID: 0,
      ID: 0,
      type: 'Default',
      treeLevel: 1,
      contentType: '',
      contentTypes: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        key: 'ID',
        traceback: 'innerCode'
      },
      site: {},
      currentCatalog: {},
      search: { key: '', contentType: '' }, //  查询栏目类型和关键字
      treeLoading: true,
      affixWidth: 'auto',
      loadNode: async function (parentNode) {
      // console.log(that);

        const res = await axios.get(`/ui/dimensions/${that.dimensionId}/catalogs`, {
          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()
    await this.getCatalogTree()
    //  this.handOldCatalog(''true)
  },
  watch: {
    dimensionId(val) {
      if (val) {
        this.currentCatalog = {}
        this.getCatalogTree()
        //  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 (localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_cid']) {
          const ID = parseInt(localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_cid'])
          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'] === 'null' ? '' : 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'],
            path: localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_path'],
            alias: localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_alias']
          }
          // if(this.checkOldCatalog()){
          this.handleNodeClick(checkData)
          // }
          this.$refs['ctree'] && this.$refs['ctree'].setCurrentNode(ID)
          // this.$refs['ctree'] && this.$refs['ctree'].setCurrentNode({innerCode: innerCode})÷
        } else {
          let checkData = {
            ID: 0,
            innerCode: '',
            treeLevel: 0,
            contentType: '',
            type: 'Default',
            path: '',
            alias: ''
          }
          this.handleNodeClick(checkData)
        }
      } else {
        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 + '_treeLevel'] = data.treeLevel ? data.treeLevel : 10
        localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_contentType'] = data.contentType
        localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_type'] = data.type || 'Default'
        localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_path'] = data.path
        localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_alias'] = data.alias
      }
    },
    handleNodeClick(data) {
      if (!data) {
        this.catalogID = 0
        this.currentCatalog = null
        return
      }
      this.currentCatalog = data
      this.catalogID = data.ID
      this.contentType = data.contentType
      this.parentID = data.parentID || 0
      this.type = data.type || 'Default'
      this.handOldCatalog(data, false)
    },
    // 加载栏目树
    async getCatalogTree() {
      this.treeLoading = true
      let opts = {
        contentType: this.search.contentType,
        searchKeyWord: encodeURI(this.search.key),
        isCatalogpri: 'Y',
        loadRoot: 'Y',
        isCatalogEdit: 'Y'
        // currentCatalogID: TODO 需要添加当前栏目ID，当个人偏好默认加载二级时，当前栏目为大于二级时加载不了数据
      }
      let res = await axios.get(`/ui/dimensions/${this.dimensionId}/catalogs`, { params: opts })
      this.treeLoading = false
      // 遍历所有数据，取标题的平均长度
      let count = 0
      let length = 0
      let level = -1
      const getCatalogNameLength = (array) => {
        level++
        array.forEach(i => {
          count++
          length += i.name.length * 12 + level * 22
          if (i.children && i.children.length){
            getCatalogNameLength(i.children)
          }
        })
      }
      getCatalogNameLength(res.data.data)
      let la = Math.floor(length / count) + 28
      la = Math.min(la, 400)
      // 如果标题比较长，把栏目树调宽一些
      if (la > 300){
        this.affixWidth = la + 'px'
      }
      this.catalogTrees = res.data.data
      if (localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_cid']) {
        this.handOldCatalog('', true)
      } else {
        this.catalogID = this.catalogTrees.length ? this.catalogTrees[0].ID : 0
        this.handleNodeClick(this.catalogTrees[0])
        this.$refs['ctree'] && this.$refs['ctree'].setCurrentNode(this.catalogID)
      }
    },
    // 栏目查询
    searchClickHandler() {
      this.loadCatalogTree()
    },
    async loadCatalogTree(val) {
      await this.getCatalogTree()
      await this.$nextTick()
      if (val === 'del' || val === 'move') {
        this.catalogID = 0
        this.contentType = ''
        this.parentID = 0
        this.type = 'Default'
        let data = {ID: this.catalogID, contentType: this.contentType, type: this.type, innerCode: ''}
        this.handOldCatalog(data, false)
      } else if (val) {
        this.catalogID = val.ID
        this.contentType = val.contentType
        this.parentID = val.parentID
        this.type = val.type
        this.handleNodeClick(val)
        this.$refs['ctree'] && this.$refs['ctree'].setCurrentNode({innerCode: val.innerCode})
      }
    },
    checkOldCatalog() {
      let oldCatalog = localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_did_' + this.dimensionId + '_cid']
      let isTrue = false
      if (!oldCatalog) {
        return isTrue
      }
      return this.catalogTrees.find(catalog => catalog.ID === oldCatalog)
    },
    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>
</style>
<style>
.view-tabs .el-tabs__header.is-top{
  padding-top: 0;
}
.el-tree el-tree--highlight-current {
  overflow: auto;
  height: 350px;
  background: gray
}
.search-bar {
    padding: 0 0 5px 0;
}
.toolbar {
  border-bottom: 1px solid #e8eaed;
}
.catalog-settings-tree {border-bottom: none;padding-bottom:10px;margin-top:0px}
.catalog-settings-tree .layout-left-top  .search-icon {top: 68px;right: 10px;}
.catalog-settings-tree .layout-left-top .el-input {padding:0 10px;}
.catalog-settings-tree .layout-left-top {padding:0 0 10px;}
.search-catalog {
  width:90px!important;
}

.search-catalog .el-input--suffix .el-input__inner {
  padding-right : 0;
  padding-left: 5px;
}
</style>
