// pages/workbench/workbench.js
const api = require('../../utils/api')
const app = getApp()

Page({
  data: {
    userInfo: {},
    currentStatus: 'offline',
    statusText: '离线',
    showStatusModal: false,
    // 等级信息
    levelCode: 'junior',
    levelName: '初级',
    textPrice: 0.5,
    voicePrice: 1,
    stats: {
      todayOrders: 0,
      todayIncome: '0.00',
      totalOrders: 0,
      totalIncome: '0.00'
    },
    hallOrders: [],
    activeOrders: [],
    loading: false
  },

  onLoad() {
    this.setData({
      userInfo: app.globalData.userInfo || {}
    })
  },

  onShow() {
    this.loadCompanionStatus()
    this.loadWorkbenchData()
    this.loadHallOrders()
    this.loadActiveOrders()
  },

  // 加载陪聊师状态（包含等级信息）
  async loadCompanionStatus() {
    try {
      const res = await api.companion.getStatus()
      if (res.success && res.data) {
        const data = res.data
        this.setData({
          currentStatus: data.onlineStatus || 'offline',
          statusText: this.getStatusText(data.onlineStatus || 'offline'),
          // 等级信息
          levelCode: data.levelCode || 'junior',
          levelName: data.levelName || '初级',
          textPrice: data.textPrice || 0.5,
          voicePrice: data.voicePrice || 1
        })
      }
    } catch (err) {
      console.error('加载陪聊师状态失败:', err)
    }
  },

  // 加载工作台数据
  async loadWorkbenchData() {
    try {
      const res = await api.companion.getWorkbench()
      if (res.success) {
        const data = res.data || {}
        this.setData({
          stats: {
            todayOrders: data.todayOrders || data.todayStats?.orderCount || 0,
            todayIncome: (data.todayIncome || data.todayStats?.totalAmount || 0).toFixed(2),
            totalOrders: data.totalOrders || data.monthStats?.orderCount || 0,
            totalIncome: (data.totalIncome || data.monthStats?.totalAmount || 0).toFixed(2)
          }
        })
      }
    } catch (err) {
      console.error('加载工作台数据失败:', err)
    }
  },

  // 加载接单大厅订单
  async loadHallOrders() {
    try {
      const res = await api.order.getHall()
      if (res.success) {
        const orders = (res.data || []).map(order => ({
          ...order,
          createTimeText: this.formatTime(order.created_at),
          serviceTypeText: this.getServiceTypeText(order.service_type)
        }))
        this.setData({ hallOrders: orders })
      }
    } catch (err) {
      console.error('加载接单大厅失败:', err)
    }
  },

  // 加载进行中的订单
  async loadActiveOrders() {
    try {
      const res = await api.companion.getOrders({ status: 'in_progress' })
      if (res.success) {
        const orders = (res.data?.list || []).map(order => ({
          ...order,
          remainingTime: this.calculateRemainingTime(order)
        }))
        this.setData({ activeOrders: orders })
      }
    } catch (err) {
      console.error('加载进行中订单失败:', err)
    }
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'online': '在线接单',
      'busy': '忙碌中',
      'offline': '离线'
    }
    return statusMap[status] || '离线'
  },

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

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return ''
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now - date
    
    if (diff < 60000) return '刚刚'
    if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
    if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
    return `${date.getMonth() + 1}/${date.getDate()}`
  },

  // 计算剩余时间
  calculateRemainingTime(order) {
    if (!order.start_time || !order.duration) return '未知'
    const startTime = new Date(order.start_time).getTime()
    const endTime = startTime + order.duration * 60 * 1000
    const remaining = endTime - Date.now()
    
    if (remaining <= 0) return '已超时'
    const minutes = Math.floor(remaining / 60000)
    return `${minutes}分钟`
  },

  // 显示状态选择器
  showStatusPicker() {
    this.setData({ showStatusModal: true })
  },

  // 隐藏状态选择器
  hideStatusPicker() {
    this.setData({ showStatusModal: false })
  },

  // 切换状态
  async changeStatus(e) {
    const status = e.currentTarget.dataset.status
    if (status === this.data.currentStatus) {
      this.hideStatusPicker()
      return
    }

    wx.showLoading({ title: '切换中...' })
    try {
      const res = await api.companion.updateStatus(status)
      if (res.success) {
        this.setData({
          currentStatus: status,
          statusText: this.getStatusText(status)
        })
        wx.showToast({ title: '状态已更新', icon: 'success' })
      } else {
        wx.showToast({ title: res.message || '切换失败', icon: 'none' })
      }
    } catch (err) {
      wx.showToast({ title: '切换失败', icon: 'none' })
    } finally {
      wx.hideLoading()
      this.hideStatusPicker()
    }
  },

  // 刷新接单大厅
  refreshHall() {
    wx.showLoading({ title: '刷新中...' })
    this.loadHallOrders().finally(() => {
      wx.hideLoading()
      wx.showToast({ title: '已刷新', icon: 'success' })
    })
  },

  // 接受订单
  async acceptOrder(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.accept(orderId)
            if (result.success) {
              wx.showToast({ title: '接单成功', icon: 'success' })
              this.loadHallOrders()
              this.loadActiveOrders()
              this.loadWorkbenchData()
            } else {
              wx.showToast({ title: result.message || '接单失败', icon: 'none' })
            }
          } catch (err) {
            wx.showToast({ title: '接单失败', icon: 'none' })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  // 拒绝订单
  async rejectOrder(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.reject(orderId, '陪聊师暂时无法接单')
            if (result.success) {
              wx.showToast({ title: '已拒绝', icon: 'success' })
              this.loadHallOrders()
            } 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.loadActiveOrders()
              this.loadWorkbenchData()
            } 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}`
    })
  },

  // 跳转到订单列表
  goToOrders() {
    wx.navigateTo({ url: '/pages/companion-orders/companion-orders' })
  },

  // 跳转到客户管理
  goToCustomers() {
    wx.navigateTo({ url: '/pages/customer-management/customer-management' })
  },

  // 跳转到提现
  goToWithdraw() {
    wx.navigateTo({ url: '/pages/withdraw/withdraw' })
  },

  // 跳转到佣金明细
  goToCommission() {
    wx.navigateTo({ url: '/pages/commission/commission' })
  }
})
