// pages/square/square.js - 微信朋友圈风格
const app = getApp()
const api = require('../../utils/api')

// 模拟动态数据 - 将从API获取，这里仅作为备用
const MOCK_POSTS = []

Page({
  data: {
    statusBarHeight: 44,
    navBarHeight: 44,
    totalNavHeight: 88,
    posts: [],
    showCommentInput: false,
    commentText: '',
    currentCommentPostId: null,
    showCreateModal: false,
    newPostText: '',
    newPostImages: [],
    auditStatus: 0
  },

  onShow() {
    wx.hideTabBar({ animation: false })
    const app = getApp()
    this.setData({
      auditStatus: app.globalData.auditStatus
    })
  },

  onLoad() {
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 44
    const menuButton = wx.getMenuButtonBoundingClientRect()
    const navBarHeight = menuButton.height + (menuButton.top - statusBarHeight) * 2
    const totalNavHeight = statusBarHeight + navBarHeight
    
    this.setData({
      statusBarHeight,
      navBarHeight,
      totalNavHeight
    })
    
    // 从API加载动态列表
    this.loadPosts()
  },
  
  /**
   * 加载动态列表
   */
  async loadPosts() {
    try {
      const res = await api.post.getList({ page: 1, limit: 20 })
      
      if (res.success && res.data) {
        const posts = (res.data.list || res.data || []).map(post => ({
          id: post.id,
          userId: post.user_id,
          userName: post.user_name || '用户',
          userAvatar: post.user_avatar || '',
          content: post.content || '',
          images: post.images || [],
          time: post.created_at || '',
          likes: post.likes || [],
          comments: post.comments || [],
          isLiked: post.is_liked || false,
          likesText: (post.likes || []).join('，'),
          showActions: false
        }))
        
        this.setData({ posts })
      }
    } catch (err) {
      console.error('加载动态失败', err)
      // 如果API失败，使用空列表
      this.setData({ posts: [] })
    }
  },

  // 显示/隐藏操作面板
  onShowActions(e) {
    const postId = e.currentTarget.dataset.id
    const posts = this.data.posts.map(post => ({
      ...post,
      showActions: post.id === postId ? !post.showActions : false
    }))
    this.setData({ posts })
  },

  // 点击页面其他地方隐藏操作面板
  hideAllActions() {
    const posts = this.data.posts.map(post => ({
      ...post,
      showActions: false
    }))
    this.setData({ posts })
  },

  onLikePost(e) {
    const postId = e.currentTarget.dataset.id
    const posts = this.data.posts.map(post => {
      if (post.id === postId) {
        const isLiked = !post.isLiked
        let likes = [...post.likes]
        
        if (isLiked) {
          likes.push('我')
        } else {
          likes = likes.filter(l => l !== '我')
        }
        
        return {
          ...post,
          isLiked,
          likes,
          likesText: likes.join('，'),
          showActions: false
        }
      }
      return { ...post, showActions: false }
    })
    
    this.setData({ posts })
  },

  onCommentPost(e) {
    const postId = e.currentTarget.dataset.id
    // 先隐藏操作面板
    const posts = this.data.posts.map(post => ({
      ...post,
      showActions: false
    }))
    
    this.setData({
      posts,
      showCommentInput: true,
      currentCommentPostId: postId,
      commentText: ''
    })
  },

  hideCommentInput() {
    this.setData({
      showCommentInput: false,
      currentCommentPostId: null
    })
  },

  onCommentInput(e) {
    this.setData({ commentText: e.detail.value })
  },

  onSendComment() {
    const { commentText, currentCommentPostId, posts } = this.data
    
    if (!commentText.trim()) {
      wx.showToast({ title: '请输入评论内容', icon: 'none' })
      return
    }
    
    const newPosts = posts.map(post => {
      if (post.id === currentCommentPostId) {
        return {
          ...post,
          comments: [
            ...post.comments,
            { id: 'c' + Date.now(), user: '我', text: commentText }
          ]
        }
      }
      return post
    })
    
    this.setData({
      posts: newPosts,
      showCommentInput: false,
      commentText: '',
      currentCommentPostId: null
    })
    
    wx.showToast({ title: '评论成功', icon: 'success' })
  },

  onPreviewImage(e) {
    const { urls, current } = e.currentTarget.dataset
    wx.previewImage({
      urls,
      current
    })
  },

  onCreatePost() {
    this.setData({ showCreateModal: true })
  },

  hideCreateModal() {
    this.setData({
      showCreateModal: false,
      newPostText: '',
      newPostImages: []
    })
  },

  onNewPostInput(e) {
    this.setData({ newPostText: e.detail.value })
  },

  onAddImage() {
    wx.chooseMedia({
      count: 9 - this.data.newPostImages.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const newImages = res.tempFiles.map(f => f.tempFilePath)
        this.setData({
          newPostImages: [...this.data.newPostImages, ...newImages]
        })
      }
    })
  },

  onDeleteImage(e) {
    const index = e.currentTarget.dataset.index
    const images = this.data.newPostImages.filter((_, i) => i !== index)
    this.setData({ newPostImages: images })
  },

  async onSubmitPost() {
    const { newPostText, newPostImages } = this.data
    
    if (!newPostText.trim() && newPostImages.length === 0) {
      wx.showToast({ title: '请输入内容或添加图片', icon: 'none' })
      return
    }
    
    try {
      // 调用API发布动态
      const res = await api.post.create({
        content: newPostText,
        images: newPostImages
      })
      
      if (res.success) {
        this.setData({
          showCreateModal: false,
          newPostText: '',
          newPostImages: []
        })
        
        wx.showToast({ title: '发布成功', icon: 'success' })
        
        // 重新加载动态列表
        this.loadPosts()
      } else {
        wx.showToast({ title: res.message || '发布失败', icon: 'none' })
      }
    } catch (err) {
      console.error('发布动态失败', err)
      wx.showToast({ title: '发布失败', icon: 'none' })
    }
  },

  // 切换 Tab - 需要登录的页面检查登录状态
  switchTab(e) {
    const path = e.currentTarget.dataset.path
    const app = getApp()
    
    // 消息和我的页面需要登录
    if (path === '/pages/chat/chat' || path === '/pages/profile/profile') {
      if (!app.globalData.isLoggedIn) {
        wx.navigateTo({
          url: '/pages/login/login?redirect=' + encodeURIComponent(path)
        })
        return
      }
    }
    wx.switchTab({ url: path })
  },

  // 测试按钮
  onTest() {
    wx.showToast({
      title: '测试功能',
      icon: 'none'
    })
  }
})
