// components/comment/Index.js
import api from '../../utils/Api.js'
const Util = require('../../utils/Util.js')

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    courseId: {
      type: Number
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    star: 0,
    content: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 点击star
     */
    tapStar(event) {
      this.setData({
        star: parseInt(event.detail.dataset.v)
      })
    },

    /**
     * 评论输入
     */
    bindContentChange(event) {
      this.setData({
        content: event.detail.value
      })
    },

    /**
     * 取消
     */
    _tapCancel(event) {
      let that = this
      that.triggerEvent('cancel', event)
    },

    /**
     * 确定
     */
    _tapConfirm(event) {
      let that = this
      let ret = that._verifyData()
      if (ret.error) {
        wx.showToast({
          title: ret.msg,
        })
        return
      }
      that._postCommentData(function (res) {
        that.triggerEvent('confirm', { ...event, data: res.data })
      })
    },

    /**
     * 验证数据
     */
    _verifyData() {
      let that = this
      if (that.data.star <= 0) {
        return { error: 1, msg: '请打分' }
      }
      if (!that.data.content || that.data.content.length <= 0) {
        return { error: 1, msg: '请输入评论' }
      }
      return { error: 0 }
    },

    /**
     * 提交评论数据
     */
    _postCommentData(callback) {
      let that = this
      let params = {
        order_id: that.data.courseId,
        grade: that.data.star,
        content: that.data.content
      }
      api.me.submitCommit(params).then(res => {
        if (res.code) {
          wx.showToast({
            title: res.msg,
          })
        } else {
          wx.showToast({
            title: res.msg,
          })
          typeof callback == "function" && callback(res)
        }
      })
    }
  }
})
