// pages/detail/detail.js
import api from '../../utils/api.js'
import util from '../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    TabIndex: 0,
    inputFocus: false,
    commentParams: {},
    commentList: [],
    commentCount: 0,
    detailInfo: {},
    sendParams: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (opt) {
    if (opt.id) {
      this.setData({
        commentParams: {
          page: 1,
          offset: 10,
          game_id: opt.id
        },
        sendParams: {
          content: '',
          game_id: opt.id
        }
      })
      this.getDetailInfo(opt.id)
      this.getDetailComment()
    }
  },
  routeComment: function (e) {
    util.routeTo(`/pages/detail/comment?id=${e.target.dataset.gmid}`)
  },
  FocusInput: function (e) {
    this.setData({
      inputFocus: true
    })
  },
  ChangeTab: function (e) {
    this.setData({
      TabIndex: e.target.dataset.index
    })
  },
  inputChange: function (e) {
    this.data.sendParams.content = e.detail.value
    this.setData({
      sendParams: this.data.sendParams
    })
  },
  sendComment: function () {
    api.addComment(this.data.sendParams).then(res => {
      if (res.code === 200) {
        this.data.commentParams.page = 1
        this.data.sendParams.content = ''
        this.setData({
          commentParams: this.data.commentParams,
          sendParams: this.data.sendParams
        })
        this.getDetailComment()
      }
    })
  },
  getDetailInfo: function (id) {
    api.getGameDetail({ game_id: id}).then(res => {
      if (res.code === 200) {
        this.setData({
          detailInfo: res.data
        })
      }
    })
  },
  getDetailComment: function () {
    api.getGmaeCommentList(this.data.commentParams).then(res => {
      if (res.code === 200) {
        res.data.list.forEach((item, ids) => {
          item.create_time = util.formatTime(item.create_time, 'yyyy/MM/dd hh:mm')
        })
        this.setData({
          commentList: this.data.commentParams.page === 1 ? res.data.list : this.data.commentList.concat(res.data.list),
          commentCount: res.data.count
        })
      }
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.commentCount <= this.data.commentList.length) {
      return false
    }
    this.data.commentParams.page = ++this.data.commentParams.page
    this.setData({
      commentParams: this.data.commentParams
    })
    this.getDetailComment()
  },

  openGame: function (e) {
    let id = e.currentTarget.dataset.id
    api.openGame({
      game_id: id
    }).then(res => {
      console.log(res)
    }, err => {
      console.log(err)
    })
  }
})