const app = getApp()
const db = wx.cloud.database()

Page({
  data: {
    name: '',
    keywords: ['咖啡馆', '餐厅', '公园', '商场', '电影院', 'KTV', '酒吧', '火锅', '烧烤', '其他'],
    keyword: '咖啡馆',
    meetTime: '',
    meetDate: '',
    meetTimeOnly: '',
    requirements: '',
    userInfo: {
      avatarUrl: '',
      nickName: ''
    }
  },

  onLoad() {
    // 生成默认聚会名称
    const randomNum = Math.floor(Math.random() * 9000) + 1000
    this.setData({
      name: `聚会-${randomNum}`
    })
  },

  onNameInput(e) {
    this.setData({
      name: e.detail.value
    })
  },

  onSelectKeyword(e) {
    this.setData({
      keyword: e.currentTarget.dataset.keyword
    })
  },

  onTimeInput(e) {
    this.setData({
      meetTime: e.detail.value
    })
  },

  onDateChange(e) {
    const date = e.detail.value
    this.setData({
      meetDate: date
    })
    this.updateMeetTime()
  },

  onTimeChange(e) {
    const time = e.detail.value
    this.setData({
      meetTimeOnly: time
    })
    this.updateMeetTime()
  },

  updateMeetTime() {
    const { meetDate, meetTimeOnly } = this.data
    if (meetDate && meetTimeOnly) {
      this.setData({
        meetTime: `${meetDate} ${meetTimeOnly}`
      })
    } else if (meetDate) {
      this.setData({
        meetTime: meetDate
      })
    }
  },

  onRequirementsInput(e) {
    this.setData({
      requirements: e.detail.value
    })
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.setData({
      'userInfo.avatarUrl': avatarUrl
    })
  },

  onNicknameChange(e) {
    const nickName = e.detail.value
    this.setData({
      'userInfo.nickName': nickName
    })
  },

  onSubmit() {
    const { name, keyword, meetTime, requirements, userInfo } = this.data

    if (!name.trim()) {
      wx.showToast({
        title: '请输入聚会名称',
        icon: 'none'
      })
      return
    }

    // 检查是否填写了昵称
    if (!userInfo.nickName || !userInfo.nickName.trim()) {
      wx.showToast({
        title: '请输入你的昵称',
        icon: 'none'
      })
      return
    }

    this.createRoom(name, keyword, meetTime, requirements)
  },

  onCancel() {
    wx.navigateBack()
  },

  createRoom(name, keywords, meetTime, requirements) {
    wx.showLoading({ title: '创建中...', mask: true })
    wx.cloud.callFunction({
      name: 'createRoom',
      data: {
        name,
        meetTime,
        keywords,
        requirements: requirements || '',
        userInfo: this.data.userInfo
      },
      success: res => {
        wx.hideLoading()
        if (res.result.success) {
          const roomId = res.result.roomId

          // 保存到本地存储
          let myRooms = wx.getStorageSync('myRooms') || []
          myRooms = myRooms.filter(item => item.roomId !== roomId)
          myRooms.unshift({
            roomId,
            name,
            meetTime,
            keywords
          })
          if (myRooms.length > 2) {
            myRooms = myRooms.slice(0, 2)
          }
          wx.setStorageSync('myRooms', myRooms)

          // 更新全局roomList
          let roomList = wx.getStorageSync('roomList') || []
          roomList = roomList.filter(item => item.roomId !== roomId)
          roomList.unshift({
            roomId,
            name,
            meetTime,
            keywords
          })
          if (roomList.length > 5) {
            roomList = roomList.slice(0, 5)
          }
          wx.setStorageSync('roomList', roomList)

          wx.redirectTo({
            url: `/pages/room/room?roomId=${roomId}&isCreator=true`
          })
        } else {
          wx.showToast({ title: res.result.msg || '创建失败', icon: 'none' })
        }
      },
      fail: err => {
        wx.hideLoading()
        console.error('云函数调用失败', err)
        wx.showToast({ title: '网络错误', icon: 'none' })
      }
    })
  }
})
