import { defineStore } from 'pinia'
import { ref } from 'vue'
import type {
  Content,
  ContentQueryParams,
  ContentStatus,
  ContentType,
  ContentStatistics,
  ContentAuditStatus,
  ContentCategory
} from '../../types/content'

// 模拟数据 - 内容列表
const mockContents: Content[] = [
  {
    id: 1,
    title: '西藏自驾游攻略分享',
    content: '这次西藏之行非常难忘，沿途风景美不胜收...',
    contentType: 'article',
    authorId: 101,
    authorName: '旅行达人小王',
    publishTime: '2024-01-15 10:30:00',
    status: 'published',
    viewCount: 1250,
    likeCount: 89,
    commentCount: 45,
    shareCount: 23,
    auditStatus: 'approved',
    category: 'travel',
    tags: ['西藏', '自驾', '攻略'],
    images: ['/images/tibet1.jpg', '/images/tibet2.jpg'],
    isPublic: true,
    allowComments: true,
    allowSharing: true,
    editCount: 2
  },
  {
    id: 2,
    title: '认养小羊的快乐时光',
    content: '今天去农场看望了我认养的小羊，它长得真快...',
    contentType: 'post',
    authorId: 102,
    authorName: '爱心人士小李',
    publishTime: '2024-01-14 15:20:00',
    status: 'published',
    viewCount: 890,
    likeCount: 67,
    commentCount: 32,
    shareCount: 18,
    auditStatus: 'approved',
    category: 'animal',
    tags: ['认养', '小羊', '农场'],
    images: ['/images/sheep1.jpg'],
    isPublic: true,
    allowComments: true,
    allowSharing: true,
    editCount: 1
  },
  {
    id: 3,
    title: '周末电影聚会邀请',
    content: '本周末组织电影观看活动，欢迎喜欢电影的朋友参加...',
    contentType: 'activity',
    authorId: 103,
    authorName: '电影爱好者小张',
    publishTime: '2024-01-16 09:00:00',
    status: 'draft',
    viewCount: 120,
    likeCount: 15,
    commentCount: 8,
    shareCount: 5,
    auditStatus: 'pending',
    category: 'entertainment',
    tags: ['电影', '聚会', '周末'],
    isPublic: true,
    allowComments: true,
    allowSharing: true,
    editCount: 3
  }
]

// 模拟数据 - 内容统计
const mockContentStats: ContentStatistics = {
  totalContents: 1560,
  publishedContents: 1200,
  draftContents: 200,
  deletedContents: 160,
  totalViews: 125000,
  totalLikes: 8900,
  totalComments: 4500,
  totalShares: 2300,
  averageEngagementRate: 12.5,
  contentTypeDistribution: {
    article: 600,
    post: 800,
    activity: 120,
    comment: 40,
    review: 200
  },
  categoryDistribution: {
    travel: 450,
    animal: 380,
    entertainment: 280,
    food: 200,
    sports: 150,
    study: 100,
    other: 0
  },
  dailyGrowth: 25,
  topContents: mockContents.slice(0, 3),
  authorDistribution: {
    totalAuthors: 350,
    activeAuthors: 280,
    newAuthorsThisMonth: 45,
    topAuthors: [
      { authorId: 101, authorName: '旅行达人小王', contentCount: 45, totalViews: 12000 },
      { authorId: 102, authorName: '爱心人士小李', contentCount: 38, totalViews: 8900 },
      { authorId: 103, authorName: '电影爱好者小张', contentCount: 32, totalViews: 7600 }
    ]
  }
}

export const useContentStore = defineStore('content', () => {
  // 状态
  const contents = ref<Content[]>(mockContents)
  const currentContent = ref<Content | null>(null)
  const contentStats = ref<ContentStatistics>(mockContentStats)
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 获取内容列表
  const fetchContents = async (params: ContentQueryParams) => {
    loading.value = true
    error.value = null
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))
      
      // 简单的过滤和分页逻辑
      let filteredContents = mockContents
      
      if (params.keyword) {
        filteredContents = filteredContents.filter(content => 
          content.title.includes(params.keyword!) || 
          content.content.includes(params.keyword!)
        )
      }
      
      if (params.status) {
        filteredContents = filteredContents.filter(content => content.status === params.status)
      }
      
      if (params.contentType) {
        filteredContents = filteredContents.filter(content => content.contentType === params.contentType)
      }
      
      if (params.auditStatus) {
        filteredContents = filteredContents.filter(content => content.auditStatus === params.auditStatus)
      }
      
      if (params.authorId) {
        filteredContents = filteredContents.filter(content => content.authorId === params.authorId)
      }
      
      if (params.startTime && params.endTime) {
        filteredContents = filteredContents.filter(content => 
          content.publishTime >= params.startTime! && 
          content.publishTime <= params.endTime!
        )
      }
      
      // 分页
      const start = (params.page - 1) * params.pageSize
      const paginatedContents = filteredContents.slice(start, start + params.pageSize)
      
      contents.value = paginatedContents
      
      return {
        contents: paginatedContents,
        total: filteredContents.length,
        page: params.page,
        pageSize: params.pageSize
      }
    } catch (err) {
      error.value = '获取内容列表失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取内容详情
  const fetchContentDetail = async (id: number) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 300))
      
      const content = mockContents.find((c: Content) => c.id === id)
      if (!content) {
        throw new Error('内容不存在')
      }
      
      currentContent.value = content
      return content
    } catch (err) {
      error.value = '获取内容详情失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 审核内容
  const auditContent = async (id: number, auditStatus: 'approved' | 'rejected', remark?: string) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      
      const contentIndex = mockContents.findIndex((c: Content) => c.id === id)
      if (contentIndex === -1) {
        throw new Error('内容不存在')
      }
      
      mockContents[contentIndex].auditStatus = auditStatus
      if (remark) {
        mockContents[contentIndex].auditRemark = remark
      }
      mockContents[contentIndex].auditTime = new Date().toISOString()
      
      // 更新本地状态
      if (currentContent.value?.id === id) {
        currentContent.value.auditStatus = auditStatus
        currentContent.value.auditRemark = remark
        currentContent.value.auditTime = new Date().toISOString()
      }
      
      return mockContents[contentIndex]
    } catch (err) {
      error.value = '审核内容失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 更新内容状态
  const updateContentStatus = async (id: number, status: 'published' | 'draft' | 'deleted') => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 300))
      
      const contentIndex = mockContents.findIndex((c: Content) => c.id === id)
      if (contentIndex === -1) {
        throw new Error('内容不存在')
      }
      
      mockContents[contentIndex].status = status
      
      // 更新本地状态
      if (currentContent.value?.id === id) {
        currentContent.value.status = status
      }
      
      return mockContents[contentIndex]
    } catch (err) {
      error.value = '更新内容状态失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 删除内容
  const deleteContent = async (id: number) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 300))
      
      const contentIndex = mockContents.findIndex((c: Content) => c.id === id)
      if (contentIndex === -1) {
        throw new Error('内容不存在')
      }
      
      mockContents.splice(contentIndex, 1)
      
      // 清除当前内容
      if (currentContent.value?.id === id) {
        currentContent.value = null
      }
      
      return true
    } catch (err) {
      error.value = '删除内容失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取内容统计
  const fetchContentStatistics = async () => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 800))
      
      // 模拟实时数据更新
      const updatedStats = {
        ...mockContentStats,
        totalContents: mockContents.length,
        publishedContents: mockContents.filter(c => c.status === 'published').length,
        draftContents: mockContents.filter(c => c.status === 'draft').length,
        totalViews: mockContents.reduce((sum, c) => sum + c.viewCount, 0),
        totalLikes: mockContents.reduce((sum, c) => sum + c.likeCount, 0),
        totalComments: mockContents.reduce((sum, c) => sum + c.commentCount, 0),
        totalShares: mockContents.reduce((sum, c) => sum + c.shareCount, 0)
      }
      
      contentStats.value = updatedStats
      return updatedStats
    } catch (err) {
      error.value = '获取内容统计失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 搜索内容
  const searchContents = async (keyword: string, filters?: Partial<ContentQueryParams>) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 400))
      
      let results = mockContents.filter(content => 
        content.title.includes(keyword) || 
        content.content.includes(keyword) ||
        content.tags?.some((tag: string) => tag.includes(keyword))
      )
      
      if (filters?.status) {
        results = results.filter(content => content.status === filters.status)
      }
      
      if (filters?.contentType) {
        results = results.filter(content => content.contentType === filters.contentType)
      }
      
      return results
    } catch (err) {
      error.value = '搜索内容失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 批量操作
  const batchOperation = async (ids: number[], operation: 'publish' | 'draft' | 'delete' | 'approve' | 'reject') => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 600))
      
      const results = []
      
      for (const id of ids) {
        const contentIndex = mockContents.findIndex(c => c.id === id)
        if (contentIndex !== -1) {
          switch (operation) {
            case 'publish':
              mockContents[contentIndex].status = 'published'
              break
            case 'draft':
              mockContents[contentIndex].status = 'draft'
              break
            case 'delete':
              mockContents.splice(contentIndex, 1)
              break
            case 'approve':
              mockContents[contentIndex].auditStatus = 'approved'
              break
            case 'reject':
              mockContents[contentIndex].auditStatus = 'rejected'
              break
          }
          results.push({ id, success: true })
        } else {
          results.push({ id, success: false, error: '内容不存在' })
        }
      }
      
      return results
    } catch (err) {
      error.value = '批量操作失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 重置错误
  const clearError = () => {
    error.value = null
  }

  return {
    // 状态
    contents,
    currentContent,
    contentStats,
    loading,
    error,
    
    // 操作
    fetchContents,
    fetchContentDetail,
    auditContent,
    updateContentStatus,
    deleteContent,
    fetchContentStatistics,
    searchContents,
    batchOperation,
    clearError
  }
})