/**
 * 牛只交易状态管理模块
 * 管理交易相关的数据和状态
 */

import { defineStore } from 'pinia'
import { tradingApi } from '@/common/api/trading'

export const useTradingStore = defineStore('trading', {
  state: () => ({
    // 交易列表
    tradeList: [],
    
    // 当前交易详情
    currentTrade: null,
    
    // 我的发布列表
    myPublishList: [],
    
    // 我的购买列表
    myPurchaseList: [],
    
    // 交易订单列表
    orderList: [],
    
    // 当前订单详情
    currentOrder: null,
    
    // 价格行情数据
    priceData: [],
    
    // 市场统计数据
    marketStats: {
      totalTrades: 0,
      todayTrades: 0,
      averagePrice: 0,
      priceChange: 0,
      activeTraders: 0
    },
    
    // 交易分类
    categories: [],
    
    // 地区列表
    regions: [],
    
    // 加载状态
    loading: {
      tradeList: false,
      myPublishList: false,
      myPurchaseList: false,
      orderList: false,
      priceData: false,
      marketStats: false
    },
    
    // 分页信息
    pagination: {
      tradeList: { page: 1, size: 20, total: 0 },
      myPublishList: { page: 1, size: 20, total: 0 },
      myPurchaseList: { page: 1, size: 20, total: 0 },
      orderList: { page: 1, size: 20, total: 0 }
    },
    
    // 筛选条件
    filters: {
      category: '',
      region: '',
      priceRange: [],
      weightRange: [],
      ageRange: [],
      gender: '',
      breed: '',
      sortBy: 'createTime',
      sortOrder: 'desc'
    },
    
    // 搜索关键词
    searchKeyword: ''
  }),

  getters: {
    // 获取在售交易列表
    availableTrades: (state) => {
      return state.tradeList.filter(trade => trade.status === 'available')
    },
    
    // 获取已售出交易列表
    soldTrades: (state) => {
      return state.tradeList.filter(trade => trade.status === 'sold')
    },
    
    // 获取我的在售发布
    myAvailablePublish: (state) => {
      return state.myPublishList.filter(trade => trade.status === 'available')
    },
    
    // 获取我的已售发布
    mySoldPublish: (state) => {
      return state.myPublishList.filter(trade => trade.status === 'sold')
    },
    
    // 获取待付款订单
    pendingPaymentOrders: (state) => {
      return state.orderList.filter(order => order.status === 'pending_payment')
    },
    
    // 获取待发货订单
    pendingShipmentOrders: (state) => {
      return state.orderList.filter(order => order.status === 'pending_shipment')
    },
    
    // 获取已完成订单
    completedOrders: (state) => {
      return state.orderList.filter(order => order.status === 'completed')
    },
    
    // 获取今日价格变化
    todayPriceChange: (state) => {
      if (state.priceData.length < 2) return 0
      
      const today = state.priceData[state.priceData.length - 1]
      const yesterday = state.priceData[state.priceData.length - 2]
      
      return ((today.price - yesterday.price) / yesterday.price * 100).toFixed(2)
    },
    
    // 获取价格趋势
    priceTrend: (state) => {
      if (state.priceData.length < 2) return 'stable'
      
      const recent = state.priceData.slice(-5)
      const trend = recent.reduce((acc, curr, index) => {
        if (index === 0) return acc
        return acc + (curr.price > recent[index - 1].price ? 1 : -1)
      }, 0)
      
      if (trend > 2) return 'rising'
      if (trend < -2) return 'falling'
      return 'stable'
    },
    
    // 获取热门品种
    popularBreeds: (state) => {
      const breedCount = {}
      state.tradeList.forEach(trade => {
        breedCount[trade.breed] = (breedCount[trade.breed] || 0) + 1
      })
      
      return Object.entries(breedCount)
        .sort(([,a], [,b]) => b - a)
        .slice(0, 5)
        .map(([breed, count]) => ({ breed, count }))
    },
    
    // 获取活跃地区
    activeRegions: (state) => {
      const regionCount = {}
      state.tradeList.forEach(trade => {
        regionCount[trade.region] = (regionCount[trade.region] || 0) + 1
      })
      
      return Object.entries(regionCount)
        .sort(([,a], [,b]) => b - a)
        .slice(0, 10)
        .map(([region, count]) => ({ region, count }))
    }
  },

  actions: {
    /**
     * 获取交易列表
     * @param {Object} params 查询参数
     */
    async fetchTradeList(params = {}) {
      this.loading.tradeList = true
      
      try {
        const response = await tradingApi.getTradeList({
          page: this.pagination.tradeList.page,
          size: this.pagination.tradeList.size,
          keyword: this.searchKeyword,
          ...this.filters,
          ...params
        })
        
        const { data, total } = response.data
        
        if (params.page === 1) {
          this.tradeList = data
        } else {
          this.tradeList.push(...data)
        }
        
        this.pagination.tradeList.total = total
        
        return response
      } catch (error) {
        console.error('获取交易列表失败:', error)
        throw error
      } finally {
        this.loading.tradeList = false
      }
    },

    /**
     * 获取交易详情
     * @param {number} id 交易ID
     */
    async fetchTradeDetail(id) {
      try {
        const response = await tradingApi.getTradeDetail(id)
        this.currentTrade = response.data
        
        return response
      } catch (error) {
        console.error('获取交易详情失败:', error)
        throw error
      }
    },

    /**
     * 获取我的发布列表
     * @param {Object} params 查询参数
     */
    async fetchMyPublishList(params = {}) {
      this.loading.myPublishList = true
      
      try {
        const response = await tradingApi.getMyPublishList({
          page: this.pagination.myPublishList.page,
          size: this.pagination.myPublishList.size,
          ...params
        })
        
        const { data, total } = response.data
        
        if (params.page === 1) {
          this.myPublishList = data
        } else {
          this.myPublishList.push(...data)
        }
        
        this.pagination.myPublishList.total = total
        
        return response
      } catch (error) {
        console.error('获取我的发布列表失败:', error)
        throw error
      } finally {
        this.loading.myPublishList = false
      }
    },

    /**
     * 获取我的购买列表
     * @param {Object} params 查询参数
     */
    async fetchMyPurchaseList(params = {}) {
      this.loading.myPurchaseList = true
      
      try {
        const response = await tradingApi.getMyPurchaseList({
          page: this.pagination.myPurchaseList.page,
          size: this.pagination.myPurchaseList.size,
          ...params
        })
        
        const { data, total } = response.data
        
        if (params.page === 1) {
          this.myPurchaseList = data
        } else {
          this.myPurchaseList.push(...data)
        }
        
        this.pagination.myPurchaseList.total = total
        
        return response
      } catch (error) {
        console.error('获取我的购买列表失败:', error)
        throw error
      } finally {
        this.loading.myPurchaseList = false
      }
    },

    /**
     * 获取订单列表
     * @param {Object} params 查询参数
     */
    async fetchOrderList(params = {}) {
      this.loading.orderList = true
      
      try {
        const response = await tradingApi.getOrderList({
          page: this.pagination.orderList.page,
          size: this.pagination.orderList.size,
          ...params
        })
        
        const { data, total } = response.data
        
        if (params.page === 1) {
          this.orderList = data
        } else {
          this.orderList.push(...data)
        }
        
        this.pagination.orderList.total = total
        
        return response
      } catch (error) {
        console.error('获取订单列表失败:', error)
        throw error
      } finally {
        this.loading.orderList = false
      }
    },

    /**
     * 获取订单详情
     * @param {number} id 订单ID
     */
    async fetchOrderDetail(id) {
      try {
        const response = await tradingApi.getOrderDetail(id)
        this.currentOrder = response.data
        
        return response
      } catch (error) {
        console.error('获取订单详情失败:', error)
        throw error
      }
    },

    /**
     * 获取价格行情数据
     * @param {Object} params 查询参数
     */
    async fetchPriceData(params = {}) {
      this.loading.priceData = true
      
      try {
        const response = await tradingApi.getPriceData(params)
        this.priceData = response.data
        
        return response
      } catch (error) {
        console.error('获取价格行情失败:', error)
        throw error
      } finally {
        this.loading.priceData = false
      }
    },

    /**
     * 获取市场统计数据
     */
    async fetchMarketStats() {
      this.loading.marketStats = true
      
      try {
        const response = await tradingApi.getMarketStats()
        this.marketStats = response.data
        
        return response
      } catch (error) {
        console.error('获取市场统计失败:', error)
        throw error
      } finally {
        this.loading.marketStats = false
      }
    },

    /**
     * 发布交易信息
     * @param {Object} tradeData 交易数据
     */
    async publishTrade(tradeData) {
      try {
        const response = await tradingApi.publishTrade(tradeData)
        const newTrade = response.data
        
        this.myPublishList.unshift(newTrade)
        this.tradeList.unshift(newTrade)
        
        return response
      } catch (error) {
        console.error('发布交易失败:', error)
        throw error
      }
    },

    /**
     * 更新交易信息
     * @param {number} id 交易ID
     * @param {Object} tradeData 交易数据
     */
    async updateTrade(id, tradeData) {
      try {
        const response = await tradingApi.updateTrade(id, tradeData)
        const updatedTrade = response.data
        
        // 更新我的发布列表
        const publishIndex = this.myPublishList.findIndex(trade => trade.id === id)
        if (publishIndex > -1) {
          this.myPublishList[publishIndex] = updatedTrade
        }
        
        // 更新交易列表
        const tradeIndex = this.tradeList.findIndex(trade => trade.id === id)
        if (tradeIndex > -1) {
          this.tradeList[tradeIndex] = updatedTrade
        }
        
        // 更新当前交易
        if (this.currentTrade?.id === id) {
          this.currentTrade = updatedTrade
        }
        
        return response
      } catch (error) {
        console.error('更新交易失败:', error)
        throw error
      }
    },

    /**
     * 删除交易信息
     * @param {number} id 交易ID
     */
    async deleteTrade(id) {
      try {
        const response = await tradingApi.deleteTrade(id)
        
        // 从我的发布列表中移除
        const publishIndex = this.myPublishList.findIndex(trade => trade.id === id)
        if (publishIndex > -1) {
          this.myPublishList.splice(publishIndex, 1)
        }
        
        // 从交易列表中移除
        const tradeIndex = this.tradeList.findIndex(trade => trade.id === id)
        if (tradeIndex > -1) {
          this.tradeList.splice(tradeIndex, 1)
        }
        
        // 清除当前交易
        if (this.currentTrade?.id === id) {
          this.currentTrade = null
        }
        
        return response
      } catch (error) {
        console.error('删除交易失败:', error)
        throw error
      }
    },

    /**
     * 创建订单
     * @param {Object} orderData 订单数据
     */
    async createOrder(orderData) {
      try {
        const response = await tradingApi.createOrder(orderData)
        const newOrder = response.data
        
        this.orderList.unshift(newOrder)
        
        return response
      } catch (error) {
        console.error('创建订单失败:', error)
        throw error
      }
    },

    /**
     * 支付订单
     * @param {number} orderId 订单ID
     * @param {Object} paymentData 支付数据
     */
    async payOrder(orderId, paymentData) {
      try {
        const response = await tradingApi.payOrder(orderId, paymentData)
        
        // 更新订单状态
        const orderIndex = this.orderList.findIndex(order => order.id === orderId)
        if (orderIndex > -1) {
          this.orderList[orderIndex].status = 'paid'
          this.orderList[orderIndex].payTime = new Date().toISOString()
        }
        
        if (this.currentOrder?.id === orderId) {
          this.currentOrder.status = 'paid'
          this.currentOrder.payTime = new Date().toISOString()
        }
        
        return response
      } catch (error) {
        console.error('支付订单失败:', error)
        throw error
      }
    },

    /**
     * 取消订单
     * @param {number} orderId 订单ID
     * @param {string} reason 取消原因
     */
    async cancelOrder(orderId, reason) {
      try {
        const response = await tradingApi.cancelOrder(orderId, { reason })
        
        // 更新订单状态
        const orderIndex = this.orderList.findIndex(order => order.id === orderId)
        if (orderIndex > -1) {
          this.orderList[orderIndex].status = 'cancelled'
          this.orderList[orderIndex].cancelReason = reason
        }
        
        if (this.currentOrder?.id === orderId) {
          this.currentOrder.status = 'cancelled'
          this.currentOrder.cancelReason = reason
        }
        
        return response
      } catch (error) {
        console.error('取消订单失败:', error)
        throw error
      }
    },

    /**
     * 确认收货
     * @param {number} orderId 订单ID
     */
    async confirmReceive(orderId) {
      try {
        const response = await tradingApi.confirmReceive(orderId)
        
        // 更新订单状态
        const orderIndex = this.orderList.findIndex(order => order.id === orderId)
        if (orderIndex > -1) {
          this.orderList[orderIndex].status = 'completed'
          this.orderList[orderIndex].receiveTime = new Date().toISOString()
        }
        
        if (this.currentOrder?.id === orderId) {
          this.currentOrder.status = 'completed'
          this.currentOrder.receiveTime = new Date().toISOString()
        }
        
        return response
      } catch (error) {
        console.error('确认收货失败:', error)
        throw error
      }
    },

    /**
     * 获取交易分类
     */
    async fetchCategories() {
      try {
        const response = await tradingApi.getCategories()
        this.categories = response.data
        
        return response
      } catch (error) {
        console.error('获取交易分类失败:', error)
        throw error
      }
    },

    /**
     * 获取地区列表
     */
    async fetchRegions() {
      try {
        const response = await tradingApi.getRegions()
        this.regions = response.data
        
        return response
      } catch (error) {
        console.error('获取地区列表失败:', error)
        throw error
      }
    },

    /**
     * 设置搜索关键词
     * @param {string} keyword 搜索关键词
     */
    setSearchKeyword(keyword) {
      this.searchKeyword = keyword
    },

    /**
     * 设置筛选条件
     * @param {Object} filters 筛选条件
     */
    setFilters(filters) {
      this.filters = { ...this.filters, ...filters }
    },

    /**
     * 重置筛选条件
     */
    resetFilters() {
      this.filters = {
        category: '',
        region: '',
        priceRange: [],
        weightRange: [],
        ageRange: [],
        gender: '',
        breed: '',
        sortBy: 'createTime',
        sortOrder: 'desc'
      }
      this.searchKeyword = ''
    },

    /**
     * 收藏交易
     * @param {number} tradeId 交易ID
     */
    async favoriteTrade(tradeId) {
      try {
        const response = await tradingApi.favoriteTrade(tradeId)
        
        // 更新交易的收藏状态
        const updateTradeFavorite = (list) => {
          const index = list.findIndex(trade => trade.id === tradeId)
          if (index > -1) {
            list[index].isFavorited = true
            list[index].favoriteCount = (list[index].favoriteCount || 0) + 1
          }
        }
        
        updateTradeFavorite(this.tradeList)
        updateTradeFavorite(this.myPublishList)
        
        if (this.currentTrade?.id === tradeId) {
          this.currentTrade.isFavorited = true
          this.currentTrade.favoriteCount = (this.currentTrade.favoriteCount || 0) + 1
        }
        
        return response
      } catch (error) {
        console.error('收藏交易失败:', error)
        throw error
      }
    },

    /**
     * 取消收藏交易
     * @param {number} tradeId 交易ID
     */
    async unfavoriteTrade(tradeId) {
      try {
        const response = await tradingApi.unfavoriteTrade(tradeId)
        
        // 更新交易的收藏状态
        const updateTradeFavorite = (list) => {
          const index = list.findIndex(trade => trade.id === tradeId)
          if (index > -1) {
            list[index].isFavorited = false
            list[index].favoriteCount = Math.max((list[index].favoriteCount || 1) - 1, 0)
          }
        }
        
        updateTradeFavorite(this.tradeList)
        updateTradeFavorite(this.myPublishList)
        
        if (this.currentTrade?.id === tradeId) {
          this.currentTrade.isFavorited = false
          this.currentTrade.favoriteCount = Math.max((this.currentTrade.favoriteCount || 1) - 1, 0)
        }
        
        return response
      } catch (error) {
        console.error('取消收藏失败:', error)
        throw error
      }
    },

    /**
     * 刷新数据
     */
    async refreshData() {
      try {
        await Promise.all([
          this.fetchTradeList({ page: 1 }),
          this.fetchMarketStats(),
          this.fetchPriceData()
        ])
      } catch (error) {
        console.error('刷新数据失败:', error)
        throw error
      }
    },

    /**
     * 清除数据
     */
    clearData() {
      this.tradeList = []
      this.currentTrade = null
      this.myPublishList = []
      this.myPurchaseList = []
      this.orderList = []
      this.currentOrder = null
      this.priceData = []
      
      // 重置分页
      Object.keys(this.pagination).forEach(key => {
        this.pagination[key].page = 1
        this.pagination[key].total = 0
      })
      
      // 重置筛选条件
      this.resetFilters()
      
      // 重置统计数据
      this.marketStats = {
        totalTrades: 0,
        todayTrades: 0,
        averagePrice: 0,
        priceChange: 0,
        activeTraders: 0
      }
    }
  }
})