import { defineStore } from 'pinia'
import { ref } from 'vue'
import { post, get, postForm } from '@/utils/request'
import request from '@/utils/request'

// ── 类型定义 ──────────────────────────────────────────────

export interface AgentInfo {
  id: string
  email: string
  username: string
  nickName?: string
  agentName?: string
  realName?: string
  superPartner?: string
  todayNewUserCount: number
  todayOrderUserCount: number
  todayAward: string
}

export interface RewardRecord {
  username: string
  memberId: string
  num: string
}

export interface RewardSetItem {
  id: string
  memberId?: string
  superPartner?: string
  rate: number | string
  followRate?: number | string
}

export interface MemberItem {
  id: string
  memberId?: string
  username?: string
  email?: string
  createTime?: string
  superPartner?: string
}

// ── 工具函数 ──────────────────────────────────────────────

/** 截断到4位小数（不四舍五入）- 与 App 端行为一致 */
export function truncate4(val: string | number | null | undefined): string {
  const s = String(val ?? '0')
  const n = parseFloat(s)
  if (isNaN(n)) return '0.0000'
  const fixed = n.toFixed(10)
  const dot = fixed.indexOf('.')
  const end = dot + 5 // dot + 4 位小数
  return fixed.slice(0, end)
}

/** 邮箱脱敏：a**@domain.com */
export function maskEmail(email: string): string {
  if (!email) return '--'
  const at = email.indexOf('@')
  if (at <= 1) return email
  return `${email[0]}**${email.slice(at)}`
}

/** 今日零时时间字符串 */
function todayStartStr(): string {
  const now = new Date()
  const y = now.getFullYear()
  const m = String(now.getMonth() + 1).padStart(2, '0')
  const d = String(now.getDate()).padStart(2, '0')
  return `${y}-${m}-${d} 00:00:00`
}

// ── Store ─────────────────────────────────────────────────

export const useBrokerStore = defineStore('broker', () => {
  // 经纪商基本信息
  const info = ref<AgentInfo | null>(null)
  const infoLoading = ref(false)
  const infoError = ref<string | null>(null)

  // 今日返佣列表
  const todayRewards = ref<RewardRecord[]>([])
  const rewardsLoading = ref(false)

  // 邀请列表（返佣比例设置）
  const rewardSetList = ref<RewardSetItem[]>([])
  const setListLoading = ref(false)
  const setListPage = ref(1)
  const setListHasMore = ref(true)

  // 团队详情
  const teamAsset = ref<string>('0')
  const teamLoading = ref(false)

  // 返佣历史记录（全量分页）
  const rewardHistory = ref<RewardRecord[]>([])
  const historyLoading = ref(false)
  const historyPage = ref(1)
  const historyHasMore = ref(true)

  // 编辑弹窗
  const editTarget = ref<RewardSetItem | null>(null)
  const editLoading = ref(false)
  const editError = ref<string | null>(null)

  async function fetchInfo() {
    infoLoading.value = true
    infoError.value = null
    try {
      const data = await post<AgentInfo>('/uc/agent/info', {})
      info.value = data
    } catch (e) {
      infoError.value = e instanceof Error ? e.message : '获取经纪商信息失败'
      throw e
    } finally {
      infoLoading.value = false
    }
  }

  async function fetchTodayRewards() {
    rewardsLoading.value = true
    try {
      // 后端使用 query params（与 App 端行为一致）
      const data = await request.post<never, unknown>('/uc/agent/reward', undefined, {
        params: { pageNo: 1, pageSize: 50, startTime: todayStartStr() },
      }) as { content?: RewardRecord[] } | RewardRecord[] | null
      if (Array.isArray(data)) {
        todayRewards.value = data
      } else if (data && typeof data === 'object' && 'content' in data && Array.isArray(data.content)) {
        todayRewards.value = data.content
      } else {
        todayRewards.value = []
      }
    } catch {
      todayRewards.value = []
    } finally {
      rewardsLoading.value = false
    }
  }

  async function fetchRewardSetList(refresh = false) {
    if (refresh) {
      setListPage.value = 1
      rewardSetList.value = []
      setListHasMore.value = true
    }
    if (!setListHasMore.value || setListLoading.value) return
    setListLoading.value = true
    try {
      const data = await post<RewardSetItem[]>('/uc/agent/reward/set/list', {})
      const list = Array.isArray(data) ? data : []
      rewardSetList.value = refresh ? list : [...rewardSetList.value, ...list]
      setListHasMore.value = false // 接口一次返回全部
    } catch {
      // 静默处理
    } finally {
      setListLoading.value = false
    }
  }

  async function fetchTeamStat(endDate?: string) {
    teamLoading.value = true
    try {
      const params: Record<string, string> = {}
      if (endDate) params['endDate'] = endDate
      const data = await get<{ totalBalance?: string }>('/uc/agent/stat', params)
      teamAsset.value = data?.totalBalance ?? '0'
    } catch {
      teamAsset.value = '0'
    } finally {
      teamLoading.value = false
    }
  }

  async function fetchRewardHistory(refresh = false) {
    if (refresh) {
      historyPage.value = 1
      rewardHistory.value = []
      historyHasMore.value = true
    }
    if (!historyHasMore.value || historyLoading.value) return
    historyLoading.value = true
    const PAGE_SIZE = 20
    try {
      const data = await request.post<never, unknown>('/uc/agent/reward', undefined, {
        params: { pageNo: historyPage.value, pageSize: PAGE_SIZE },
      }) as { content?: RewardRecord[] } | RewardRecord[] | null
      let list: RewardRecord[] = []
      if (Array.isArray(data)) {
        list = data
      } else if (data && typeof data === 'object' && 'content' in data && Array.isArray(data.content)) {
        list = data.content
      }
      rewardHistory.value = refresh ? list : [...rewardHistory.value, ...list]
      if (list.length < PAGE_SIZE) {
        historyHasMore.value = false
      } else {
        historyPage.value++
      }
    } catch {
      // 静默
    } finally {
      historyLoading.value = false
    }
  }

  function openEdit(item: RewardSetItem) {
    editTarget.value = { ...item }
    editError.value = null
  }

  function closeEdit() {
    editTarget.value = null
    editError.value = null
  }

  async function submitEditRate(id: string, rate: number, followRate?: number) {
    editLoading.value = true
    editError.value = null
    try {
      const body: Record<string, string> = {
        id,
        rate: String(rate),
      }
      if (followRate !== undefined) body['followRate'] = String(followRate)
      await postForm('/uc/agent/reward/set', body)
      // 更新本地列表
      const idx = rewardSetList.value.findIndex(r => r.id === id)
      if (idx !== -1) {
        rewardSetList.value[idx] = {
          ...rewardSetList.value[idx],
          rate,
          followRate,
        }
      }
      closeEdit()
    } catch (e) {
      editError.value = e instanceof Error ? e.message : '设置失败'
      throw e
    } finally {
      editLoading.value = false
    }
  }

  async function loadAll() {
    await Promise.all([
      fetchInfo(),
      fetchTodayRewards(),
      fetchRewardSetList(true),
      fetchTeamStat(),
    ])
  }

  return {
    info, infoLoading, infoError,
    todayRewards, rewardsLoading,
    rewardSetList, setListLoading, setListHasMore,
    teamAsset, teamLoading,
    rewardHistory, historyLoading, historyHasMore,
    editTarget, editLoading, editError,
    fetchInfo, fetchTodayRewards, fetchRewardSetList,
    fetchTeamStat, fetchRewardHistory,
    openEdit, closeEdit, submitEditRate,
    loadAll,
  }
})
