// 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,
  },
 
  // 点击切换
  clickTab: function (e) {
    const { current } = e.target.dataset
    if (this.data.currentTab == current) {
      return false;
    } else {
      this.setData({
        currentTab: current,
      })
    }
    this.getContentList(current)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

   },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let time = Date.parse(new Date())
    if (member.premiumExpireTime && member.premiumExpireTime > time) {
      this.setData({
        plus: 1
      })
    } else {
      this.setData({
        plus: 0
      })
    }
    this.getCategoryList()
    this.getContentPermission()
    this.data.currentShareContent = null;
  },

  // 发布内容权限
  getContentPermission() {
    console.log(member)
    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(() => {
    })
  },

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

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

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

  // 获取发现内容
  getContentList(classifyId){
    wxService.post(`/merchant/contentMobileTerminal/getContentList?pageNum=${this.data.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: this.data.pageNum == 1 ? [...data.content] : [...this.data.contentList, ...data.content],
            totalPages: data.totalPages,
            totalElements: data.totalElements
          })
        }else{
          this.setData({
            contentList: []
          })
        }
      }
    }).finally(() => {
    })
  },

  // 点赞
  gotoLike(e){
    console.log(e.detail)
    let params = e.detail
     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.getContentList(this.data.currentTab)
          }

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

      }else{
        wxService.post(`/merchant/contentMobileTerminal/operationDelete`, {
          contentId: 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.getContentList(this.data.currentTab)
          }

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

  // 分享
  _onTapShare(e){

    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.tentacleId){
        this.data.currentShareContent.tentacleId = res.tentacleId;
        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;
        this.setData({
          showCardModal: true,
          cardTitle: e.detail.title,
          cardUrl: e.detail.url,
          pagePath: path
        });
      }
    })
  },
  
  /**
 * 页面相关事件处理函数--监听用户下拉动作
 */
  onPullDownRefresh: function () {
    this.setData({
      pageNum: 1,
    })
    this.getContentList(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.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, // 可以更换分享的图片
      }
    } 

    let tentacleInfo = {
      content: '内容列表',
      title: '内容列表',
      contentType: app.globalData.contants.SHARE_TYPE.CONTENTS_LIST,
      type: 3// 1:门店,2:员工(暂时不做),3:会员,4:第三方外部渠道,5:智能营销
    };
    wxService.getTentacleContent(tentacleInfo).then(res => {
      if (res && res.tentacleId) {
        this.data.currentShareContent.tentacleId = res.tentacleId;
        let tentacleId = Integer.digit(res.tentacleId, 10, 64);
        var path = `pages/myShare/myShare?t=${tentacleId}`;
        return {
          path : path
        }
      }
    });
  }
})