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

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    categoryList: [], //分类
    baseImgUrl: app.globalData.imageUrl,
    pageNum: 1,
    pageSize: 3,
    totalPages: 0,
    totalElements: 0,
    currentTab: 0,
    showCardModal: false,
    cardTitle: '',
    cardUrl: '',
    pagePath:'',
    contentList: [],
    contentPermission: false,
    currentShareContent: null,
    scene:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.hideShareMenu();
    let memberId = options.memberId;
    if (memberId) {
      let tentacleInfo = {
        content: '我的发布页面',
        title: '我的发布',
        tentacleId: memberId,
        contentType: app.globalData.contants.SHARE_TYPE.CONTENTS_LIST,
        type: 3// 1:门店,2:员工(暂时不做),3:会员,4:第三方外部渠道,5:智能营销
      };

      this.generatePointObject(tentacleInfo);
    }
    

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const { memberId, member } = wx.getStorageSync('_baseUserInfo')
    const premiumExpireTime = member && member.premiumExpireTime || ''
    // ios 兼容 是不是plus vip
    let currentEndTime = (new Date(premiumExpireTime.replace(/-/g, '/'))).getTime(); // 到期时间
    let time = (new Date()).getTime(); 
    if (member && member.premiumExpireTime && currentEndTime > time) {
      this.setData({
        plus: 1
      })
    } else {
      this.setData({
        plus: 0
      })
    }
    
    this.getBannerInfo()
    this.getContentPermission()
    this.data.currentShareContent = null;
    this.setData({
      pageNum: 1
    })
    //获取内容列表
    this.getContentList(this.data.pageNum);
    
  },

  // 发布内容权限
  getContentPermission(){
    const { memberId, member } = wx.getStorageSync('_baseUserInfo')
    wxService.post(`/merchant/contentMobileTerminal/getReleasePermissions`, {
      userId: memberId,
      plus:this.data.plus,
      level: member.level || 0
    }).then(res => {
      if (!res) return false
      const { result, data } = res.data
      if (result == 0) {
        this.setData({
          contentPermission: data
        })
      }
    }).finally(() => {
    })
  },

  // banner
  getBannerInfo(){
    const { memberId, member } = wx.getStorageSync('_baseUserInfo')
    wxService.post(`/merchant/contentMobileTerminal/getBannerAndInviteSum`, {
      userId: memberId
    }).then(res => {
      if (!res) return false
      const { result, data } = res.data
      if (result == 0) {
        this.setData({
          bannerUrl: data.bannerUrl,
          inviteSum: data.inviteSum,
          yesterdayInviteSum: data.yesterdayInviteSum
        })
      }
    }).finally(() => {
    })
  },



  // 获取发现内容
  getContentList(pageNum) {
    wx.showLoading({
      title: '加载中'
    })
    const { memberId } = wx.getStorageSync('_baseUserInfo')
    wxService.post(`/merchant/contentMobileTerminal/getContentList?pageNum=${pageNum}&pageSize=${this.data.pageSize}`, {
      userId: memberId
    }).then(res => {
      wx.hideLoading()
      if (!res) return false
      const { result, data } = res.data
      if (result == 0) {
        if (data.content) {
          this.setData({
            contentList: pageNum == 1 ? [...data.content] : [...this.data.contentList, ...data.content],
            totalPages: data.totalPages,
            totalElements: data.totalElements
          },() => {
            console.log(this.data.contentList)
          })


        } else {
          this.setData({
            contentList: []
          })
        }
      }
    }).finally(() => {
      wx.hideLoading()
    })
  },

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

  // 点赞
  gotoLike(e) {
    let params = {
      contentId: e.detail.contentId,
      type: 1,
      userId: e.detail.userId
    }
    if (!e.detail.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.setData({
            pageNum: 1
          })
          this.getContentList(this.data.pageNum)
        }

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

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

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

  // 分享
  _onTapShare(e) {
    const { memberId, member } = wx.getStorageSync('_baseUserInfo')
    console.log(e)
    let tentacleInfo = {
      content: JSON.stringify(e.detail),
      contentId: e.detail.id,
      contentType: app.globalData.contants.SHARE_TYPE.DETAILS_OF_THE_CONTENT, //内容类型 1.文章 2.商品 3.页面
      title: e.detail.title, //标题
      type: 3// 1:门店,2:员工(暂时不做),3:会员,4:第三方外部渠道,5:智能营销
    }

    this.data.currentShareContent = e.detail;

    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: e.detail.title,
          cardUrl: e.detail.url,
          pagePath: path,
          scene: scene
        });

        let params = {
          contentId: e.detail.id,
          type: 3,
          userId: memberId
        }
        this.getReadyOrForwardNumber(params)
      }
    })
  },

  /**
 * 页面相关事件处理函数--监听用户下拉动作
 */
  onPullDownRefresh: function () {
    this.setData({
      pageNum: 1,
    })
    this.getContentList(this.data.pageNum)
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { pageNum, pageSize, totalPages } = this.data
    if (pageNum < totalPages) {
      this.setData({
        pageNum: pageNum + 1,
      })
      this.getContentList(this.data.pageNum)
    }
  },
  /**
 * 用户点击右上角分享
 */
  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;
      console.log(path)
      return {
        path: path,
        imageUrl: this.data.cardUrl // 可以更换分享的图片
      }
    }
    else {
      //修改为参数memberId
      const { memberId, member } = wx.getStorageSync('_baseUserInfo')
      var path = `subPackage/page/pages/myRelease/myRelease`;
      if (memberId) {
        let m = Integer.digit(memberId, 10, 64);
        path = `subPackage/page/pages/myRelease/myRelease?m=${m}`;
      }
      return {
        path: path
      }
    }

  }
})