// pages/companion-orders/companion-orders.js
const api = require('../../utils/api')

Page({
  data: {
    currentTab: 'all',
    orders: [],
    stats: {
      totalOrders: 0,
      completedOrders: 0,
      totalIncome: '0.00'
    },
    page: 1,
    pageSize: 20,
    hasMore: true,
    loading: false,
    // 评价回复弹窗
    showReplyModal: false,
    currentReview: null,
    replyContent: '',
    submittingReply: false
  },

  onLoad() {
    this.loadStats()
    this.loadOrders()
  },

  onPullDownRefresh() {
    this.setData({ page: 1, hasMore: true })
    Promise.all([this.loadStats(), this.loadOrders()]).finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreOrders()
    }
  },

  // 加载统计数据
  async loadStats() {
    try {
      const res = await api.companion.getOrderStats()
      if (res.success) {
        this.setData({
          stats: {
            totalOrders: res.data.total_orders || 0,
            completedOrders: res.data.completed_orders || 0,
            totalIncome: (res.data.total_income || 0).toFixed(2)
          }
        })
      }
    } catch (err) {
      console.error('加载统计数据失败:', err)
    }
  },

  // 加载订单列表
  async loadOrders() {
    this.setData({ loading: true })
    try {
      const params = {
        page: 1,
        pageSize: this.data.pageSize
      }
      if (this.data.currentTab !== 'all') {
        params.status = this.data.currentTab
      }

      const res = await api.companion.getOrders(params)
      if (res.success) {
        const orders = (res.data?.list || []).map(order => this.formatOrder(order))
        this.setData({
          orders,
          page: 1,
          hasMore: orders.length >= this.data.pageSize
        })
      }
    } catch (err) {
      console.error('加载订单失败:', err)
    } finally {
      this.setData({ loading: false })
    }
  },

  // 加载更多订单
  async loadMoreOrders() {
    this.setData({ loading: true })
    try {
      const params = {
        page: this.data.page + 1,
        pageSize: this.data.pageSize
      }
      if (this.data.currentTab !== 'all') {
        params.status = this.data.currentTab
      }

      const res = await api.companion.getOrders(params)
      if (res.success) {
        const newOrders = (res.data?.list || []).map(order => this.formatOrder(order))
        this.setData({
          orders: [...this.data.orders, ...newOrders],
          page: this.data.page + 1,
          hasMore: newOrders.length >= this.data.pageSize
        })
      }
    } catch (err) {
      console.error('加载更多订单失败:', err)
    } finally {
      this.setData({ loading: false })
    }
  },

  // 格式化订单数据
  formatOrder(order) {
    return {
      ...order,
      statusText: this.getStatusText(order.status),
      serviceTypeText: this.getServiceTypeText(order.service_type),
      createTimeText: this.formatTime(order.created_at)
    }
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'pending': '待服务',
      'in_progress': '进行中',
      'completed': '已完成',
      'cancelled': '已取消'
    }
    return statusMap[status] || status
  },

  // 获取服务类型文本
  getServiceTypeText(type) {
    const typeMap = {
      'chat': '文字聊天',
      'voice': '语音聊天',
      'video': '视频聊天'
    }
    return typeMap[type] || '聊天服务'
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return ''
    const date = new Date(timeStr)
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${month}/${day} ${hour}:${minute}`
  },

  // 切换标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    if (tab === this.data.currentTab) return
    
    this.setData({
      currentTab: tab,
      orders: [],
      page: 1,
      hasMore: true
    })
    this.loadOrders()
  },

  // 开始服务
  async startService(e) {
    const orderId = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '开始服务',
      content: '确定要开始服务吗？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...' })
          try {
            const result = await api.order.startService(orderId)
            if (result.success) {
              wx.showToast({ title: '服务已开始', icon: 'success' })
              this.loadOrders()
              this.loadStats()
            } else {
              wx.showToast({ title: result.message || '操作失败', icon: 'none' })
            }
          } catch (err) {
            wx.showToast({ title: '操作失败', icon: 'none' })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  // 结束服务
  async endService(e) {
    const orderId = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '结束服务',
      content: '确定要结束服务吗？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...' })
          try {
            const result = await api.order.endService(orderId)
            if (result.success) {
              wx.showToast({ title: '服务已结束', icon: 'success' })
              this.loadOrders()
              this.loadStats()
            } else {
              wx.showToast({ title: result.message || '操作失败', icon: 'none' })
            }
          } catch (err) {
            wx.showToast({ title: '操作失败', icon: 'none' })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  // 跳转到聊天
  goToChat(e) {
    const order = e.currentTarget.dataset.order
    wx.navigateTo({
      url: `/pages/companion-chat/companion-chat?orderId=${order.id}&userId=${order.user_id}`
    })
  },

  // 跳转到订单详情
  goToDetail(e) {
    const orderId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${orderId}`
    })
  },

  // 查看评价
  viewReview(e) {
    const order = e.currentTarget.dataset.order
    if (order.review) {
      this.setData({
        currentReview: order.review,
        showReplyModal: true,
        replyContent: ''
      })
    }
  },

  // 关闭回复弹窗
  closeReplyModal() {
    this.setData({
      showReplyModal: false,
      currentReview: null,
      replyContent: ''
    })
  },

  // 输入回复内容
  onReplyInput(e) {
    this.setData({ replyContent: e.detail.value })
  },

  // 提交回复
  async submitReply() {
    const { currentReview, replyContent } = this.data
    
    if (!replyContent.trim()) {
      wx.showToast({ title: '请输入回复内容', icon: 'none' })
      return
    }
    
    if (this.data.submittingReply) return
    
    this.setData({ submittingReply: true })
    wx.showLoading({ title: '提交中...' })
    
    try {
      const res = await api.companion.replyReview(currentReview.id, replyContent.trim())
      
      wx.hideLoading()
      this.setData({ submittingReply: false })
      
      if (res.success) {
        wx.showToast({ title: '回复成功', icon: 'success' })
        this.closeReplyModal()
        // 刷新订单列表
        this.loadOrders()
      } else {
        wx.showToast({ title: res.message || res.error || '回复失败', icon: 'none' })
      }
    } catch (err) {
      wx.hideLoading()
      this.setData({ submittingReply: false })
      console.error('回复评价失败', err)
      wx.showToast({ title: '回复失败', icon: 'none' })
    }
  }
})
