// 客户管理页面 - 陪聊师端
// 对接后端API

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

Page({
  data: {
    statusBarHeight: 44,
    navHeight: 92,
    loading: false,
    // 统计数据
    balanceInt: '0',
    balanceDec: '00',
    pendingAmount: '0.00',
    totalSettled: '0.00',
    newCustomers: 0,
    promotionOrders: 0,
    // 搜索
    searchQuery: '',
    // 客户列表
    customerList: [],
    page: 1,
    hasMore: true
  },

  onLoad() {
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 44
    const navHeight = statusBarHeight + 48
    
    this.setData({
      statusBarHeight,
      navHeight
    })
    
    this.loadData()
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadData().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreCustomers()
    }
  },

  /**
   * 加载数据
   */
  async loadData() {
    await Promise.all([
      this.loadStats(),
      this.loadCustomers()
    ])
  },

  /**
   * 加载统计数据
   */
  async loadStats() {
    try {
      const res = await api.companion.getOrderStats()
      
      if (res.success && res.data) {
        const balance = res.data.balance || 0
        const balanceStr = balance.toFixed(2)
        const [balanceInt, balanceDec] = balanceStr.split('.')
        
        this.setData({
          balanceInt: parseInt(balanceInt).toLocaleString(),
          balanceDec: balanceDec || '00',
          pendingAmount: (res.data.pending_amount || 0).toFixed(2),
          totalSettled: (res.data.total_settled || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 }),
          newCustomers: res.data.new_customers || 0,
          promotionOrders: res.data.promotion_orders || 0
        })
      }
    } catch (err) {
      console.log('获取统计数据失败', err)
    }
  },

  /**
   * 加载客户列表
   */
  async loadCustomers() {
    this.setData({ loading: true, page: 1 })
    
    try {
      const params = { page: 1, pageSize: 20 }
      
      if (this.data.searchQuery.trim()) {
        params.keyword = this.data.searchQuery.trim()
      }
      
      const res = await api.companion.getCustomers(params)
      
      if (res.success && res.data) {
        const customers = (res.data.list || res.data || []).map(c => this.transformCustomer(c))
        
        this.setData({
          customerList: customers,
          hasMore: customers.length >= 20,
          loading: false
        })
      } else {
        this.setData({ customerList: [], loading: false })
      }
    } catch (err) {
      console.error('加载客户列表失败', err)
      this.setData({ loading: false })
    }
  },

  /**
   * 加载更多客户
   */
  async loadMoreCustomers() {
    const nextPage = this.data.page + 1
    this.setData({ loading: true })
    
    try {
      const params = { page: nextPage, pageSize: 20 }
      
      if (this.data.searchQuery.trim()) {
        params.keyword = this.data.searchQuery.trim()
      }
      
      const res = await api.companion.getCustomers(params)
      
      if (res.success && res.data) {
        const newCustomers = (res.data.list || res.data || []).map(c => this.transformCustomer(c))
        
        this.setData({
          customerList: [...this.data.customerList, ...newCustomers],
          page: nextPage,
          hasMore: newCustomers.length >= 20,
          loading: false
        })
      } else {
        this.setData({ hasMore: false, loading: false })
      }
    } catch (err) {
      console.error('加载更多客户失败', err)
      this.setData({ loading: false })
    }
  },

  /**
   * 转换客户数据格式
   */
  transformCustomer(customer) {
    return {
      id: customer.id || customer.user_id,
      displayId: `ID${String(customer.id || customer.user_id).slice(-4)}`,
      nickname: customer.nickname || customer.name,
      avatar: customer.avatar,
      time: this.formatTime(customer.last_contact_at || customer.created_at),
      status: customer.status || 'success',
      orderCount: customer.order_count || 0,
      totalAmount: customer.total_amount || 0
    }
  },

  /**
   * 格式化时间
   */
  formatTime(dateStr) {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    return `${hour}:${minute}`
  },

  onBack() {
    wx.navigateBack()
  },

  onSearchInput(e) {
    this.setData({ searchQuery: e.detail.value })
  },

  /**
   * 搜索客户
   */
  onSearch() {
    this.loadCustomers()
  },

  /**
   * 点击客户
   */
  onCustomerTap(e) {
    const customer = e.currentTarget.dataset.customer || {}
    const id = e.currentTarget.dataset.id || customer.id
    
    wx.showActionSheet({
      itemList: ['查看详情', '发起聊天', '查看订单'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 查看详情
          wx.showModal({
            title: '客户详情',
            content: `客户ID: ${customer.displayId || id}\n订单数: ${customer.orderCount || 0}\n消费金额: ¥${customer.totalAmount || 0}`,
            showCancel: false
          })
        } else if (res.tapIndex === 1) {
          // 发起聊天
          wx.navigateTo({
            url: `/pages/companion-chat/companion-chat?customerId=${id}`
          })
        } else if (res.tapIndex === 2) {
          // 查看订单
          wx.navigateTo({
            url: `/pages/orders/orders?customerId=${id}`
          })
        }
      }
    })
  }
})
