<template>
  <div v-loading="dataLoading" class="layout-no-flex">
    <el-toolbar>
      <el-button @click="goBack" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" @click="save" v-loading="saveLoading"><span><i class="fa fa-save"></i>保存</span></el-button>
      <el-button v-if="this.ID !== 'new'" type="button" class="el-button el-button--default" @click="togglePreview"><span><i class="fa fa-eye"></i> 预览</span></el-button>
    </el-toolbar>
    <el-row>
      <el-col :span="tmpMedia.articles && tmpMedia.articles.length ? 10 : 24" class="left">
        <div class="panel-card table-card">
          <div v-for="val in tmpMedia.articles" :key="val.ID">
            <div v-if="val.index === 0" :class="'appmsg-title '+selectArticles[0].value" @click.stop="selectHandler(val)">
              <a href="javascript:void(0);" onclick="return false;" target="_blank">
                <h4 class="appmsg_title">{{val.title}}</h4>
              </a>
              <img :src="tmpMedia.prefix + val.logoFile" onerror="this.src='@static/assets/images/picture.png'" width="100%" />
              <div class="button-div">
                <div style="position:absolute;top:45%;left:32%;">
                  <el-button type="text" @click.stop="editArticle(val)">编辑</el-button>
                  <el-button type="text" @click.stop="delArticle(val.index)">删除</el-button>
                </div>
              </div>
            </div>
            <div v-else :class="'appmsg-div '+(selectArticles[val.index].value)" @click.stop="selectHandler(val)">
              <el-row>
                <el-col :span="17">
                  <a onclick="return false;" href="javascript:void(0);" target="_blank">{{val.title}}</a>
                </el-col>
                <el-col :span="7">
                  <img :src="tmpMedia.prefix + val.logoFile" onerror="this.src='assets/images/picture404-'+((row.ID||row.$index) % 4)+'.png';" width="100%" />
                </el-col>
              </el-row>
              <div class="button-div">
                <div style="position:absolute;top:35%;left:33%;">
                  <el-button type="text" @click.stop="editArticle(val)">编辑</el-button>
                  <el-button type="text" @click.stop="delArticle(val.index)">删除</el-button>
                </div>
              </div>
            </div>
          </div>
          <!-- 添加素材图标 -->
          <div class="add-div">
            <a @click.stop="addArticle" class="add-body">
              <i class="fa fa-plus" aria-hidden="true"></i>
            </a>
          </div>
        </div>
      </el-col>
      <el-col :span="14" v-if="tmpMedia.articles && tmpMedia.articles.length">
        <div class="detail-panel">
          <div class="panel-header">
            <div class="title">关联内容基本信息</div>
          </div>
          <el-form :model="article" label-suffix="：" label-width="120px" disabled>
            <el-form-item prop="title" label="标题">
              {{article.title}}
            </el-form-item>
            <el-form-item prop="author" label="作者">
              {{article.author}}
            </el-form-item>
            <el-form-item prop="contentTypeName" label="内容类型">
              {{article.contentTypeName}}
            </el-form-item>
            <el-form-item prop="catalogName" label="所属栏目">
              {{article.catalogName}}
            </el-form-item>
            <el-form-item prop="summary" label="摘要">
              {{article.summary}}
            </el-form-item>
          </el-form>
          <div class="center" style="margin-top:20px;">
            <el-button type="primary" v-if="article && article.ID" size="medium" round class="shadow-primary" @click="editContent">
              <i class="fa fa-floppy-o"></i>编辑内容
            </el-button>
          </div>
        </div>
      </el-col>
    </el-row>
    <block-item-dialog :show.sync="createArticleModal" :item="tmpArticle" :account-id="weiXinID" @callback="blockItemDialogCallback"></block-item-dialog>
    <preview-popover v-if="previewState" :mediaid="ID" :weixinid="weiXinID" :weixinname="accountData.MName" :articles="tmpMedia.articles" @hide="togglePreview" :prefix="tmpMedia.prefix"></preview-popover>
  </div>
</template>
<script>
import util from '@src/common/util.js'
import blockItemDialog from '../block/blockItemDialog.vue'
import previewPopover from './components/previewPopover.vue'
export default {
  components: {
    'preview-popover': previewPopover,
    'block-item-dialog': blockItemDialog
  },
  props: {
    ID: {
      default: 0
    },
    weiXinID: {
      default: 0
    }
  },
  data() {
    return {
      selectArticles: [],
      isEdit: false,
      dataLoading: false,
      saveLoading: false,
      editMode: 0,
      contentSelectDialogModal: false,
      resourceDialogProps: {
        dataType: 'block',
        resourceType: 'image',
        imageType: 'logo',
        imageHeight: 120,
        imageWidth: 120,
        inputType: 'radio'
      },
      tmpMedia: {},
      createArticleModal: false,
      tmpArticle: {},
      titleColor: '',
      previewPath: '',
      article: {},
      previewState: false,
      accountData: {}
    }
  },
  mounted() {
  // console.log(this.ID)
    this.isEdit = this.ID !== 'new'
    this.loadData()
  },
  methods: {
    editContent() {
      let path
      if (this.article.contentTypeID === 'Special') {
        path = `/special/${this.article.catalogID}/${this.article.ID}`
        this.$router.push(path)
      } else {
        path = `/contentEditor/${this.article.ID}?type=${this.article.contentTypeID}&cid=${this.article.catalogID}`
        window.open('contentEditor.html#' + path)
      }
    },
    selectHandler(val) {
      if (val.ID === this.article.ID) {
        return
      }
      this.selectArticles.forEach(select => {
        if (val.ID === select.ID) {
          select.value = 'selected'
        } else {
          select.value = ''
        }
      })
      this.initArticleContent(val.ID)
    },
    async initArticleContent(contentID) {
      let res = await axios.get(`/ui/contentcore/contents/${contentID}`)
      this.article = res.data.data
    },
    goBack() {
      this.$router.back()
    },
    contentSelectCallback(data) {
      this.tmpArticle = {
        ID: data.ID,
        publishDate: data.publishDate,
        title: data.title,
        logoFile: data.logoFile,
        URL: data.link,
        index: this.tmpArticle.index,
        summary: ''
      }
      this.previewPath = this.tmpMedia.prefix + data.logoFile
    },
    editArticle(data) {
      this.editMode = 1
      this.tmpArticle = Object.assign({}, data)
      this.previewPath = this.tmpMedia.prefix + data.logoFile
      this.titleColor = ''
      this.createArticleModal = true
    },
    delArticle(index) {
      this.tmpMedia.articles.splice(index, 1)
      this.tmpMedia.articles.forEach(o => {
        o.index = this.tmpMedia.articles.findIndex(val => val === o)
      })
    },
    async loadData() {
      this.saveLoading = false
      this.dataLoading = true
      let res = ''
      try {
        res = await axios.get('/ui/wechat/medias/init', {
          params: {
            ID: this.isEdit ? this.ID : null
          }
        })
        let accountData = await axios.get(`/ui/mediaaccounts/${this.weiXinID}`)
        this.accountData = accountData.data.data
      } catch (e) {
        util.showErrorMessageBox(e)
        this.dataLoading = false
        return
      }
      this.tmpMedia = res.data.data
      this.dataLoading = false
      if (!this.isEdit) {
        Vue.set(this.tmpMedia, 'articles', [])
      } else {
        this.tmpMedia.articles.forEach(val => {
          this.selectArticles.push({
            ID: val.ID,
            value: val.index === 0 ? 'selected' : ''
          })
        })
        this.initArticleContent(this.tmpMedia.articles[0].ID)
      }
    },
    async save() {
      this.saveLoading = true
      let res
      this.tmpMedia.weiXinID = this.$route.params.weiXinID
      try {
        if (this.isEdit) {
          res = await axios.put(`/ui/wechat/medias/${this.ID}`, this.tmpMedia)
        } else {
          res = await axios.post('/ui/wechat/medias', this.tmpMedia)
        }
      } catch (e) {
        util.showErrorMessageBox(e)
        this.saveLoading = false
        return
      }
      util.showResponseMessage(res.data)
      this.saveLoading = false
      if (res.data.status === 1) {
        this.$emit('callback')
        this.goBack()
      }
    },
    addArticle() {
      this.editMode = 0
      this.titleColor = ''
      this.previewPath = ''
      this.tmpArticle = {
        ID: 0,
        publishDate: '',
        title: '',
        logoFile: '',
        URL: '',
        index: this.tmpMedia.articles.length,
        summary: ''
      }
      this.createArticleModal = true
    },
    blockItemDialogCallback(article) {
      article.publishDate = article.date
      if (this.editMode) {
        this.tmpMedia.articles.splice(article.index, 1, article)
      } else {
        this.tmpMedia.articles.splice(article.index, 0, article)
      }
      this.selectArticles = []
      let maxLength = this.tmpMedia.articles.length - 1
      this.tmpMedia.articles.forEach(val => {
        this.selectArticles.push({
          ID: val.ID,
          value: val.index === maxLength ? 'selected' : ''
        })
      })
      this.tmpMedia.articles.length && this.initArticleContent(this.tmpMedia.articles[maxLength].ID)
    },
    // 预览(或取消预览)微信内容
    togglePreview() {
      this.previewState = !this.previewState
    }
  }

}
</script>
<style scoped>
.el-button + .el-button {
  margin-left: 0px;
}

.table-card {
  width: 400px;
  margin: auto;
  padding: 0;
  float: left;
}

.table-card .selected {
  border: 1px solid #28b06e;
}

.appmsg-title {
  position: relative;
  margin: 0;
}

.appmsg-title a {
  font-weight: 400;
  font-style: normal;
  font-size: 16px;
  color: #fff;
  width: 100%;
}

.appmsg_title {
  background: rgba(0, 0, 0, 0.5) !important;
  position: absolute;
  bottom: 0;
  width: 100%;
  font-size: 16px;
  padding: 15px 8px 10px 10px;
}

.appmsg-div,
.add-div {
  position: relative;
  padding: 15px;
  border-top: 1px solid #eee;
}

.appmsg-div a {
  font-size: 14px;
  color: #666;
}

.appmsg-div a:hover {
  color: black;
  text-decoration: none;
}

.appmsg-div img {
  float: right;
}

.add-body {
  text-align: center;
  line-height: 60px;
  border: 2px dashed #d9dadc;
  display: block;
  color: #8d8d8d;
}

.button-div {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  line-height: 100%;
  background: rgba(229, 229, 229, 0.85) !important;
  filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr='#d9e5e5e5', endcolorstr='#d9e5e5e5');
  text-align: center;
}

.appmsg-title:hover .button-div {
  display: inline;
}

.appmsg-div:hover .button-div {
  display: inline;
}
</style>
