<template>
  <div class="layout-no-cols right-list-toolbar">
    <div class="tool-box">
      <el-row>
        <el-col :span="14">
          <el-toolbar>
            <el-button @click="addTemplate" priv="ContentCore.TemplateMenu.Edit">
              <i class="fa fa-plus" aria-hidden="true"></i>新建
            </el-button>
            <el-button @click="importSiteTemplate" priv="ContentCore.TemplateMenu.Edit">
              <i class="fa fa-arrow-up" aria-hidden="true"></i>导入模板包
            </el-button>
            <el-button @click="exportSiteTemplate" priv="ContentCore.TemplateMenu.Export">
              <i class="fa fa-arrow-down" aria-hidden="true"></i>导出模板包
            </el-button>
            <el-button @click="toTemplateVersionPage">
              <i class="fa fa-files-o" aria-hidden="true"></i>模板包版本
            </el-button>
          </el-toolbar>
        </el-col>
        <el-col :span="10" class="tool-search-square-box-r">
          <el-input v-model="searchTemplateName" @keyup.enter.native="loadTemplateTreeData" placeholder="模板名称" class="search-bar-algin-toolbar">
            <el-select slot="prepend" placeholder="" v-model="searchPublishPlatform" @change="loadTemplateTreeData">
              <el-option v-for="item in publishPlatformsData" :key="item.ID" :label="item.name" :value="item.ID"></el-option>
            </el-select>
          </el-input>
          <span class="search-icon"><i class="fa fa-search" slot="append" @click="loadTemplateTreeData" title="查询"></i></span>
        </el-col>
      </el-row>
    </div>
    <div class="scroll margin-top-8" v-loading="templateLoading">
      <tree-table :data="templateTreeData" :expanded-level="1" row-key="ID" class="catalog-tree-table">
        <tree-table-column label="名称">
          <template slot-scope="scope">
            <a class="list-card-title" href="javascript:void(0)" @click.stop="onCellClick(scope.row)">
              <i v-if="scope.row.fileFlag=='N'" class="fa fa-folder"></i>
              <i v-if="scope.row.fileFlag=='Y'" class="fa fa-file-text"></i>
              {{scope.row.name}}
            </a>
          </template>
        </tree-table-column>
        <el-table-column prop="ID" label="模板文件" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="100" align="right">
          <template slot-scope="scope">
            <el-button v-if="scope.row.fileFlag=='N'" @click.stop="addTemplate(scope.row)" priv="ContentCore.TemplateMenu.Edit" type="text" title="新建" class="table-operate-icon">
              <i class="fa fa-plus f16"></i>
            </el-button>
            <el-button v-if="scope.row.fileFlag=='Y'" @click.stop="editTemplate(scope.row)" priv="ContentCore.TemplateMenu.Edit" type="text" title="编辑" class="table-operate-icon">
              <i class="fa fa-edit f16"></i>
            </el-button>
            <el-button v-if="scope.row.fileFlag=='Y'" @click.stop="exportFile(scope.row)" priv="ContentCore.TemplateMenu.Export" type="text" title="打包导出相关文件" class="table-operate-icon">
              <i class="fa fa-arrow-down f16"></i>
            </el-button>
          </template>
        </el-table-column>
      </tree-table>
    </div>
  </div>

</template>

<script>
import util from '@src/common/util.js'
import TreeTable from '@src/components/treeTable/TreeTable.vue'
import TreeTableColumn from '@src/components/treeTable/TreeTableColumn.vue'

export default {
  data() {
    return {
      selectedRow: [],
      templateLoading: false,
      publishPlatformsData: [], // 发布平台数据
      searchPublishPlatform: 'pc', // 工具栏发布平台搜索值
      searchTemplateName: '', // 工具栏模板名称搜索值
      templateTreeData: [], // 模板列表树数据
      currentTemplateParam: {
        fileName: '',
        platformID: null,
        siteID: null,
        name: ''
      } // 参数
    }
  },
  methods: {
    // 编辑模板
    editTemplate(row) {
      if (!row || row.fileFlag === 'N') {
        this.$alert('参数错误!', '系统提示')
        return
      }
      if (String(row.visualTemplatePageID) !== '0') {
        window.open(`specialDesigner.html?ID=${row.visualTemplatePageID}`)
      } else {
        window.open(`templateEditor.html?ID=&fileName=${row.ID}&platformID=${row.platformID}&siteID=${row.siteID}`)
      }
    },
    // 打包导出相关文件
    exportFile(row) {
      if (!row || !row.ID) {
        this.$alert('参数错误 !', '系统提示')
        return
      }

      this.$message(' 正在导出，请等待 . . .')
      window.location.href = `./ui/template/export?fileName=${row.ID}&platformID=${row.platformID}&siteID=${
        row.siteID
      }`
    },

    toTemplateVersionPage() {
      let query = {
        platformID: this.currentTemplateParam.platformID,
        siteID: this.currentTemplateParam.siteID
      }
      let path = `${this.$route.path}/version`.replace(/\/\//g, '/')
      this.$router.push({path: path, query: query})
    },

    importSiteTemplate() {
      let query = {
        platformID: this.currentTemplateParam.platformID,
        siteID: this.currentTemplateParam.siteID
      }
      let path = `${this.$route.path}/import`.replace(/\/\//g, '/')
      this.$router.push({path: path, query: query})
    },

    selectionChange(row) {
      this.selectedRow = row
      if (!row.length) {
        this.currentTemplateParam = {}
        return
      }
      let nodeData = row[row.length - 1]
      let id = nodeData.ID
      let fileFlag = nodeData.fileFlag
      let platFormID = nodeData.platformID
      let siteID = nodeData.siteID
      id = fileFlag === 'N' ? '' : id

      this.currentTemplateParam.fileName = id
      this.currentTemplateParam.platformID = platFormID
      this.currentTemplateParam.siteID = siteID
    },
    // 添加模板
    addTemplate(row) {
      let parentPath = ''
      if (row && row.ID && row.ID !== 'template') {
        parentPath = row.ID.startsWith('template/') ? row.ID.replace(/template\//g, '') : row.ID
      }
      let params = {
        siteID: this.currentTemplateParam.siteID,
        platformID: this.currentTemplateParam.platformID,
        parentPath: parentPath
      }

      this.$router.push({path: `${this.$route.path}/new`.replace(/\/\//g, '/'), query: params})
    },
    // 导出模板包
    async exportSiteTemplate() {
      let params = {
        siteID: this.currentTemplateParam.siteID,
        platformID: this.currentTemplateParam.platformID
      }
      try {
        let res = await axios.get('/ui/publishplatform/templatezip', { params })
        if (res.data.status === 1) {
          await util.showProgress(res.data.data.taskID, `导出模板包`)
          window.location.href = `./ui/site/export?path=${res.data.data.path}&siteID=${params.siteID}&platformID=${params.platformID}`
        } else {
          util.showMessage(res)
        }
      } catch (e) {
        util.showErrorNotification(e)
      }
    },

    onCellClick(row) {
      let nodeData = row
      let id = nodeData.ID
      let fileFlag = nodeData.fileFlag
      let platFormID = nodeData.platformID
      let siteID = nodeData.siteID
      id = fileFlag === 'N' ? '' : id
      this.currentTemplateParam.fileName = id
      this.currentTemplateParam.platformID = platFormID
      this.currentTemplateParam.siteID = siteID

      if (fileFlag === 'N') {
        row._expanded = !row._expanded
        return
      }

      let path = `${this.$route.path}/tabs`.replace(/\/\//g, '/')
      this.$router.push({path: path, query: this.currentTemplateParam})
    },

    async initData() {
      let params = {
        platformID: this.searchPublishPlatform,
        name: this.searchTemplateName
      }

      this.templateLoading = true
      try {
        let res = await axios.get('/ui/template/tree', { params: params })
        if (res.data.status === 1) {
          this.templateTreeData = res.data.data
          this.setDefultParams()
          //  res.data.rootText && this.templateTreeData.unshift({ ID: 'root' name: res.data.rootText })
        }
        let resp = await axios.get('/ui/publishplatform/usedpublishplatforms')
        this.publishPlatformsData = resp.data.status === 1 ? resp.data.data : this.publishPlatformsData
        this.loadTemplateTypes()
      } catch (e) {}
      this.templateLoading = false
    },

    setDefultParams() {
      if (!this.templateTreeData.length) {
        this.currentTemplateParam.fileName = ''
        this.currentTemplateParam.platformID = ''
        this.currentTemplateParam.siteID = ''
        return
      }

      let nodeData = this.templateTreeData[0]
      let id = nodeData.ID
      let fileFlag = nodeData.fileFlag
      let platFormID = nodeData.platformID
      let siteID = nodeData.siteID
      id = fileFlag === 'N' ? '' : id

      this.currentTemplateParam.fileName = id
      this.currentTemplateParam.platformID = platFormID
      this.currentTemplateParam.siteID = siteID
    },

    // 加载左侧模板列表树数据
    async loadTemplateTreeData() {
      this.templateLoading = true
      try {
        this.currentTemplateParam.platformID = this.searchPublishPlatform
        let params = {
          platformID: this.searchPublishPlatform,
          name: this.searchTemplateName.trim()
        }
        let res = await axios.get('/ui/template/tree', { params: params })
        let data = res.data
        if (data.status === 1) {
          this.templateTreeData = data.data
          this.setDefultParams()
        }
      } catch (e) {}
      this.templateLoading = false
    },

    // 加载搜索栏下拉框数据(发布平台)
    async loadUsedPublishPlatforms() {
      let res = await axios.get('/ui/publishplatform/usedpublishplatforms')
      let data = res.data
      this.publishPlatformsData = data.data
    },

    // 加载模板类型下拉框数据
    async loadTemplateTypes() {
      this.dialogDataLoading = true
      try {
        let res = await axios.get('/ui/contentcore/templateeditor/templatetypes')
        this.templateTypes = res.data.status === 1 ? res.data.data : []
      } catch (e) {}
      this.dialogDataLoading = false
    }
  },
  components: {
    'tree-table': TreeTable,
    'tree-table-column': TreeTableColumn
  },
  created() {
    this.initData()
  }
}
</script>

<style scoped>
.pointer {
  cursor: pointer;
}
.catalog-tree-table .list-card-title {
  font-size: 14px;
}
.form-panel .is-required {
  display: block;
}
.title-column__content {
  cursor: pointer;
}
.padding-top-bottom .search-bar {
  padding-bottom: 5px;
}
.tabs-wrap {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
}
.info-form-wrap {
  margin-top: 10px;
  padding: 10px 0;
  width: 560px;
}
.pane-wrap {
  padding: 0 15px 15px;
}
.tag-item,
.title {
  line-height: 1.5;
  margin: 0.2em 0 0.3em 0;
}
.tag-item .tag-label {
  display: inline-block;
  text-align: right;
  width: 100px;
}
.title {
  margin-top: 1em;
  font-size: 20px;
}
.right-list-toolbar .tool-search-square-box-r .search-icon {
  line-height: 13px;
}
</style>
