// pages/wodedashou/wodedashou.js
import request from '../../utils/request.js'
import { resolveAvatarUrl } from '../../utils/avatar.js'
import { openPrivateChat, buildDashouPeerId } from '../../utils/im-user.js'
const app = getApp()

Page({
  data: {
    // 统计
    yaoqingzongshu: 0,
    zaixianCount: 0,
    zhengchangCount: 0,
    fengjinCount: 0,

    // 列表
    dashouList: [],
    currentPage: 1,
    pageSize: 10,
    hasMore: true,
    isLoading: false,      // 首次加载或筛选时使用
    isLoadingMore: false,  // 上拉加载更多时使用

    // 筛选条件
    keyword: '',
    zhanghaozhuangtai: null,  // null=全部, 1=正常, 2=封禁
    zaixianzhuangtai: null,   // null=全部, 1=在线, 2=离线

    // 公共资源
    ossImageUrl: '',
    defaultAvatar: ''
  },

  onLoad() {
    this.initGlobal()
    this.jiazaiShuju(true)
    this.registerNotification()
  },

  registerNotification() {
    const comp = this.selectComponent('#global-notification')
    if (comp?.showNotification) {
      app.globalData.globalNotification = {
        show: d => comp.showNotification(d),
        hide: () => comp.hideNotification()
      }
    }
  },

  initGlobal() {
    const g = app.globalData
    this.setData({
      ossImageUrl: g.ossImageUrl || '',
      defaultAvatar: (g.ossImageUrl || '') + (g.morentouxiang || '')
    })
  },

  // 手动点击刷新按钮（重新加载第一页）
  shuaxinShuju() {
    if (this.data.isLoading) return
    this.setData({ currentPage: 1 })
    this.jiazaiShuju(true)
  },

  // 上拉触底加载更多（同时也作为按钮点击方法）
  shanglaJiazaiGengduo() {
    if (!this.data.hasMore || this.data.isLoadingMore || this.data.isLoading) return
    this.jiazaiShuju(false)
  },

  // 核心数据请求
  async jiazaiShuju(isFirstLoad) {
    if (isFirstLoad && this.data.isLoading) return
    if (!isFirstLoad && this.data.isLoadingMore) return

    this.setData({
      isLoading: isFirstLoad ? true : this.data.isLoading,
      isLoadingMore: isFirstLoad ? false : true
    })

    try {
      const res = await request({
        url: '/yonghu/gshqyqds',
        method: 'POST',
        data: {
          page: isFirstLoad ? 1 : this.data.currentPage,
          pageSize: this.data.pageSize,
          keyword: this.data.keyword,
          zhanghaozhuangtai: this.data.zhanghaozhuangtai,
          zaixianzhuangtai: this.data.zaixianzhuangtai
        }
      })

      if (res.data.code === 200) {
        this.handleResponse(res.data.data, isFirstLoad)
      } else {
        wx.showToast({ title: res.data.message || '加载失败', icon: 'none' })
        if (!isFirstLoad) {
          this.setData({ currentPage: this.data.currentPage - 1 })
        }
      }
    } catch (err) {
      wx.showToast({ title: '网络异常', icon: 'none' })
      if (!isFirstLoad) {
        this.setData({ currentPage: this.data.currentPage - 1 })
      }
    } finally {
      this.setData({
        isLoading: false,
        isLoadingMore: false
      })
    }
  },

  handleResponse(data, isFirstLoad) {
    const process = (list) => list.map(item => ({
      ...item,
      touxiangUrl: this.fullAvatar(item.touxiang)
    }))

    if (isFirstLoad) {
      this.setData({
        dashouList: process(data.dashouList || []),
        yaoqingzongshu: data.yaoqingzongshu || 0,
        zaixianCount: data.zaixianCount || 0,
        zhengchangCount: data.zhengchangCount || 0,
        fengjinCount: data.fengjinCount || 0,
        currentPage: data.hasMore ? 2 : 1,
        hasMore: data.hasMore
      })
    } else {
      this.setData({
        dashouList: [...this.data.dashouList, ...process(data.dashouList || [])],
        currentPage: this.data.currentPage + 1,
        hasMore: data.hasMore
      })
    }
  },

  fullAvatar(relative) {
    return resolveAvatarUrl(relative, app)
  },

  // 筛选输入
  onKeywordInput(e) {
    this.setData({ keyword: e.detail.value.trim() })
  },

  // picker 变更
  onZhanghaoChange(e) {
    const idx = parseInt(e.detail.value, 10)
    this.setData({ zhanghaozhuangtai: idx === 0 ? null : idx })
  },
  onZaixianChange(e) {
    const idx = parseInt(e.detail.value, 10)
    this.setData({ zaixianzhuangtai: idx === 0 ? null : idx })
  },

  // 点击筛选按钮
  applyFilter() {
    if (this.data.isLoading) return
    this.setData({ currentPage: 1 })
    this.jiazaiShuju(true)
  },

  // 联系打手（私聊）
  contactDashou(e) {
    const dashouUid = e.currentTarget.dataset.uid
    if (!dashouUid) return
    const item = this.data.dashouList.find(i => i.uid === dashouUid)
    openPrivateChat(this, {
      toUserId: buildDashouPeerId(dashouUid),
      toName: item?.nicheng || '打手',
      toAvatar: item?.touxiang || item?.touxiangUrl || '',
    })
  }
})