import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Activity, ActivityQueryParams, ActivityStatus, ActivityType, ActivityStatistics } from '../../types/activity'

interface ActivityState {
  activities: Activity[]
  currentActivity: Activity | null
  loading: boolean
  totalCount: number
  queryParams: ActivityQueryParams
}

export const useActivityStore = defineStore('activity', () => {
  // 状态
  const activities = ref<Activity[]>([])
  const currentActivity = ref<Activity | null>(null)
  const loading = ref(false)
  const totalCount = ref(0)
  const queryParams = ref<ActivityQueryParams>({
    page: 1,
    pageSize: 10,
    keyword: '',
    status: undefined,
    activityType: undefined,
    organizerId: undefined,
    startDate: '',
    endDate: ''
  })

  // 获取活动列表
  const fetchActivities = async (params?: ActivityQueryParams) => {
    loading.value = true
    try {
      // 模拟数据
      const mockActivities: Activity[] = [
        {
          id: 1,
          title: '周末郊游',
          activityType: 'travel',
          description: '周末一起去郊游，享受大自然',
          organizerId: 101,
          organizerName: '张组织者',
          location: '北京市朝阳公园',
          startTime: '2024-01-20 09:00:00',
          endTime: '2024-01-20 17:00:00',
          maxParticipants: 20,
          currentParticipants: 15,
          status: 'active',
          price: 50.00,
          createTime: '2024-01-15 14:30:00',
          images: ['/images/activity1.jpg'],
          tags: ['郊游', '户外', '社交']
        },
        {
          id: 2,
          title: '电影之夜',
          activityType: 'movie',
          description: '一起观看最新上映的电影',
          organizerId: 102,
          organizerName: '李组织者',
          location: '北京市万达影城',
          startTime: '2024-01-22 19:00:00',
          endTime: '2024-01-22 22:00:00',
          maxParticipants: 10,
          currentParticipants: 8,
          status: 'active',
          price: 35.00,
          createTime: '2024-01-16 10:15:00',
          images: ['/images/activity2.jpg'],
          tags: ['电影', '娱乐', '社交']
        }
      ]
      
      activities.value = mockActivities
      totalCount.value = mockActivities.length
      
      if (params) {
        queryParams.value = { ...queryParams.value, ...params }
      }
    } catch (error) {
      console.error('获取活动列表失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取活动详情
  const fetchActivityDetail = async (activityId: number) => {
    loading.value = true
    try {
      // 模拟数据
      const mockActivity: Activity = {
        id: activityId,
        title: `活动${activityId}`,
        activityType: 'travel',
        description: '活动描述',
        organizerId: 100 + activityId,
        organizerName: '组织者',
        location: '地点',
        startTime: '2024-01-20 10:00:00',
        endTime: '2024-01-20 18:00:00',
        maxParticipants: 20,
        currentParticipants: 10,
        status: 'active',
        price: 50.00,
        createTime: '2024-01-15 14:30:00',
        images: ['/images/activity.jpg'],
        tags: ['标签1', '标签2']
      }
      
      currentActivity.value = mockActivity
      return mockActivity
    } catch (error) {
      console.error('获取活动详情失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 更新活动状态
  const updateActivityStatus = async (activityId: number, status: ActivityStatus) => {
    try {
      // 模拟状态更新
      const activity = activities.value.find(a => a.id === activityId)
      if (activity) {
        activity.status = status
      }
      
      if (currentActivity.value && currentActivity.value.id === activityId) {
        currentActivity.value.status = status
      }
      
      return true
    } catch (error) {
      console.error('更新活动状态失败:', error)
      throw error
    }
  }

  // 审核活动
  const auditActivity = async (activityId: number, auditStatus: ActivityStatus, auditRemark?: string) => {
    try {
      // 模拟审核操作
      const activity = activities.value.find(a => a.id === activityId)
      if (activity) {
        activity.status = auditStatus
        activity.auditRemark = auditRemark
        activity.auditTime = new Date().toISOString()
      }
      
      if (currentActivity.value && currentActivity.value.id === activityId) {
        currentActivity.value.status = auditStatus
        currentActivity.value.auditRemark = auditRemark
        currentActivity.value.auditTime = new Date().toISOString()
      }
      
      return true
    } catch (error) {
      console.error('审核活动失败:', error)
      throw error
    }
  }

  // 搜索活动
  const searchActivities = async (keyword: string) => {
    queryParams.value.keyword = keyword
    return fetchActivities(queryParams.value)
  }

  // 重置查询参数
  const resetQueryParams = () => {
    queryParams.value = {
      page: 1,
      pageSize: 10,
      keyword: '',
      status: undefined,
      activityType: undefined,
      organizerId: undefined,
      startDate: '',
      endDate: ''
    }
  }

  // 获取活动统计
  const getActivityStatistics = async () => {
    try {
      // 模拟统计数据
      return {
        totalActivities: 89,
        activeActivities: 67,
        completedActivities: 22,
        cancelledActivities: 5,
        totalParticipants: 456,
        totalRevenue: 12800.50,
        averageParticipation: 5.12,
        activityTypeDistribution: {
          travel: 25,
          movie: 18,
          dinner: 15,
          game: 12,
          other: 19
        },
        statusDistribution: {
          pending: 8,
          active: 67,
          completed: 22,
          cancelled: 5
        },
        popularActivities: activities.value.slice(0, 5)
      }
    } catch (error) {
      console.error('获取活动统计失败:', error)
      throw error
    }
  }

  // 导出活动数据
  const exportActivities = async () => {
    try {
      // 模拟导出功能
      const csvContent = activities.value.map(activity => 
        `${activity.id},${activity.title},${activity.organizerName},${activity.activityType},${activity.status},${activity.currentParticipants}`
      ).join('\n')
      
      return csvContent
    } catch (error) {
      console.error('导出活动数据失败:', error)
      throw error
    }
  }

  return {
    activities,
    currentActivity,
    loading,
    totalCount,
    queryParams,
    fetchActivities,
    fetchActivityDetail,
    updateActivityStatus,
    auditActivity,
    searchActivities,
    resetQueryParams,
    getActivityStatistics,
    exportActivities
  }
})