// pages/detail/index.js
import api from '../../utils/Api.js'
import Schedule from '../../utils/Schedule.js'
import Wx from '../../utils/Wx.js'
const {
  $Toast
} = require('../../iview/base/index');
const WxParse = require('../../wxParse/wxParse.js');
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    detail: {},

    comments: [],

    currentPage: 1,
    loading: true,
    hasMore: true,

    show_kf: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 检查用户是否登陆
    this.checkUserLogin()
    if (options.id) {
      this.setData({
        id: options.id
      })
    }
  },

  /**
 * 用户资料授权
 */
  checkUserLogin: function (callback) {
    if (app.globalData.userInfo == null) {
      api.me.info().then(res => {
        if (res.code == 0) {
          app.globalData.userInfo = res.data
        } else {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/auth/index',
            })
          }, 800)
        }
      })
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    let that = this
    wx.showNavigationBarLoading()
    wx.showLoading({
      title: '加载中...',
    })
    new Schedule().task(this.getDetailData).delay(1200).task(() => {
      wx.hideNavigationBarLoading()
      wx.hideLoading()
    }).task(this.getCommentData)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.setData({
      detail: {},
      comments: [],

      loading: true,
      hasMore: true,
      currentPage: 1
    })
    wx.showNavigationBarLoading()
    wx.showLoading({
      title: '加载中...',
    })
    new Schedule().task(this.getDetailData).delay(1200).task(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
      wx.hideLoading()
    }).task(this.getCommentData)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let that = this
    if (that.data.loading || !that.data.hasMore) {
      return;
    } else {
      let page = that.data.currentPage + 1
      new Schedule().task(() => {
        that.setData({
          loading: true,
          currentPage: page
        })
      }).delay(1000).task(that.getCommentData)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  getDetailData: function() {
    api.project.detail({
      id: this.data.id
    }).then(res => {
      if (!res.code) {
        this.setData({
          detail: res.data
        })
        var that = this;
        WxParse.wxParse('description', 'html', res.data.description, that, 5);
      }
    })
  },

  // 获取评论数据
  getCommentData: function() {
    // 商家详情没有评论
    if(this.data.detail.type=='2'){
      this.setData({
        hasMore: false,
        loading: false
      })
      return
    }
    const p = this.data.currentPage
    api.project.comments({
      pid: this.data.id,
      p,
    }).then(res => {
      if (res.code) {
        this.setData({
          hasMore: false,
          loading: false
        })
      } else {
        this.setData({
          comments: this.data.comments.concat(res.data),
          loading: false,
          hasMore: res.data && res.data.length > 0 ? true : false,
          currentPage: res.data && res.data.length > 0 ? p : (p - 1)
        })
        typeof callback == "function" && callback()
      }
    })
  },

  handleMap: function() {
    wx.openLocation({
      latitude: parseFloat(this.data.detail.latitude),
      longitude: parseFloat(this.data.detail.longitude),
    })
  },

  handleVip: function() {
    wx.navigateTo({
      url: '/pages/me/vip/index',
    })
  },

  handleHome: function() {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },

  handleCollect: function() {
    let that = this
    api.project.collect({
      pid: this.data.id
    }).then(res => {
      // 收藏改变
      if(res.code==0){
        let detail = that.data.detail
        detail.is_collect = !detail.is_collect
        if( res.collect == 'add' ){
          // 添加收藏
          detail.collect_num = parseInt(detail.collect_num) + 1
        }else{
          // 移除收藏
          detail.collect_num = parseInt(detail.collect_num) - 1
        }
        that.setData({
          detail: detail
        })
      }
      $Toast({
        content: res.msg,
        type: !res.code ? 'success' : 'error'
      });
    })
  },

  handleShare: function() {
    Wx.showShareMenu({
      withShareTicket: true,
    }).then(res => {
      console.log(res)
    })
  },

  // 立即报名
  enrollClick: function() {
    let status = this.data.detail.status
    // 0-立即报名；1-预约下次；2-已售罄
    if(status==0){
      wx.navigateTo({
        url: '/pages/detail/enroll/index?id=' + this.data.id,
      })
    } else if (status == 1){
      wx.navigateTo({
        url: '/pages/detail/appoint/index?id=' + this.data.id,
      })
    }else{
      $Toast({
        content: "活动已售罄",
        type: 'error'
      });
    }
  },

  // 商家详情 - 咨询客服下单
  kfClick: function() {
    this.setData({
      show_kf: true
    })
  },
  // 客户弹框按钮点击
  handleKfClose: function(event){
    let that = this
    if(event.type=='ok'){
      // 保存二维码
      wx.downloadFile({
        url: that.data.detail.kf_qrcode,
        success: function(res){
          console.log(res)
          if (res.statusCode === 200){
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function (res) {
                wx.showToast({
                  title: '图片保存成功',
                })
              },
              fail: function (res) {
                wx.showToast({
                  title: '图片保存失败',
                })
              }
            })
          }
        }
      })
    }
    // 关闭弹框
    that.setData({
      show_kf: false
    })
  }
})