/**
 * 代理商管理 Composable
 */

import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { AccountService } from '@/api/modules'
import type { Agent, AgentQueryParams, CreateAgentParams } from '@/types/api'
import { usePagination } from './usePagination'

export function useAgentManagement() {
  // 加载状态
  const loading = ref(false)

  // 表格数据
  const tableData = ref<Agent[]>([])

  // 代理商树数据
  const treeData = ref<Agent[]>([])

  // 分页
  const { pagination, setTotal, handleCurrentChange, handleSizeChange } = usePagination()

  const agentService = AccountService as unknown as {
    getAgents: (params?: AgentQueryParams) => Promise<any>
    getAgentTree: () => Promise<any>
    getAgent: (id: string | number) => Promise<any>
    createAgent: (data: CreateAgentParams) => Promise<any>
    updateAgent: (id: string | number, data: Partial<CreateAgentParams>) => Promise<any>
    toggleAgentStatus: (id: string | number, status: 0 | 1) => Promise<any>
    getSubAgents: (id: string | number) => Promise<any>
  }

  /**
   * 获取代理商列表
   * @param params 查询参数
   */
  const fetchAgentList = async (params?: AgentQueryParams) => {
    loading.value = true
    try {
      const res = await agentService.getAgents({
        current: pagination.current,
        size: pagination.size,
        ...params
      })

      tableData.value = res.data.items
      setTotal(res.data.total)
    } catch (error) {
      console.error('获取代理商列表失败:', error)
      console.log('获取代理商列表失败')
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取代理商树
   */
  const fetchAgentTree = async () => {
    loading.value = true
    try {
      const res = await agentService.getAgentTree()
      treeData.value = res.data
    } catch (error) {
      console.error('获取代理商树失败:', error)
      console.log('获取代理商树失败')
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取代理商详情
   * @param id 代理商ID
   */
  const fetchAgentDetail = async (id: string | number) => {
    loading.value = true
    try {
      const res = await agentService.getAgent(id)
      return res.data
    } catch (error) {
      console.error('获取代理商详情失败:', error)
      console.log('获取代理商详情失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 创建代理商
   * @param data 代理商数据
   */
  const createAgent = async (data: CreateAgentParams) => {
    loading.value = true
    try {
      await agentService.createAgent(data)
      ElMessage.success('创建成功')
      return true
    } catch (error) {
      console.error('创建失败:', error)
      console.log('创建失败')
      return false
    } finally {
      loading.value = false
    }
  }

  /**
   * 更新代理商
   * @param id 代理商ID
   * @param data 代理商数据
   */
  const updateAgent = async (id: string | number, data: Partial<CreateAgentParams>) => {
    loading.value = true
    try {
      await agentService.updateAgent(id, data)
      ElMessage.success('更新成功')
      return true
    } catch (error) {
      console.error('更新失败:', error)
      console.log('更新失败')
      return false
    } finally {
      loading.value = false
    }
  }

  /**
   * 切换代理商状态
   * @param id 代理商ID
   * @param status 状态
   */
  const toggleStatus = async (id: string | number, status: 0 | 1) => {
    loading.value = true
    try {
      await agentService.toggleAgentStatus(id, status)
      ElMessage.success('状态更新成功')
      return true
    } catch (error) {
      console.error('状态更新失败:', error)
      console.log('状态更新失败')
      return false
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取下级代理列表
   * @param id 代理商ID
   */
  const fetchSubAgents = async (id: string | number) => {
    loading.value = true
    try {
      const res = await agentService.getSubAgents(id)
      return res.data
    } catch (error) {
      console.error('获取下级代理失败:', error)
      console.log('获取下级代理失败')
      return []
    } finally {
      loading.value = false
    }
  }

  /**
   * 刷新列表
   */
  const refresh = () => {
    fetchAgentList()
  }

  return {
    loading,
    tableData,
    treeData,
    pagination,
    handleCurrentChange,
    handleSizeChange,
    fetchAgentList,
    fetchAgentTree,
    fetchAgentDetail,
    createAgent,
    updateAgent,
    toggleStatus,
    fetchSubAgents,
    refresh
  }
}
