<template>
  <div class="layout-no-cols right-list-toolbar">
    <div class="tool-box">
      <el-row style="width:100%">
        <el-col :span="10">
          <el-toolbar>
            <el-button @click="$router.push(`${$route.path}/new`)" priv="Pageweaver.TemplateMenu.Add">
              <i class="fa fa-plus"></i>新建
            </el-button>
            <el-button @click="importZip" priv="Pageweaver.TemplateMenu.Import">
              <i class="fa fa-upload"></i>导入
            </el-button>
          </el-toolbar>
        </el-col>
        <el-col :span="14" class="search-bar-algin-toolbar">
          <el-select class="layout-select" v-if="hasManageAllPriv" v-model="filter.siteID" style="width:145px" clearable placeholder="站点" @change="queryListData">
            <el-option v-for="site in sites" :key="site.ID" :label="site.name" :value="site.ID">
            </el-option>
          </el-select>
          <tree-select class="layout-select subject-selector" style="width:145px" :disableRoot="false" :clearable="false" top :value.sync="filter.subjectID" :items="subjects" :itemsOptions="subjectOptions" placeholder="主题分类" @click-change="queryListData"></tree-select>
          <el-input  name="keyword" style="width:auto" v-model="filter.keyword" placeholder="请输入关键字" @keyup.enter.native="queryListData" class="search-box-special-template">
            <i class="fa fa-search" slot="append" @click="queryListData" title="查询"></i>
          </el-input>
        </el-col>
      </el-row>
    </div>

    <div class="mini special-body">
      <waterfall-flow-list :data.sync="dataList" ref="templates" :data-read-url="getTemplateList" :page-size="10" :space-y="20"
        @selection-change="onSelectionChange">
        <template slot="list" slot-scope="{item}">
          <div class="panel-card table-group-item"  v-loading="deletingID.indexOf(','+item.ID+',') !== -1">
            <div class="table-card">
              <div class="logo-wrap">
                <img :src="item.listLogo ? item.listLogo + '' : 'assets/images/special/thumb'+(item.ID % 4)+'.png'" :onerror="'this.src = \'assets/images/special/thumb' +  (parseInt(item.ID.substr(item.ID.length - 3)) % 4) + '.png\''"
                  class="logo-img" />
              </div>
              <div class="title">{{item.title}}</div>
              <div class="attrs">
                <span class="time">新建时间：{{item.addTime | fixDateTime}}</span>
                <span class="fr use-count">{{item.useCount}}次</span>

              </div>
            </div>
            <div class="bottom-div">
              <el-tooltip content="单击切换共享状态" placement="top">
                <el-button @click.stop="toggleShareStatus(item)" class="btn-share-status" size="small" :type="item.shareFlag==='Y'?'success':'info'"
                  plain>{{item.shareFlag==='Y' ?'已共享':'未共享' }}</el-button>
              </el-tooltip>
              <div class="buttons">
                <a :href="`./ui/special/preview/${item.ID}/content`" target="_blank" style="color:unset !important;">
                  <el-button class="btn-item-txt-nopadding btn-item-txt-link" type="text" title="预览">
                    <i class="fa fa-search-plus"></i> 预览
                  </el-button>
                </a>
                <a :href="`specialDesigner.html?ID=${item.ID}`" target="_blank" style="color:unset !important;">
                  <el-button class="btn-item-txt-nopadding btn-item-txt-link" type="text" title="编辑" priv="Pageweaver.TemplateMenu.Edit">
                    <i class="fa fa-pencil" aria-hidden="true"></i>编辑
                  </el-button>
                </a>
                <el-button class="btn-item-txt-nopadding" @click="$router.push(`${$route.path}/${item.ID}`)" type="text" title="配置" priv="Pageweaver.TemplateMenu.Config">
                    <i class="fa fa-cog" aria-hidden="true"></i>配置
                </el-button>
                <el-dropdown placement="bottom-end">
                  <span>
                    <el-button size="small" class="btn-item-txt-nopadding" type="text" title="更多">
                      <i class="fa fa-ellipsis-h f16" style="padding-right:0;"></i>
                    </el-button>
                  </span>
                  <el-dropdown-menu slot="dropdown" class="button-dropdown">
                    <el-dropdown-item>
                      <el-button type="text" @click.native.stop="del(item.ID)" priv="Pageweaver.TemplateMenu.Delete" style="width:100%;"><i class="fa fa-minus"></i>删除</el-button></el-dropdown-item>
                    <el-dropdown-item>
                      <el-button type="text" @click.native.stop="exportTemplate(item.ID)" priv="Pageweaver.TemplateMenu.Export" style="width:100%;"><i class="fa fa-download"></i>导出</el-button></el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
          </div>
        </template>
      </waterfall-flow-list>
    </div>

    <el-dialog title="导入模板包" :visible.sync="uploadZip.showFlag" :append-to-body="true" class="import_dailog" @open="uploadDialogInit">
      <el-form label-position="right" label-width="120px">
        <el-form-item label="文件：">
          <el-upload ref="upload" :multiple="false" action="" :limit="1" :disabled="uploadZip.files.length>0" :auto-upload="false"
            class="upload-additional-dic" :http-request="uploadFile" :on-remove="removeFile" :on-change="selectFile" :accept="allowType"
            style="width:70%;">
            <el-row :gutter="3">
              <el-col :span="18">
                <el-input disabled v-model="allowType" size="small"></el-input>
              </el-col>
              <el-col :span="6">
                <el-button size="small" type="primary">选择文件</el-button>
              </el-col>
            </el-row>
            <div slot="tip" class="el-upload__tip">只能上传{{allowType}}文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="uploadZip.showFlag = false">取 消</el-button>
        <el-button type="primary" @click="confirm" :loading="templateUploading">{{templateUploading ? '上传中' : '确 定'}}</el-button>
      </div>
    </el-dialog>
  </div>
  <!-- </el-dialog> -->
</template>
<script>
import util from '@src/common/util.js'
import WaterfallFlowList from '@src/components/waterfallFlow/WaterfallFlowList.vue'
import TreeSelect from '@src/components/TreeSelect.vue'
import './special.css'
export default {
  components: {
    WaterfallFlowList,
    TreeSelect
  },
  filters: {
    fixDateTime: function(val) {
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      catalogID: 0,
      dataList: [],
      checkedItems: [],
      deletingID: '',
      templateUploading: false,
      allowType: '.zip',
      hasManageAllPriv: false,
      sites: [],
      subjects: [],
      subjectOptions: { key: 'topicID', label: 'name', children: 'children' },
      filter: {
        pageIndex: 1,
        pageSize: 15,
        siteID: '',
        keyword: '',
        orderType: 'Default',
        publishPlatform: '',
        subjectID: ''
      },
      uploadZip: {
        showFlag: false,
        files: []
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      let resp = await axios.get(`/ui/pageweaver/template/listinit`)
      if (resp.data.status === 1) {
        let ajaxData = resp.data.data
        this.hasManageAllPriv = ajaxData.hasManageAllPriv
        this.sites = ajaxData.sites
        this.subjects = ajaxData.subjects
      }
    },
    getTemplateList() {
      return [
        '/ui/pageweaver/template',
        {
          params: {
            pageIndex: this.filter.pageIndex - 1,
            pageSize: this.filter.pageSize,
            siteID: this.filter.siteID,
            keyword: encodeURIComponent(this.filter.keyword),
            orderType: this.filter.orderType,
            publishPlatform: this.filter.publishPlatform,
            subjectID: this.filter.subjectID
          }
        }
      ]
    },
    // 切换单个模板共享状态
    async toggleShareStatus(template) {
      var type = template.shareFlag === 'Y' ? 'N' : 'Y'
      let resp = await axios.put(`/ui/pageweaver/template/${template.ID}/share/${type}`)
      if (resp.data.status === 1) {
        template.shareFlag = type
      } else {
        util.showResponseMessage(resp.data)
      }
    },
    onSelectionChange(selection) {
      this.checkedItems = []
      selection.forEach(row => {
        this.checkedItems.push(row.ID)
      })
    },

    // 删除模板
    async del(id) {
      try {
        const delIDs = typeof id === 'string' ? id : this.checkedTemplates.join(',')
        await this.$confirm('确定要删除模板吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.deletingID = `,${delIDs},`
        let resp = await axios.delete(`/ui/pageweaver/template/${delIDs}`)
        util.showResponseMessage(resp.data)
        if (resp.data.status === 1) {
          this.queryListData()
          this.checkedTemplates = []
        }
      } catch (e) {
        return
      } finally {
        this.deletingID = ''
      }
    },
    // 批量切换模板状态
    async share(type) {
      if (!this.checkedTemplates || this.checkedTemplates.length === 0) {
        this.$alert('请先选择记录')
        return
      }
      let resp = await axios.put(`/ui/pageweaver/template/${this.checkedTemplates.join(',')}/share/${type}`)
      util.showResponseMessage(resp.data)
      if (resp.data.status === 1) {
        this.queryListData()
      }
    },
    // 导入模板
    importZip() {
      this.uploadZip.files = []
      this.uploadZip.showFlag = true
    },
    // 导出模板
    async exportTemplate(ID) {
      // TODO:模板数据导出中
      let resp = await axios.get(`/ui/pageweaver/template/${ID}/export`)
      if (resp.data.data) {
        window.location.href = `ui/pageweaver/template/${ID}/download?fileName=${resp.data.data}`
      } else {
        util.showResponseMessage(resp.data)
      }
    },
    // 根据条件检索专题模板数据
    async queryListData() {
      if (this.filter.subjectID === 0) {
        this.filter.subjectID = ''
      }
      this.$refs.templates.getData()
    },

    uploadDialogInit() {
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
    },
    async uploadFile(event) {
      const { file } = event

      const formData = new FormData()
      formData.append('file', file)
      let res = await axios.post('/ui/pageweaver/template/import', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      if (res.data.status === 1) {
        if (res.data.taskID) {
          await util.showProgress(res.data.taskID, '模板导入中...')
        }
        this.queryListData()
        this.uploadZip.showFlag = false
      } else {
        util.showErrorMessageBox(res.data.message)
      }
      this.templateUploading = false
    },
    removeFile(files) {
      this.uploadZip.files = []
    },
    selectFile(files) {
      if (files.length > 1) {
        this.$message.info('文件总数量限制为1')
        return
      }
      this.uploadZip.files = JSON.parse(JSON.stringify(files))
    },
    confirm() {
      if (this.uploadZip.files.length === 0) {
        this.$alert('请选择要上传的文件', '提示', {
          type: 'info',
          confirmButtonText: '确定'
        })
        return
      }
      this.templateUploading = true
      this.$refs.upload.submit()
    }
  }
}
</script>
<style>
.import_dailog .el-dialog {
  width: 500px;
}

@media (max-width: 480px) {
  .import_dailog .el-dialog {
    width: 96%;
  }
}
</style>
<style scoped>
.filter-item label {
  padding-left: 7px;
}
.table-group-item {
  margin: 0;
  width: 330px;
  display: inline-block;
  position: relative;
}

.logo-wrap {
  padding-bottom: 15px;
  font-size: 16px;
  line-height: 24px;
  font-weight: bold;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
.logo-wrap img{
  max-width: 100%;
  max-height: 100%;
}
.table-card .title {
  padding-bottom: 10px;
  font-weight: bold;
  color: #333;
}

.table-card .time {
  color: #a2a2a2;
}

.table-card .status {
  color: #666;
}

.logo-wrap .logo-img {
  width: 100%;
  border-radius: 3px;
}

.bottom-div {
  position: relative;
  margin-top: 5px;
  font-size: 12px;
  padding: 5px 0;
}

.bottom-div .buttons {
  float: right;
  text-align: right;
  height: 27px;
  line-height: 27px;
}

.btn-share-status {
  background: #e3f7ee;
  color: #31b070;
  border: none;
}

</style>
