<template>
  <div class="article_container" v-if="article">
    
    <div class="richText">
      <div class="title" v-if="article.title">{{article.title}}</div>
      <div class="title_info">
        <div class="title_user" v-if="article.author">{{article.author}}</div>
        <div class="title_time" v-if="article.createDatetime">{{article.createDatetime}}</div>
      </div>
      <!-- <wxParse :content="article.content" v-if="!article.msg" /> -->
      <!-- <div v-html="article.content" v-if="!article.msg"></div>/ -->
      <mp-html :content="article.content" :copy-link="false" @linktap="linktap" v-if="!article.msg" />
      <!-- <rich-text :datas="datas" v-if="!article.msg"></rich-text> -->
      <div class="title" style="min-height: 50vh;color: #999;align-items: center;display: flex;justify-content: center;" v-else>{{article.msg}}</div>
    </div>
    <div style="width:100%;height:10px;background-color:#EEF2F5;"></div>
    <ul>
      <div class="all">全部评论</div>
      
      <div v-if="list.length == 0" style="text-align: center;color: #969799;font-size:12px">暂无评论</div>
      <li id="pingLun" style="opacity:0;height: 0px;position:absolute;top:-130px;left:0;"></li>
      <li class="van-hairline--bottom" v-for="(item,index) in list" :key="index">
        <div class="left">
          <img :src="(item.userImageUrl || item.handImage) | DFSImg(400,400)" alt="">
        </div>
        <div class="middle">
          <div style="color:#666666;">{{item.reviewName}}</div>
          <div class="time">{{getTime(item.updateDatetime)}}</div>
          <div class="show_info">{{item.content}}</div>
        </div>
      </li>
    </ul>
    <div class="bottom van-hairline--top">
      <input confirm-type="search" placeholder="说两句吧" v-model="commentContent" @confirm="commentsSubmit">
      <div class="icon_box">
        <div class="share" @click="toBottom">
          <div class="num">
            {{total}}
          </div>
          <img src="https://mayi-newshop.oss-cn-shanghai.aliyuncs.com/product/2EWPQRMQwm.png?x-oss-process=image/resize,m_pad,limit_0,w_400,h_400" alt="">
        </div>
        <div class="share" @click="thumbsUp">
          <img src="https://mayi-newshop.oss-cn-shanghai.aliyuncs.com/product/i3HttTMh6f.png?x-oss-process=image/resize,m_pad,limit_0,w_400,h_400" alt="" v-if="!isThumbsUp">
          <img src="https://mayi-newshop.oss-cn-shanghai.aliyuncs.com/product/MkRsXX3QsM.png?x-oss-process=image/resize,m_pad,limit_0,w_400,h_400" alt="" v-else>
        </div>
        <div class="share" @click="poupShow">
          <img src="https://mayi-newshop.oss-cn-shanghai.aliyuncs.com/product/wBYDz3CZkM.png?x-oss-process=image/resize,m_pad,limit_0,w_400,h_400" alt="">
        </div>
      </div>
    </div>

    <shade-guide ref="shadeGuide" />
  </div>
</template>

<script>
import article from '@/api/article'
import shadeGuide from "./shadeGuide.vue";
import { throttle, concatUrl } from "../../../utils/index.js"
// import wxParse from 'mpvue-wxparse'

const app = getApp();
const { $themeToLink, log } = app;
export default {
  data() {
    return {
      article: null,
      commentContent: '',
      articleId: null,
      isThumbsUp: false,

      loading: false,
      finished: false,
      list: [],
      total: 0,
      query: {
        pageNum: 0,
        pageSize: 20,
      },
    }
  },
  components: {
    "shade-guide": shadeGuide,

  },
  created() {
  },
  onReady() {
  },
  onLoad(options) {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })

    if (options.queryStr) {
      wx.showModal({
        title: "",
        content: options.queryStr,
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#3CC51F',
        success: (result) => {
          if (result.confirm) {

          }
        },
        fail: () => { },
        complete: () => { }
      });
    } else if (options.article_id) {
      this.articleId = options.article_id
      this.query['articleId'] = this.articleId
      this.init()
    }

    //进页面存储需要绑定的信息
    if (options.userId || options.spokesmanRelId) {
      wx.setStorage({
        key: "becomeInfo",
        data: JSON.stringify(options)
      });
    }

    if (wx.getStorageSync("sessionid")) {
      //获取分销信息
      this.getSpokesmanInit(wx.getStorageSync("becomeInfo") ? JSON.parse(wx.getStorageSync("becomeInfo")) : '')
    }


  },
  // onShareAppMessage() {
  //   return {
  //     title: '',
  //     path: `/pages/pages_subpack/article/main?article_id=${this.articleId}`
  //   }
  // },
  async onShareAppMessage(res) {
    console.log('wxshare');
    let newHref = `/pages/pages_subpack/article/main?article_id=${this.articleId}`;
    let title = app.globalData.shopInfo.shopName;
    let hasInvitationStatus = 0;
    if (wx.getStorageSync("sessionid")) {
      await app.fenxiaoModel.getSpokesmanidByShare().then(data => {
        hasInvitationStatus = data.hasInvitationStatus;
      })
      await app.fenxiaoModel.getSpokesmanInfo().then(data => {
        let newData = {}
        if (data != null) {
          if (hasInvitationStatus == 1) {
            newData = {
              spokesmanGroupId: data.groupId,
              spokesmanShopId: data.shopId,
              spokesmanRelId: data.id,
              userId: data.userId
            }
          } else {
            newData = {
              userId: data.userId
            }
          }
        }
        newHref = concatUrl(newHref, newData)
      })
    }
    console.log(newHref, title, 'share');
    return {
      title: title, // 默认是小程序的名称
      path: newHref, // 默认是当前页面
      imageUrl: '',
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == "shareAppMessage:ok") {
          log.info(res, "分享成功");
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == "shareAppMessage:fail cancel") {
          // 用户取消转发
          log.info(res, "分享失败");
        } else if (res.errMsg == "shareAppMessage:fail") {
          // 转发失败,其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调(转发成不成功都会执行)
      }
    };
  },
  //用户点击右上角分享朋友圈
  onShareTimeline: function () {
    return {
      title: '',
      query: `article_id=${this.article_id}`,
      imageUrl: ''
    }
  },
  // async onShareTimeline() {
  //   console.log('Timeline');
  //   // let newHref = `/pages/pages_subpack/article/main?article_id=${this.articleId}`;
  //   let newHref = ''
  //   let title = app.globalData.shopInfo.shopName;
  //   let hasInvitationStatus = 0;
  //   if (wx.getStorageSync("sessionid")) {
  //     await app.fenxiaoModel.getSpokesmanidByShare().then(data => {
  //       hasInvitationStatus = data.hasInvitationStatus;
  //     })
  //     await app.fenxiaoModel.getSpokesmanInfo().then(data => {
  //       let newData = {}
  //       if (data != null) {
  //         if (hasInvitationStatus == 1) {
  //           newData = {
  //             spokesmanGroupId: data.groupId,
  //             spokesmanShopId: data.shopId,
  //             spokesmanRelId: data.id,
  //             userId: data.userId
  //           }
  //         } else {
  //           newData = {
  //             userId: data.userId
  //           }
  //         }
  //       }
  //       newHref = concatUrl(newHref, newData)
  //     })
  //   }
  //   console.log(newHref, title, 'TimelineShare');
  //   // let queryStr = `articleId_${this.articleId}/spokesmanGroupId_${obj.spokesmanGroupId}/spokesmanShopId_${obj.spokesmanShopId}/spokesmanRelId_${obj.spokesmanRelId}/userId_${obj.userId}`
  //   return {
  //     title: title,
  //     query: 'a=1111',
  //     imageUrl: '',
  //     createDatetime: ''
  //   }
  // },
  methods: {
    toPageUrl(backPath, backParams = "") {
      return `../../index/main?from=themeLink&backpath=${encodeURIComponent(
        backPath
      )}&params=${encodeURIComponent(backParams)}`;
    },
    getUrlofLink(data) {
      return data.link.split("?")[0];
    },
    getUrlofQuery(data) {
      let arr = data.link.split("?")
      let params = [];
      arr.forEach((res, index) => {
        if (index >= 1) {
          params.push(res)
        }
      })
      return params.join("?") || "";
    },
    linktap(e) {
      console.log(e.mp.detail);
      let href = e.mp.detail.href
      let articleid = e.mp.detail['data-articleid']
      let productid = e.mp.detail['data-productid']
      let data = {
        link: `/goods/${productid}`,
        type: 1
      }
      let url = this.toPageUrl(this.getUrlofLink(data), this.getUrlofQuery(data));
      console.log(url,'last');
      wx.navigateTo({
        url

      });

      // console.log(href, articleid, productid);
      // let linkVal = `/goods/${productid}`;
      // $themeToLink({
      //   type: 1,
      //   link: linkVal
      // });

    },
    getSpokesmanInit(extConfig) {
      //绑定上下级关系
      app.fenxiaoModel.becomeRelation(extConfig).then(res => {
        if (res) {
          wx.removeStorage({
            key: "becomeInfo"
          });
        }
      })
    },
    //富文本解析和替换
    formatRichText(html) {
      // let newContent = html.replace(/class="(.*)gobuy(.*)"/gi,function(match){
      //   match = match + ' onclick="gotowebview"'
      //  console.log(match, 'match');
      //  return match;
      // })
      let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
        if (match.startsWith('<img style="object-fit: contain;')) {
          // console.log(match, 'match');
          match = match.replace(/height:(.*?);/g, 'height: 76px !important;')
          match = match.replace(/width:(.*?);/g, 'width: 90px !important;')
          // console.log(match, 'match');
        } else {
          match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
          match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
          match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        }
        return match;
      });
      // console.log('newContent', newContent);
      // newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
      //   match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
      //   return match;
      // });
      // newContent = newContent.replace(/<br[^>]*\/>/gi, '');
      // newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:10px 0;"');

      return newContent
    },
    init() {
      log.info('qq');
      article.getArticleInfo(this.articleId).then(res => {
        if (res.data.data) {
          let article = res.data.data
          let content = res.data.data.content.replace('<body>', '<div style="overflow-x: hidden;width:100%">').replace("</body>", "</div>")
          let createDatetime = article.createDatetime != '' ? article.createDatetime.slice(0, -9) : ''
          article.content = this.formatRichText(content)
          article.createDatetime = createDatetime
          this.article = article
          // this.createDatetime = article.createDatetime != '' ? article.createDatetime.slice(0,-3):''
          // log.info(this.createDatetime,'article.createDatetime');
          if (article.fabulousFlag == 'true') {
            this.isThumbsUp = true;
          }
          // 不设置title
          // if (article.title && article.title.length) {
          //   wx.setNavigationBarTitle({
          //     title: article.title
          //   })
          // }
        }
      });

    },
    poupShow() {
      this.$refs.shadeGuide.open();
    },
    // 文章评论
    commentsSubmit(e) {
      log.info('submit');
      if (this.articleId == null) return
      if (this.commentContent.trim().length == 0) {
        wx.showToast({
          title: '请输入要评论的内容',
          icon: 'none',
          duration: 1000,
        });
        return
      }
      let query = {
        articleId: this.articleId,
        content: this.commentContent
      }
      log.info(query);
      article.saveReview(query).then(res => {
        if (res.data.code == '200') {
          this.commentContent = '';
          wx.showToast({
            title: '评论成功,正在审核',
            icon: 'none',
            duration: 1000,
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 1000,
          });
        }
      })
    },
    //点赞
    thumbsUp() {
      // this.$refs.shadeGuide.open();
      let query = {
        articleId: this.articleId,
        fabulousType: !this.isThumbsUp ? 1 : 2
      }
      // if(!this.isThumbsUp){
      article.addLike(query).then(res => {
        if (res.data.code == "200") {
          this.isThumbsUp = !this.isThumbsUp;
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 1000,
          });
        }
      })
      // }else {
      //   article.cancelLike(query).then(res=>{
      //     if(res.code=="200"){
      //       this.isThumbsUp = !this.isThumbsUp;
      //     }else {
      //       Toast(res.msg)
      //     }
      //   })
      // }
    },
    // 获取评论
    getComments() {
      this.query.pageNum += 1;
      article.getReviews(this.query).then(res => {
        this.loading = false;
        if (res.data.code == '200') {
          res.data.data.forEach(ele => {
            this.list.push(ele)
          })
          this.total = res.data.total;
          if (res.data.data.length < 20) {
            this.finished = true
          }
        } else {
          this.finished = true;
        }
        log.info(res, 777777777)
      })
    },
    getTime(time) {
      time = time.replace(/-/g, "/");
      log.info(time, 888888888)
      let timestamp = (Date.parse(new Date()) - Date.parse(new Date(time))) / 1000;
      if (timestamp < 60) {
        return '刚刚'
      } else if (timestamp < 3600) {
        return parseInt(timestamp / 60) + '分钟前'
      } else if (timestamp < 3600 * 12) {
        return parseInt(parseInt(timestamp / 60) / 60) + '小时前'
      } else if (new Date().getFullYear() == new Date(time).getFullYear()) {
        return time.slice(5).replace(/\//g, "-")
      } else if (new Date().getFullYear() > new Date(time).getFullYear()) {
        return time.replace(/\//g, "-")
      }
    },
    // 划到最底部
    toBottom() {
      wx.createSelectorQuery().select('.article_container').boundingClientRect(function (rect) {
        // 使页面滚动到底部
        log.info(rect.height, 'rect.height');
        wx.pageScrollTo({
          scrollTop: rect.height
        })
      }).exec()
    },
  }
}
</script>

<style lang="scss" scoped>
// @import url("~mpvue-wxparse/src/wxParse.css");
.mceNonEditable{
  box-sizing: border-box;
}
.imgbox .img {
  height: 96px !important;
}
.article_container {
  position: relative;
}
.richText {
  width: 100%;
  height: auto;
  padding: 0 10px;
  padding-bottom: 100px;
  box-sizing: border-box;
  overflow-x: hidden;
}

.title {
  font-size: 20px;
  color: #333;
  width: 100%;
  padding: 12px 0;
  text-align: left;
  font-weight: 700;
}
.title_info {
  display: flex;
  justify-content: flex-start;
  // padding: 0 12px;
  font-size: 13px;
  margin-bottom: 24px;
}
.title_user {
  width: 100%;
  color: #999;
}
.title_time {
  width: 100%;
  // padding-right: 13px;
  text-align: left;
  color: #999;
}

.bottom {
  width: 100%;
  height: 49px;
  position: fixed;
  background-color: #fff;
  bottom: 0;
  left: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px;
  padding-right: 22px;
  box-sizing: border-box;
}
input {
  border: none;
  width: 150px;
  height: 20px;
  line-height: 20px;
  background-color: #eeeeed;
  border-radius: 16px;
  padding: 5px 13px;
  font-size: 16px;
}

.icon_box {
  flex-grow: 1;
  display: flex;
  padding-left: 9px;
  align-items: center;
  justify-content: space-between;
}
.share,
.zan {
  width: 26px;
  height: 26px;
  display: flex;
  align-items: center;
  position: relative;
}
.num {
  position: absolute;
  top: -9px;
  left: calc(100% - 9px);
  border-radius: 10px;
  min-width: 18px;
  height: 18px;
  background-color: #ff4848;
  color: #fff;
  text-align: center;
  line-height: 18px;
  padding: 0 6px;
  /* transform: translateX(100%); */
}
img {
  max-width: 100%;
  height: 100%;
  /* margin-right: 30px; */
}

ul {
  width: 100%;
  // padding-bottom: 22px;
  position: relative;
  padding: 0 10px;
  margin-bottom: 100px;
  box-sizing: border-box;
  li {
    width: 100%;
    padding-right: 7px;
    display: flex;
    padding: 0 12px;
    margin-bottom: 10px;
    padding-bottom: 12px;
    .left {
      width: 36px;
      height: 36px;
      height: 100%;
      margin-right: 14px;
      border-radius: 20px;
      overflow: hidden;
      img {
        width: 100%;
        // height: 36px;
      }
    }
    .middle {
      width: 100%;
      font-size: 13px;
      .show_info {
        font-size: 14px;
        color: #333333;
      }
      .time {
        padding: 5px 0 8px;
        color: #666666;
      }
    }
  }
  .all {
    width: 100%;
    font-size: 14px;
    color: #333;
    padding: 10px 12px 12px;
  }
}
</style>