<template>
  <div v-show="loaded"
       class="wrap">
    <!-- 人物详情不展示banner -->
    <div v-if="form.articleTemplate !== 23 && !isPeople"
         class="banner"
         :style="{backgroundImage: form.bannerImg ? ('url(' + form.bannerImg + ')') : ''}">
      {{ form.columnName }}
    </div>
    <div class="content">
      <Breadcrumb ref="breadcrumb"
                  :data.sync="routes" />
      <div class="article">
        <div class="left">
          <template v-if="!isPeople">
            <h2>{{ form.title }}</h2>
            <div class="meta">{{ form.source && form.source + ' | ' }} {{ form.author && form.author + ' | ' }} {{ form.releaseTime }}</div>
            <div class="meta">{{ form.edit && $t('column.edit') + '：' + form.edit }} {{ form.audit && ' | ' + $t('column.auditor') + '：' + form.audit }} {{ form.label && ' | ' + $t('column.label') + '：' + form.label }}</div>
          </template>
          <p v-if="form.summary"
             class="brief">{{ form.summary }}</p>
          <div class="des"
               id="mainBody"
               v-html="form.mainBody"></div>
          <div v-if="form.fileList && form.fileList.length"
               class="annex">
            <h6>{{$t('column.attachmentDownload')}}</h6>
            <ul class="files">
              <li v-for="(file, i) in form.fileList"
                  :key="i">
                <span class="name">{{ file.fileName }}</span>
                <span class="download"
                      @click="download(file)">{{$t('column.download')}}</span>
              </li>
            </ul>
          </div>
        </div>
        <RightColumns ref="right"
                      :party="isParty" />
      </div>
    </div>
  </div>
</template>

<script>
import Setting from '@/setting'
import Util from '@/libs/util'
import Breadcrumb from '@/components/breadcrumb'
import RightColumns from '@/components/rightColumns'
import mixins from '@/mixins/article'
export default {
  mixins: [mixins],
  data () {
    return {
      id: this.$route.query.articleId,
      columnId: +this.$route.query.id,
      preview: this.$route.query.preview,
      loaded: false,
      routes: [],
      form: {},
      columnBanner: '',
      isParty: 0, // 组织机构
      isPeople: 0, // 人物详情
      gotBanner: 0
    }
  },
  components: {
    Breadcrumb,
    RightColumns
  },
  watch: {
    '$route' () {
      this.id = this.$route.query.articleId
      this.getInfo()
    }
  },
  mounted () {
    this.getColumnInfo()
  },
  methods: {
    // 获取文章详情
    getInfo () {
      // 预览直接取缓存数据，不然就调接口
      let cache = localStorage.getItem('article')
      if (this.preview && cache) {
        cache = JSON.parse(cache)
        const temId = cache.articleTemplate
        this.form = cache
        this.routes = [
          {
            name: cache.columnName,
          },
          {
            name: cache.title
          }
        ]
        if (temId == 69) this.isParty = 1 // 组织架构（articleTemplate=69）是另一套主题，加个class即可
        if (temId == 72) this.isPeople = 1 // 人物详情（articleTemplate=72）要隐藏除了正文和摘要以外的所有字段
        if (cache.releaseTime) cache.releaseTime = cache.releaseTime.split(' ')[0]
        this.loaded = true
      } else {
        this.$post(`${this.api.findArticle}?id=${this.id}`).then(async ({ data }) => {
          // 设置面包屑
          const { columnName, path, id } = this.$route.query
          this.routes = [
            {
              name: columnName || data.columnName,
              path: path ? '/' + path : '',
              query: {
                id: id || data.columnId
              }
            },
            {
              name: data.columnName
            }
          ]
          // 文章被禁用了就直接返回
          if (data.isDisable || !data.isRelease) {
            this.$router.back()
          } else {
            const temId = data.articleTemplate
            let path = `?articleId=${this.id}&id=${id}&columnName=${columnName || ''}&siteId=${data.siteId}&path=${path || ''}`
            if (temId === 25 || temId === 26) { // 会议活动/期刊详情
              this.$router.replace((temId === 25 ? '/article/activity' : '/publish/show') + path)
            } else {
              if (temId == 69) this.isParty = 1 // 组织架构（articleTemplate=69）是另一套主题，加个class即可
              if (temId == 72) this.isPeople = 1 // 人物详情（articleTemplate=72）要隐藏除了正文和摘要以外的所有字段
              data.releaseTime = data.releaseTime.split(' ')[0]
              this.form = data
              // 手动修复tinymce缩进bug（p标签下包裹多个子元素，p标签上只有text-indent，没有font-size，导致缩进2em的情况下未能缩进两个字符）
              this.$nextTick(() => {
                document.querySelectorAll('#mainBody p').forEach(e => {
                  try {
                    if (e.children.length && e.style.textIndent) {
                      e.style.fontSize = e.children[0].style.fontSize
                    }
                  } catch (e) { }
                })
              })
              this.columnId = data.columnId
              // 如果没上传banner
              if (!data.bannerImg) {
                const columns = await this.$post(this.api.listWithTree, Util.rsa({
                  siteId: this.site,
                  columnName: '',
                  templateId: '',
                  typeId: '',
                  isSort: 1
                }))
                this.getBanner(columns.data)
                this.form.bannerImg = this.gotBanner ? this.columnBanner || require('@/assets/images/article-banner.png') : ''
              }

              // 浏览量+1
              this.$post(this.api.articlePreview, Util.rsa(this.id)).then(res => { }).catch(err => { })
              this.loaded = true
            }
          }
        }).catch(err => { })
      }
    },
    // 列表详情
    getColumnInfo () {
      this.columnId && this.$post(`${this.api.findColumn}?id=${this.columnId}`)
        .then(({ data }) => {
          if (data.detailStyleId == 69) this.isParty = 1
        })
        .catch((res) => { });
    },
    // 获取banner 规则：当前文章有上传的话，用上传的，没有上传的话，如果所属栏目有图片，读取栏目的（所属栏目没有的话读上级，上级没有就上上级，以此类推）都没有的话读取默认的
    getBanner (data) {
      for (const e of data) {
        if (e.columnBanner && !this.gotBanner) this.columnBanner = e.columnBanner
        if (e.id == this.columnId) {
          this.gotBanner = 1
          break
        } else {
          this.getBanner(e.children)
        }
      }
    },
    // 下载附件
    download (e) {
      Util.downloadFile(e.fileName, e.filePath)
    },
  }
};
</script>

<style lang="scss" scoped>
@import './editor.css';
.content {
    width: 1200px;
    /deep/ .el-breadcrumb {
        font-size: 0.98rem;
    }
}
.banner {
    display: flex;
    align-items: center;
    height: 21.6rem;
    padding-left: 10%;
    font-size: 2rem;
    font-weight: 600;
    color: #fff;
    background: url(../../assets/images/intro-bg.png) center center no-repeat;
    object-fit: cover;
}
.article {
    display: flex;
    justify-content: space-between;
    .left {
        width: 70%;
    }
    h2 {
        font-size: 1.9rem;
        color: #1c1c1c;
    }
    .meta {
        margin: 1rem 0;
        font-size: 0.88rem;
        color: #9b9b9b;
    }
    .brief {
        padding-bottom: 1.5rem;
        margin: 1rem 0;
        font-size: 1.2rem;
        line-height: 1.6;
        color: #606060;
        border-bottom: 1px solid #d8d8d8;
    }
    /deep/.des {
        // width: 100%;
        // overflow: auto;
        a {
            color: rgb(0, 0, 238);
            word-wrap: break-word;
        }
        img {
            max-width: 100%;
            object-fit: cover;
        }
        ul {
            // padding-left: 40px;
            list-style: disc;
            li {
                list-style: inherit;
            }
        }
        ol {
            // padding-left: 40px;
            list-style: decimal;
            li {
                list-style: inherit;
            }
        }
    }
    .annex {
        margin-top: 30px;
        h6 {
            padding-left: 8px;
            margin-bottom: 20px;
            font-size: 16px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            line-height: 1;
            color: #333;
            border-left: 4px solid #1583ff;
        }
        li {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        .name {
            margin-right: 8px;
            font-size: 14px;
        }
        .download {
            color: #1583ff;
            cursor: pointer;
        }
    }
}

@media (max-width: 1420px) {
    .content {
        width: 98%;
    }
}
@media (max-width: 1200px) {
    .article {
        /deep/.des {
            img {
                max-width: 100%;
                max-height: 15rem;
            }
        }
    }
    .banner {
        font-size: 1.5rem;
    }
    .article {
        flex-direction: column;
        .left {
            width: 100%;
            h2 {
                font-size: 1.5rem;
            }
        }
    }
    .article {
        .des {
            img {
                height: 15rem !important;
            }
        }
    }
    .right {
        width: 100%;
    }
}
</style>