// 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: {
    categoryList:[], //分类
    baseImgUrl: app.globalData.imageUrl,
    pageNum: 1,
    pageSize: 10,
    totalPages: 0,
    totalElements: 0,
    currentTab: 0,
    showCardModal:false,
    cardTitle:'',
    cardUrl:'',
    pagePath:'',
    contentList:[],
    currentShareContent: null,
    contentPermission: false,
    scene: ''
  },
 
  // 点击切换
  clickTab: function (e) {
    const { current } = e.target.dataset
    if (this.data.currentTab == current) {
      return false;
    } else {
      this.setData({
        currentTab: current,
      })
    }
    this.setData({
      pageNum: 1
    })
    this.getContentList(this.data.pageNum,current)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    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.getCategoryList()
    this.getContentPermission()
    this.data.currentShareContent = null;
  },

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

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

// 获取分类
  getCategoryList(){
    wxService.post(`/merchant/contentMobileTerminal/gatClassify`).then(res => {
      if (!res) return false
      const { result, data } = res.data
      if (result == 0) {
        this.setData({
          categoryList:data,
          pageNum: 1,
          currentTab: data[0].id
        })

        this.getContentList(this.data.pageNum,data[0].id)
      }

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

  // 获取发现内容
  getContentList(pageNum,classifyId){
    const { memberId, member } = wx.getStorageSync('_baseUserInfo')
    wxService.post(`/merchant/contentMobileTerminal/getContentList?pageNum=${pageNum}&pageSize=${this.data.pageSize}`, {
      classifyId: classifyId,
      userId: memberId
    }).then(res => {
      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('666666',this.data.contentList)
          })
        }else{
          this.setData({
            contentList: []
          })
        }
      }
    }).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,this.data.currentTab)
          }

        }).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,this.data.currentTab)
          }

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

  // 分享
  _onTapShare(e){
    const { memberId, member } = wx.getStorageSync('_baseUserInfo')
    let tentacleInfo = {
      content: JSON.stringify(e.detail),
      contentId: e.detail.id,
      contentType: app.globalData.contants.SHARE_TYPE.DETAILS_OF_THE_CONTENT, //内容类型 
      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,this.data.currentTab)
    wx.stopPullDownRefresh();
   },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
    const { pageNum, pageSize, totalPages } = this.data
    if (pageNum < totalPages) {
      this.setData({
        pageNum: pageNum + 1,
      })
      this.getContentList(this.data.pageNum,this.data.currentTab)
    } 
  },

  /**
  * 用户点击右上角分享
  */
  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 = `pages/myShare/myShare`;
      if (memberId) {
        let m = Integer.digit(memberId, 10, 64);
        path = `pages/myShare/myShare?m=${m}`;
      }
      return {
        path: path
      }
    }

  }
})