<script>
import _ from 'lodash'
export default {
  props: {
    selectedId: {
      type: [String, Number]
    },
    templateId: {
      type: [String, Number]
    }
  },
  data() {
    return {
      initLoading: true,
      sourceTemplateFlag: 'Y',
      templateDataLoading: false,
      filter: {
        subject: -1,
        style: -1,
        //  platform: -1
        searchWord: '',
        pageSize: 8,
        pageIndex: 1,
        orderBy: 'default'
      },
      previewTemplateIdx: null,
      totalCount: 0,
      matchedCount: 0,
      initDatas: [],
      templates: [],
      currentTemplateID: ''
    }
  },
  watch: {
    currentTemplateID(val, oldVal) {
      this.$emit('update:templateId', val)
    },
    sourceTemplateFlag(val, oldVal) {
      if (val === 'N') {
        this.currentTemplateID = ''
      }
      this.$emit('templateTypeChanged', val)
    }
  },
  created() {
    if (this.selectedId) {
      this.filter.searchWord = 'TEMPLATEID:' + this.selectedId
      this.currentTemplateID = this.selectedId
    }
    this.init()
  },
  computed: {
    templateIDs() {
      return this.templates.map(obj => obj.ID)
    },
    // 当前预览的模板ID
    previewTemplateID() {
      if (this.previewTemplateIdx === null) {
        return null
      }
      return this.templateIDs[this.previewTemplateIdx]
    },
    // 当前预览模板路径
    previewURL() {
      if (this.previewTemplateID === null) {
        return 'about:blank'
      } else {
        return `./ui/special/preview/${this.previewTemplateID}/content`
      }
    },
    subjects () {
      if (this.initDatas && this.initDatas.subjects && this.initDatas.subjects.length === 1 && this.initDatas.subjects[0].children) {
        return this.initDatas.subjects[0].children
      } else if (this.initDatas && this.initDatas.length > 1) {
        return this.initDatas.subjects
      } else {
        return []
      }
    }
  },
  methods: {
    async init() {
      this.initLoading = true
      let ajaxData = await axios.get('/ui/pageweaver/forminit')
      let res = ajaxData.data
      this.initDatas = res.data
      this.matchedCount = res.matchedCount
      this.initLoading = false
      this.queryTemplates()
    },
    doSearch() {
      this.filter.pageIndex = 1
      this.queryTemplates()
    },
    async queryTemplates() {
      const queryObj = {}
      for (let k in this.filter) {
        let val = this.filter[k]
        if (val !== null && val !== '' && val !== -1) {
          queryObj[k] = val
        }
      }
      if (queryObj.searchWord) {
        queryObj.searchWord = window.encodeURIComponent(queryObj.searchWord)
      }
      queryObj.pageIndex--
      this.templateDataLoading = true
      let ajaxData = await axios.get('/ui/pageweaver/template/sharedtemplates', {
        params: queryObj
      })
      let res = ajaxData.data.data
      this.templates = res.templates
      if (
        this.selectedId &&
        this.currentTemplateID === this.selectedId &&
        _.findIndex(this.templates, item => {
          return item.ID === this.selectedId
        }) !== -1
      ) {
        // this.filter.searchWord = ''
        this.currentTemplateID = this.selectedId
      } else {
        this.currentTemplateID = ''
      }
      this.totalCount = res.totalCount
      this.matchedCount = res.matchedCount
      this.templateDataLoading = false
    },
    sizeChange(val) {
      if (val) {
        this.filter.pageSize = val
      }
      this.queryTemplates()
    },
    // 当前页数设置
    currentChange(val) {
      if (val && this.filter.pageIndex !== val) {
        this.filter.pageIndex = val
        this.queryTemplates()
      }
    },
    changePreview(type) {
      if (type === 'prev') {
        this.previewTemplateIdx--
      } else {
        this.previewTemplateIdx++
      }
    },
    useIt() {
      this.currentTemplateID = this.previewTemplateID
      this.previewTemplateIdx = null
    },
    closePreview() {
      this.currentTemplateID = this.previewTemplateID
      this.previewTemplateIdx = null
      // this.currentTemplateID = ''
    }
  }
}
</script>
<template>
  <div class="template-selector" v-loading="initLoading">
    <el-row class="template-selector__title">
      <el-col :span="16" class="template-selector__radio">
        <el-radio v-model="sourceTemplateFlag" label="Y">模板筛选</el-radio>
        <el-radio style="margin-left:15px!important;" v-model="sourceTemplateFlag" label="N">空白模板</el-radio>
      </el-col>
      <el-col :span="8" v-show="sourceTemplateFlag === 'Y'">
        <el-input v-model="filter.searchWord" @keyup.enter.native="doSearch" placeholder="请输入关键字">
          <i slot="suffix" class="el-input__icon fa fa-search" @click="doSearch" title="搜索"></i>
        </el-input>
      </el-col>
    </el-row>
    <div class="template-selector__content" v-show="sourceTemplateFlag === 'Y'">
      <div class="filter-block">
        <el-row class="filter-item">
          <el-col :span="2" class="filter-item-label center" style="padding-top:2px;">分类：</el-col>
          <el-col :span="22">
            <el-radio-group v-model="filter.subject" @change="doSearch">
              <el-radio-button :label="-1">全部</el-radio-button>
              <el-radio-button v-for="subject in subjects" :key="subject.ID" :label="subject.topicID">{{subject.name}}</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>
        <el-row class="filter-item">
          <el-col :span="2" class="filter-item-label center">风格：</el-col>
          <el-col :span="22">
            <el-radio-group v-model="filter.style" @change="doSearch">
              <el-radio-button :label="-1">全部</el-radio-button>
              <el-radio-button v-for="style in initDatas.styles" :key="style.ID" :label="style.ID">{{style.name}}</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>
        <el-row class="filter-item">
          <el-col :span="2" class="filter-item-label center">排序：</el-col>
          <el-col :span="22">
            <el-radio-group v-model="filter.orderBy" @change="doSearch">
              <el-radio-button label="default">默认</el-radio-button>
              <el-radio-button label="time">最近更新</el-radio-button>
              <el-radio-button label="count">使用次数</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>
        <div class="filter-item">
          <div class="countInfo tar">当前模板库共有
            <i id="txt_totalCount">{{totalCount}}</i>个模板，当前条件匹配到
            <i id="txt_matchedCount">{{matchedCount}}</i>个模板</div>
        </div>

      </div>
      <div class="block-split"></div>
      <div class="templates-block" v-loading="templateDataLoading">
        <div v-show="templates.length === 0 && !templateDataLoading" class='templates-nodata'>当前没有匹配的模板</div>
        <el-row :gutter="0">
          <el-col :span="6" v-for="(item,index) in templates" :key="index">
            <div class="template-item" :class="{'selected': currentTemplateID === item.ID}" @click="currentTemplateID = item.ID">
              <div class="template-item__logo">
                <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\''" :alt="item.title">
              </div>
              <div class="template-item__title">
                <span v-text="item.title" :title="item.title + item.ID"></span>
              </div>
              <div class="template-item__attrs">
                <el-button size="small" type="text" @click.stop="previewTemplateIdx=index">
                    <i class="fa fa-eye"></i> 预览
                </el-button>
                <span class="use-count fr" v-text="item.useCount + '次'"></span>
              </div>
            </div>
          </el-col>
        </el-row>
        <div class="page" v-show="matchedCount!==0">
          <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page="filter.pageIndex" :page-sizes="[8, 16, 24, 36]"
            :page-size="filter.filter" layout="total, sizes, ->, prev, pager, next, jumper" :total="matchedCount">
          </el-pagination>
        </div>
      </div>
    </div>
    <div id="previewWrap" v-show="previewURL !== 'about:blank'">
      <div class="btns-preview">
        <el-button :disabled="previewTemplateIdx===0" @click="changePreview('prev')"><i class="fa fa-chevron-left" style="padding-right:0"></i></el-button>
        <el-button @click="useIt">使用该模板</el-button>
        <el-button @click="closePreview"><i class="fa fa-times" style="padding-right:0"></i></el-button>
        <el-button :disabled="previewTemplateIdx===templateIDs.length-1" @click="changePreview('next')"><i class="fa fa-chevron-right" style="padding-right:0"></i></el-button>
      </div>
      <iframe :src="previewURL" frameborder="0" id="iframePreview" ></iframe>
    </div>
  </div>
</template>

<style scoped>
#previewWrap {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background: rgba(255, 255, 255, 0.9);
  z-index: 999999;
}
.btns-preview{position: absolute;
  right: 20px;
  bottom: 20px;z-index: 9;}
#iframePreview {
  position: absolute;
  width: 100%;
  height: 100%;
}
.template-selector__content {
  padding-top: 10px;
  border-top: solid 1px #ddd;
}

.countInfo i {
  font-style: normal;
  color: #28b06e;
}

.filter-item {
  margin: 5px 0;
  line-height: 24px;
}

.block-split {
  height: 0px;
  border-bottom: solid 1px #e6ebed;
  background: none;
  margin: 10px 0;
}

.template-item {
  position: relative;
  border: 1px solid #fff;
  border-radius: 2px;
  padding: 10px;
  margin: 5px;
}
.template-item:hover {
  box-shadow: 0 0 5px rgba(0,0,0,.1);
}
.template-item.selected {
  border-color: #28B06E;
  box-shadow: 0px 1px 8px 0px rgba(92 , 153 , 122, 0.3);
}

.template-item.selected:before {
  position: absolute;
  right: -3px;
  top: -2px;
  color: #28b06e;
  font-size: 27px;
  line-height: 1;
  font-family: monospace;
  content: '\25E5';
  z-index: 1;
}

.template-item.selected:after {
  position: absolute;
  z-index: 1;
  font-size: 12px;
  font-weight: 600;
  right: 0px;
  top: 0px;
  color: #fff;
  content: '\221A';
  font-family: cursive;
  line-height: 1;
}

.template-item__logo {
  text-align: center;
  justify-content: center;
  align-items: center;
  /* background: #f8f8f8; */
  display: flex;
  height: 140px;
}

.template-item__logo img {
  max-width: 100%;
  max-height: 100%;
}

.template-item__title span {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.template-item__attrs a {
  color: inherit;
}

.use-count {
  color: #bbb;
  font-size: 12px;
  line-height: 29px;
}
.template-selector__radio{
  line-height: 40px;
    padding: 0 0 5px 20px;
}
.el-radio+.el-radio {
    margin-left: 20px;
}
</style>
<style>
.filter-block .el-radio-group label {
  padding: 0;
}
.filter-block .el-radio-button:first-child .el-radio-button__inner{
  border-left:none 0;
}
.filter-block .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  color: #67c23a;
  background: #f0f9eb;
  border-color: #c2e7b0;
  border: 1px solid #c2e7b0;
  border-radius: 4px;
  box-shadow: none;
}

.filter-block .el-radio-button__inner {
  border: none;
  padding: 5px 7px;
  margin: 0 5px;
  position: relative;
  outline: none;
}
</style>
