// pages/coupons.js
const app = getApp()
const wxService = require('../../utils/wxService')
const utils = require('../../utils/util')
const envInfo = require('../../config/index').envInfo
import { Integer } from '../../utils/integerDigitalConvertion'
const { memberId, member } = wx.getStorageSync('_baseUserInfo')

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    contentInfo:[],
    id:'',
    pageNo:1,
    pageSize:100,
    proList:[],

    showCardModal: false,
    currentShareContent: null,
    pagePath:'',
    loadingTime:'',
    scene: ''
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options && options.id){
      this.setData({
        id: options.id
      })
    }

    let memberIdByPage = options.memberId;
    if (memberIdByPage) {
      const { memberId, member } = wx.getStorageSync('_baseUserInfo')
      wxService.post(`/merchant/contentMobileTerminal/getContentParticulars`, {
        id: this.data.id,
        userId: memberId
      }).then(res => {
        if (!res) return false
        const { result, data } = res.data
        if (result == 0) {
          this.setData({
            contentInfo: data
          })
          let content = {
            title: this.data.contentInfo.headline,
            id: this.data.contentInfo.id,
            article: this.data.contentInfo.article,
            url: this.data.contentInfo.shareShowPictureRESDTOList[0].url
          }
          let tentacleInfo = {
            content: JSON.stringify(content),
            contentId: this.data.contentInfo.id,
            tentacleId: memberIdByPage,
            contentType: app.globalData.contants.SHARE_TYPE.DETAILS_OF_THE_CONTENT, //内容类型 
            title: this.data.contentInfo.headline, //标题
            type: 3// 1:门店,2:员工(暂时不做),3:会员,4:第三方外部渠道,5:智能营销
          }

          this.generatePointObject(tentacleInfo);
        }

      }).finally(() => {
      })
     
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const { memberId, member } = wx.getStorageSync('_baseUserInfo')
    this.getContentDetail()
    this.data.currentShareContent = null;

    //超过15s统计阅读
    this.setData({
      loadingTime: setTimeout(() => {
        let params = {
          contentId: this.data.contentInfo.id,
          type: 2,
          userId: memberId
        }
        this.getReadyOrForwardNumber(params)

      }, 15000)
    })
   
  },

  _getUserInfo(res = {}) {
    wxService.nextTick(() => {
      this.triggerEvent('getAuth', res);
    })
  },

  // 统计阅读和转发量
  getReadyOrForwardNumber(params){
    if (this.data.currentHasUserInfo){
      wxService.post(`/merchant/contentMobileTerminal/operationSave`, params).then(res => {
        if (!res) return false
        const { result, data } = res.data
        if (result == 0) {
        }
      }).finally(() => {
      })
    }
  },

  //跳转商品详情
  onTapToGoodsInfo(e){
    let item = e.currentTarget.dataset.item;
    let productId = e.currentTarget.dataset.productid;
    //组装一个临时触点信息对象到本地
    let tempObj = {
      memberId: item.userId ? item.userId : '-99',
      obj : {
        id: item.tentacleObjectId,
        tentacleType: item.tentacleType,
        tentacleId: item.tentacleId,
        contentType: item.contentType,
        contentId: item.contentId
      }
    };
    //存储
    var timestamp = Date.parse(new Date())
    var expiration = timestamp + 1800000
    wx.setStorageSync('TIME_EXPIRATION', expiration);
    wx.setStorageSync('TEMP_TENTACLE_INFO', tempObj);
    wxService.router(`/pages/productDetail/productDetail?id=${productId}&fromZc=1`);
  },

  // 分享
  onTapShare() {
    const { memberId, member } = wx.getStorageSync('_baseUserInfo')
    let content = {
      title: this.data.contentInfo.headline,
      id: this.data.contentInfo.id,
      article: this.data.contentInfo.article,
      url: this.getImageInShareShowPictureRESDTOList()
    }

    let tentacleInfo = {
      content: JSON.stringify(content),
      contentId: this.data.contentInfo.id,
      contentType: app.globalData.contants.SHARE_TYPE.DETAILS_OF_THE_CONTENT, //内容类型 
      title: this.data.contentInfo.headline, //标题
      type: 3// 1:门店,2:员工(暂时不做),3:会员,4:第三方外部渠道,5:智能营销
    }

    this.data.currentShareContent = this.data.contentInfo;

    wxService.getTentacleContent(tentacleInfo).then(res => {
      if (res && res.id) {
        this.data.currentShareContent.tentacleId = res.id;
        let id = Integer.digit(this.data.currentShareContent.id, 10, 64);
        let tentacleId = Integer.digit(this.data.currentShareContent.tentacleId, 10, 64);
        var path = 'pages/wantToBuyDetail/wantToBuyDetail';
        let scene = 'i=' + id + '&t=' + tentacleId
        this.setData({
          showCardModal: true,
          cardTitle: this.data.contentInfo.headline,
          cardUrl: this.getImageInShareShowPictureRESDTOList(),
          pagePath: path,
          scene: scene
        });
        let params = {
          contentId: this.data.contentInfo.id,
          type: 3,
          userId: memberId
        }
        this.getReadyOrForwardNumber(params)
      }
    })
  },

  //获取内容第一个图片
  getImageInShareShowPictureRESDTOList(){
    let arr = this.data.contentInfo.shareShowPictureRESDTOList;
    let reg = /^http.*(gif|png|jpeg|jpg|PNG|JPEG|JPG?g)$/,
      url = '';
    for (let i = 0; i < arr.length ; i ++){
      if (reg.test(arr[i].url)){
        url = arr[i].url;
        break;
      }
    }

    return url;
  },

  // 获取内容详情
  getContentDetail(){
    const { memberId, member } = wx.getStorageSync('_baseUserInfo')
    wxService.post(`/merchant/contentMobileTerminal/getContentParticulars`,{
      id: this.data.id,
      userId: memberId
    }).then(res => {
      if (!res) return false
      const { result, data } = res.data
      if (result == 0) {
        this.setData({
          contentInfo: data
        })
        this.getProList()
      }

    }).finally(() => {
    })
  },

  //获取内容下商品列表
  getProList(){
    var params = {
      productIds: this.data.contentInfo.productIds
    }
    if (this.data.contentInfo.productIds && this.data.contentInfo.productIds.length > 0){
      wxService.post(`/sale/product/buyer/listPage?pageNo=${this.data.pageNo}&pageSize=${this.data.pageSize}`, params).then(res => {
        if (!res) return false
        const { result, data } = res.data
        if (result == 0 && data.content) {
          this.setData({
            proList: data.content
          })
        }
      }).finally(() => {
      })
    }
  },


  // 点赞
  gotoLike(){
    const { memberId } = wx.getStorageSync('_baseUserInfo')
    let params = {
      contentId: this.data.contentInfo.id,
      type: 1,
      userId: memberId
    }
    if (!this.data.contentInfo.type) {
      wxService.post(`/merchant/contentMobileTerminal/operationSave`, params).then(res => {
        if (!res) return false
        const { result, data } = res.data
        if (result == 0) {
          wx.showToast({
            title: '点赞成功',
            icon: 'none'
          })
          this.getContentDetail()
        }

      }).finally(() => {
      })

    } else {
      wxService.post(`/merchant/contentMobileTerminal/operationDelete`, {
        id: this.data.contentInfo.id,
        userId: memberId
      }).then(res => {
        if (!res) return false
        const { result, data } = res.data
        if (result == 0) {
          wx.showToast({
            title: '取消点赞成功',
            icon: 'none'
          })
          this.getContentDetail()
        }

      }).finally(() => {
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearTimeout(this.data.loadingTime)
  },

  /**
  * 用户点击右上角分享
  */
  onShareAppMessage: function (res) {
    if (res.from != 'menu') {
      let id = Integer.digit(this.data.currentShareContent.id, 10, 64);
      let tentacleId = Integer.digit(this.data.currentShareContent.tentacleId, 10, 64);
      var path = 'pages/wantToBuyDetail/wantToBuyDetail?i=' + id + '&t=' + tentacleId;
      return {
        path: path,
        title: this.data.cardTitle,
        imageUrl: this.data.cardUrl, // 可以更换分享的图片
      }
    }else{
      //修改为参数memberId
      var path = `pages/wantToBuyDetail/wantToBuyDetail`;
      const { memberId, member } = wx.getStorageSync('_baseUserInfo')
      if (memberId) {
        let m = Integer.digit(memberId, 10, 64);
        let contentId = Integer.digit(this.data.contentInfo.id, 10, 64);
        path = `pages/wantToBuyDetail/wantToBuyDetail?i=${contentId}&m=${m}`;
      }
      return {
        title: this.data.cardTitle,
        path: path,
        imageUrl: this.data.cardUrl
      }
    }
  }
 
})