<template>
 <div>
  <el-button :disabled="!contentIds" @click="handleClick" :type="buttonType" :priv="'com.zving.cms.Catalog.Content.Copy.'+ catalogIds">
    <i class="fa fa-window-restore"></i>复制
    <el-dialog title="选择栏目" :visible.sync="show" :append-to-body="true" class="copy-catalog-dialog">
      <span style="color:red" v-if="contentType.split(',').length>1">请注意!选择了多篇不同类型的内容,只能复制到混合栏目</span>
      <div class="dialog-body" v-loading="loading">
        <el-toolbar>
          <el-radio-group v-model="copyParams.copyType" class="toobar-style">
            <el-radio v-for="item in copyTypes" :label="item.label" :key="item.label">{{item.name}}</el-radio>
          </el-radio-group>
        </el-toolbar>
        站点选择：<tree-select :value.sync="currentSiteID" :items="sites" width="50%" @click-change="changeSite"></tree-select>
        <el-checkbox-group v-model="targetCatalogIds"  class="catalog-tree">
          <el-tree
            :render-content="renderContent"
            :show-checkbox="false"
            :data="catalogTrees"
            :props="catalogProps"
            node-key="ID"
            highlight-current
            :load="loadNode1"
            lazy
            :expand-on-click-node="false"
            @node-click="clickCatalog"
            :default-expanded-keys="defaultKeys"
            ref="moveCatalogTrees">
          </el-tree>
        </el-checkbox-group>
      </div>
      <div slot="footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="confirm" :loading="confirmLoading">确 定</el-button>
      </div>
    </el-dialog>
  </el-button>
 </div>
</template>

<script>
import util from '@src/common/util.js'
import TreeSelect from '@src/components/TreeSelect.vue'
export default {
  components: {
    'tree-select': TreeSelect
  },
  props: {
    contentIds: {
      type: [String, Number]
    },
    catalogIds: {
      type: [String, Number]
    },
    buttonType: {
      type: String,
      default: 'info'
    },
    contentType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      catalogTreeLevel: 1,
      catalogTrees: [],
      targetCatalogIds: [],
      copyParams: {
        ID: this.contentIds,
        catalogIds: '',
        copyType: ''
      },
      /* 复制类型 */
      copyTypes: [
        {label: '2', name: '映射'},
        {label: '1', name: '独立复制'},
        {label: '3', name: '内部链接'},
        {label: '4', name: '标题新闻'}
      ],
      catalogProps: { children: 'children', label: 'name', isLeaf: function(data, node) { return !!data.isLeaf } },
      loading: false,
      show: false,
      confirmLoading: false,
      defaultKeys: [],
      currentSiteID: 0,
      sites: []
    }
  },
  created() {
    let userPreferences = JSON.parse(localStorage.getItem('userPreferences'))
    this.copyParams.copyType = userPreferences.copyDefaultMapping === 'Y' ? '2' : ''
    this.catalogTreeLevel = userPreferences.catalogTreeLevel
    this.currentSiteID = this.$root.siteID
  },
  methods: {
    async loadNode1(node, resolve) {
      if (node.data.children && node.data.children.length > 0) {
        // tree懒加载时返回的数据要是没有被vue监听的纯数据
        resolve(JSON.parse(JSON.stringify(node.data.children)))
      } else {
        if (node.data.isLeaf !== undefined && !node.data.isLeaf && node.data.treeLevel !== 0) {
          let resp = await axios.get(`/ui/dimensions/groupedcatalogs/${this.currentSiteID}?type=Default,Link&parent=${node.data.ID}&contentType=${this.contentType}`)
          if (resp.data.status === 1) {
            resolve(resp.data.data)
          }
        } else {
          resolve([])
        }
      }
    },
    expandNode(datas, level) {
      if (level > 0) {
        let nodes = []
        let keys = []
        datas.filter(node => nodes.push(node))
        while (nodes.length > 0) {
          let node = nodes.shift()
          if (node.treeLevel < level && !node.isLeaf) {
            keys.push(node.ID)
            if (node.children){
              node.children.filter(n => nodes.push(n))
            }
          }
        }
        keys.sort()
        if (this.defaultKeys.join() !== keys.join()){
          this.defaultKeys = keys
        }
      }
    },
    changeSite() {
      this.getCatalogs()
    },
    async handleClick () {
      let res = await axios.get('/ui/sites')
      if (res.data.status === 1) {
        this.sites = res.data.data
      }
      this.show = true
      this.confirmLoading = false
      this.getCatalogs()
    },
    async getCatalogs() {
      this.loading = true
      let resp = await axios.get(`/ui/dimensions/groupedcatalogs/${this.currentSiteID}?type=Default,Link&contentType=${this.contentType}`)
      if (resp.data.status === 1) {
        this.expandNode(resp.data.data, this.catalogTreeLevel)
        this.catalogTrees = resp.data.data
        this.loading = false
      }
    },
    changeCatalog(e, val) {
      for (let i = 0; i < val.length; i++) {
        this.catalogIds !== e.ID && this.targetCatalogIds.push(val[i])
      }
    },
    clickCatalog(e) {
      if ((this.contentType.split(',').length > 1) || (e.contentType && this.contentType !== e.contentType)) {
        return
      }
      !this.targetCatalogIds.includes(e.ID) && this.catalogIds !== e.ID && this.targetCatalogIds.push(e.ID)
    },
    async confirm() {
      if (!this.copyParams.copyType) {
        this.$alert('请选择复制类型!')
        return
      }
      if (!this.targetCatalogIds.length) {
        this.$alert('请先选择栏目！')
        return
      }
      this.confirmLoading = true
      this.copyParams.catalogIds = this.targetCatalogIds.join(',')
      this.copyParams.catalogId = this.catalogIds
      this.copyParams.ID = this.contentIds
      let resp = await axios.put(`/ui/contentcore/contents/${this.contentIds}/copy`, this.copyParams)
      this.confirmLoading = false
      util.showResponseMessage(resp.data)
      if (resp.data.status === 1) {
        this.show = false
        this.targetCatalogIds = []
        this.refreshContent()
      }
    },
    renderContent: function (createElement, { node, data }) {
      if (parseInt(data.ID) === 0 || parseInt(data.branchInnerCode) === 0 || data.ID === 'site') {
        return createElement('span', [
          createElement('i', { attrs: { class: 'fa fa-sitemap' } }),
          createElement('span', node.label)
        ])
      } else {
        return createElement('span', [
          this.allowSelected(data) && createElement('el-checkbox', {props: { label: data.ID }}, ''),
          createElement('i', { attrs: { class: 'fa fa-folder' } }),
          this.catalogIds !== data.ID ? createElement('span', node.label) : createElement('span', {attrs: {style: 'color:#b9b9ce'}}, node.label)
        ])
      }
    },
    allowSelected(data) {
      return this.catalogIds !== data.ID && (this.contentType.split(',').length > 1 ? (data.contentType === '') : (data.contentType === '' || this.contentType === data.contentType))
    },
    refreshContent() {
      this.$emit('refresh-content')
    }
  }
}
</script>
<style>
.copy-catalog-dialog .el-dialog {
  width: 420px;
}
@media (max-width: 480px) {
  .copy-catalog-dialog .el-dialog {
    width: 96%;
  }
}

</style>
<style scoped>
.toobar-style {
  margin-left: 16px;
}
.catalog-tree {
  height: 72%;
  width: 100%;
  overflow: auto;
}

.dialog-body {
  height: 400px;
  width: 100%;
  border: 1px solid #eee;
}
.el-checkbox-group{
  font-size:12px;
}
</style>
