<template>
  <div class="page" :class="{hiding:hiding}">
    <!-- <div class="tip">{{tip}}</div> -->
    <section class="today-news">
      <div class="title">今日早报</div>
      <a class="home nocolor" @click="showToday">
        <div class="f-shadow">
          <div class="bar">
            <div class="pic" :style="{'background-image': 'url(' + src + ')'}" ></div>
          </div>
          <div class="tip1">{{getText(title, 68)}}</div>
          <div class="tip2"><div class="nums">1</div>{{subTitle1}}</div>
          <div class="tip2"><div class="nums">2</div>{{subTitle2}}</div>
          <div class="go-more"></div>
        </div>
        <div class="guider-bg" v-if="hiding">
          <div class="guider-btn"></div>
        </div>
      </a>
    </section>

    <section class="activity">
      <div class="title" :class="{hiding:hiding}">展业活动</div>
      <div class="act-shadow" v-for="(item, index) in activitLyist" :key="index" :class="{'hiding':hiding}">
        <div class="act-img" :style="{'background-image': 'url(' + item.pic + ')'}"></div>
        <div class="act-info">
          <div class="act-title">{{item.title}}</div>
          <div class="act-desc">{{getText(item.desc, 90)}}</div>
          <div class="act-btns">
            <div class="act-btn" @click="tryGame(item)">试玩</div>
            <div class="act-btn act-share" @click="shareGame(item, true)">分享</div>
          </div>
        </div>
        <div class="act-ico" :class="'type'+(index+1)">{{item.contentTag}}</div>
        <div class="guider-btn" v-if="{hiding:hiding&&index==0}" @click="shareGame(item)"></div>
      </div>
    </section>


    <section class="container article-container" :class="{hiding:hiding}">
      <div class="header duiui-flex duiui-flex--spacebetween">
        <!-- <h3>热门文章</h3> -->
        <div class="title no-bottom">
          获客爆文
          <a @click="goArticlList" class="see-more__link" hover-class="none"><span class="more">查看更多</span></a>
        </div>
        
      </div>  
      <div class="article__list">
        <div v-for="item in list" class="content__wrap duiui-flex" :key="item.id" @click="goArticleDetail(item.id)">
          <div class="content-avator">
            <div class="main-img" :style="{'background-image': 'url(' + item.mainImgUrl + ')'}"></div>
          </div>         
          <div class="content-info duiui-flex__item">
            <p class="content-info__title">{{item.title}}</p>
            <div class="share-info duiui-flex">
              <div class="read-times">阅读{{item.readNum}}</div>
              <span class="dui-tag dui-tag--solid">同行分享{{item.sharedNum}}次</span>
            </div>
          </div>
        </div>
      </div>
    </section>
    <div class="intercept__modal" v-if="showInterceptModal">
      <div class="modal_main">
        <div class="J_close close" @click="closeModal"></div>
        <div class="banner-top"></div>
        <div class="tip_wrap">
          <p class="tip1">完善名片信息</p>
          <p class="tip2">让客户主动联系你</p>
        </div>
        <div class="J_complete btn" @click="goCardEditPage">去完善</div>
      </div>
    </div>  
  </div>
</template>

<script>
import { get, post } from "@js/request";
import { getUrlParameter, isWeChatApplet, formatUrl, getEllipsisText } from "@js/tooler";
import { shareConfig, updateLink } from "@js/share";


// const SCID = getUrlParameter('scid');
const urlParam = getParam();
const step = urlParam.step == 1;
const inMiniprogram = urlParam.mini == 1;
const API = {
  getInitDaily: '/kjy/mp/content/getInitDaily',
  getScId: '/kjy/mp/seller/getScId',
  getarticleList: '/kjy/mp/content/list',
  activityList: '/kjy/mp/content/activityList',
  userInfo: '/kjy/mp/user/info'
}

function getParam(){
  var param = getUrlParameter("param");
  try{
    var list = param.split("_");
    var json = {
      mini: list[0],
      step: list[1]
    }
    return json;
  }
  catch(e){

  }
  return {};
}

export default {
  data() {
    return {
      tip: "home",
      title: '',
      list: [],
      scid: 0,
      src: "//yun.dui88.com/h5-mami/webgame/kejiji/img/null.png",
      title: "",
      subTitle1: "",
      subTitle2: "",
      activitLyist: [],
      weixinQrcode: '',
      showInterceptModal: false,
      sellerId: "",
      loading: false
    };
  },
  props: {
    outside: {
      type: Boolean,
      default: false
    },
  },
  methods: {
    getText(str, size){
      return getEllipsisText(str, size);
    },
    closeModal() {
      this.showInterceptModal = false;
    },
    goCardEditPage() {
      this.showInterceptModal = false;
      wx.miniProgram.navigateTo({
        url: '/pages/sellercard/card_edit/main?sellerId=' + this.sellerId
      });
    },    
    async showToday() {
      // this.$router.push("/today");
      console.log("inMiniprogram = " + inMiniprogram);
      let res = await get(API.getScId, {contentId: this.scid, showCard: 1});
      if (res.success) {
        let id = res.data;
        if(inMiniprogram){
          // wx.miniProgram.postMessage({
          //   data: JSON.stringify({
          //     title: this.title,
          //     src: this.src
          //   })
          // })
          let params = {
            scid: id,
            n: Math.random(),
            title: this.title,
            src: this.src
          };
          if(step) params.shareGuide = true;

          let url = formatUrl('/pages/news/news_today/main', params);

          wx.miniProgram.navigateTo({
            url: url
          })
        }
        else{
          window.location.href = './daily?scid=' + id + '&n=' + Math.random()
        }
      }
      else{
        alert('请求数据出错');
      }
    },
    async getuserInfo() {
      console.log("getuserInfo");
      let res = await get(API.userInfo, {});
      if (res.success) {
        this.sellerId = res.data.sellerId;
      }
      else{
        if(res.code == "100010"){
          this.getH5Authorize();
        }
      }
    },
    async initData(){
      shareConfig({
        link: location.origin + location.pathname + location.search,
        title: "内容库",
        desc: '来自客集集的分享',
        img: 'https://yun.dui88.com/h5/miniprogram/kejiji/icons.png',
        debug: false
      })

      if(inMiniprogram){
        this.tip = "在小程序中";
      }
      else{
        this.tip = "在普通浏览器中";
      }
      // this.tip = window.navigator.userAgent.toLowerCase();
      let res = await get(API.getInitDaily, {});
      if (res.success) {
        let obj = res.data;
        this.scid = obj.id;
        this.src = obj.mainImgUrl;
        this.title = getEllipsisText(obj.title, 72);
        try{
          let contentHead = JSON.parse(obj.contentText).domesticNews;
          this.subTitle1 = contentHead[0].title;
          this.subTitle2 = contentHead[1].title;
        }
        catch(e){
          console.log(obj.text);
        }
      } else {
        if (res.code == '100010') {
          this.getH5Authorize()
        } else if (res.code == '100020') {
          
        }
      }
    },
    async getArticleList(type) {
      let res = await get(API.getarticleList, {pageNo: 1, pageSize: 5});
      if (res.success) {
        if (type) {
          this.list = this.list.concat(res.data);
        } else {
          this.list = res.data;
        }
      } else {

      }
    },
    async getActivityList() {
      let res = await get(API.activityList, {pageNo:1, pageSize:3});
      if (res.success) {
        // let activity_inprogress = res.data.filter(it => it.status == 2);
        // let activity_soon = res.data.filter(it => it.status == 1);
        // this.activitLyist = {activity_inprogress, activity_soon}
        let list = res.data;
        list.forEach(element => {
          let obj = JSON.parse(element.text);
          element.pic = obj.previewImageUrl;
          element.desc = obj.activity_des;
        });
        this.activitLyist = list;
      }
    },
    async goArticleDetail(id) {
      console.log(id);
      let params = {
        contentId: id
      };
      let res = await get(API.getScId, params);
      if (res.success) {
        let id = res.data;
        let url = formatUrl('/pages/article/main', {
          scid: id
        });
        wx.miniProgram.navigateTo({
          url: url
        });
      }
    },
    async goActivitySetting(item) {
      let obj = JSON.parse(item.text);
      let params = {
        contentId: item.id
      };
      let res = await get(API.getScId, params);
      if (res.success) {
        let id = res.data;

        let url = formatUrl('/pages/activity/link/main', {
          scid: id,
          img: obj.previewImageUrl,
          url: encodeURIComponent(obj.activity_url),
          lottery: obj.lottery
        });
        wx.miniProgram.navigateTo({
          url: url
        });
      }
    },
    goArticlList() {
      let url = '/pages/content/articleList/main';
      wx.miniProgram.navigateTo({
        url: url
      });
    },
    getH5Authorize(){
      let url = '/kjy/authorize/wxh5base?uri=' + encodeURIComponent('/kjy/mp/content' + location.search);
      window.location.href = url;
    },
    jump(item){
      console.log(item);
    },
    async tryGame(item){
      console.log(item);
      this.hiding = false;
      this.$emit("close");
      let params = {
        contentId: item.id
      };
      let res = await get(API.getScId, params);
      if (res.success) {
        let id = res.data;
        let url = location.protocol + "//" + location.host + '/kjy/mp/activity?preview=1&scid=' + id;
        url = encodeURIComponent(url);
        console.log(url);
        wx.miniProgram.navigateTo({url:`/pages/webview/main?url=${url}`});
      }
    },
    async shareGame(item, jump){
      if(this.loading){
        return;
      }
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
      }, 300);
      if(!jump){
        // let res_ = await get(API.userInfo, {});
        // if (res_.success) {
        //   this.weixinQrcode = res_.data.sellerWxQrCode;
        //   this.sellerId = res_.data.sellerId;
        // }
        // if (!this.weixinQrcode) {
        //   this.showInterceptModal = true;
        //   return;
        // }
      }
      
      this.hiding = false;
      this.$emit("close");
      if(this.hiding){
        localStorage.setItem("guider", 1);
      }
      let params = {
        contentId: item.id
      };
      // wx.miniProgram.postMessage({data: "guide"});
      let res = await get(API.getScId, params);
      if (res.success) {
        let id = res.data;
        console.log(item.text);
        let obj = JSON.parse(item.text);
        if(obj.lottery == 1){
          wx.miniProgram.navigateTo({url:`/pages/activity/setting/main?scid=${id}`});
        }
        else{
          let url = `/pages/share/main?scid=${id}`;
          wx.miniProgram.navigateTo({url: url});
        }
      }
    }
  },
  created() {
    this.hiding = this.outside;
    this.initData();
    this.getArticleList();
    this.getActivityList();
    this.getuserInfo();
  }
};
</script>
<style lang="less" scoped>
@import '../flex.less';
@import './home.less';
</style>