//index.js
//获取应用实例
import fetch from '../../utils/http'

const app = getApp()
const $api = require('../../config/api.js').$api

Page({
  onShow() {
    wx.setNavigationBarTitle({
      title: '添加评论'
    })
  },
  onLoad(e) {
    this.setData({
      Id: e.id,
      FormData: {
        ...this.data.FormData,
        mainId: e.id,
        customerId: app.globalData.UserInfo.customerId
      }
    })
  },
  data: {
    Id: '',
    UserInfo: app.globalData.UserInfo,
    SubmitOff: true,
    FormData: {
      customerId: '',
      commentType: 'activity',
      mainId: '',
      parentId: '',
      commentContent: '',
      imgArray: []
    }
  },
  AddImage() { // 添加图片
    let _self = this
    wx.chooseImage({
      count: 4 - _self.data.FormData.imgArray.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths || []
        let aArr = _self.data.FormData.imgArray.slice(0)
        let num = 0
        tempFilePaths.map((item, index) => {
          wx.uploadFile({
            url: $api.uploadImage.url,
            filePath: item,
            name: 'uploadFiles',
            success(resr) {
              num += 1
              aArr.push(JSON.parse(resr.data).data[0])
              if (num === tempFilePaths.length) {
                _self.setData({
                  FormData: {
                    ..._self.data.FormData,
                    imgArray: aArr
                  }
                })
              }
            }
          })
        })
      }
    })
  },
  FormInput(e) { // 输入form数据
    this.setData({
      FormData: {
        ...this.data.FormData,
        [e.target.dataset.name]: e.detail.value
      }
    })
  },
  DeleteItem(e) { // 删除img
    let aArr = this.data.FormData.imgArray.slice(0)
    aArr.splice(e.target.dataset.index, 1)
    this.setData({
      FormData: {
        ...this.data.FormData,
        imgArray: aArr
      }
    })
  },
  SubmitForm() { // 发布
    if (this.data.FormData.commentContent === '') {
      // Toast('评论内容不能为空！')
      wx.showToast({
        title: '评论内容不能为空！',
        icon: 'none',
      })
      return false
    }
    if (this.data.SubmitOff) {
      this.setData({
        SubmitOff: false
      })
      fetch({
        url: $api.comment.add.url,
        method: $api.comment.add.method,
        data: {
          ...this.data.FormData
        }
      }).then((res) => {
        if (res.code === 200) {
          wx.showToast({
            title: '添加评论成功！',
            icon: 'success',
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 500)
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none',
          })
          this.setData({
            SubmitOff: true
          })
        }
      })
    }
  }
})