/**
 * 牛肉商城状态管理模块
 * 管理商城相关的数据和状态
 */

import { defineStore } from 'pinia'
import { mallApi } from '@/common/api/mall'

export const useMallStore = defineStore('mall', {
  state: () => ({
    // 商品列表
    productList: [],
    
    // 当前商品详情
    currentProduct: null,
    
    // 商品分类
    categories: [],
    
    // 购物车商品
    cartItems: [],
    
    // 订单列表
    orderList: [],
    
    // 当前订单详情
    currentOrder: null,
    
    // 收货地址列表
    addressList: [],
    
    // 默认收货地址
    defaultAddress: null,
    
    // 优惠券列表
    couponList: [],
    
    // 可用优惠券
    availableCoupons: [],
    
    // 商城统计数据
    mallStats: {
      totalProducts: 0,
      totalOrders: 0,
      totalSales: 0,
      todayOrders: 0
    },
    
    // 推荐商品
    recommendProducts: [],
    
    // 热销商品
    hotProducts: [],
    
    // 新品推荐
    newProducts: [],
    
    // 加载状态
    loading: {
      productList: false,
      cartItems: false,
      orderList: false,
      addressList: false,
      couponList: false
    },
    
    // 分页信息
    pagination: {
      productList: { page: 1, size: 20, total: 0 },
      orderList: { page: 1, size: 20, total: 0 }
    },
    
    // 筛选条件
    filters: {
      categoryId: '',
      priceRange: [],
      brand: '',
      origin: '',
      sortBy: 'createTime',
      sortOrder: 'desc'
    },
    
    // 搜索关键词
    searchKeyword: ''
  }),

  getters: {
    // 获取购物车商品数量
    cartItemCount: (state) => {
      return state.cartItems.reduce((total, item) => total + item.quantity, 0)
    },
    
    // 获取购物车总价
    cartTotalPrice: (state) => {
      return state.cartItems.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    },
    
    // 获取选中的购物车商品
    selectedCartItems: (state) => {
      return state.cartItems.filter(item => item.selected)
    },
    
    // 获取选中商品总价
    selectedCartTotalPrice: (state) => {
      return state.cartItems
        .filter(item => item.selected)
        .reduce((total, item) => total + (item.price * item.quantity), 0)
    },
    
    // 获取待付款订单
    pendingPaymentOrders: (state) => {
      return state.orderList.filter(order => order.status === 'pending_payment')
    },
    
    // 获取待发货订单
    pendingShipmentOrders: (state) => {
      return state.orderList.filter(order => order.status === 'pending_shipment')
    },
    
    // 获取待收货订单
    pendingReceiveOrders: (state) => {
      return state.orderList.filter(order => order.status === 'pending_receive')
    },
    
    // 获取已完成订单
    completedOrders: (state) => {
      return state.orderList.filter(order => order.status === 'completed')
    },
    
    // 获取可用优惠券数量
    availableCouponCount: (state) => {
      return state.availableCoupons.length
    },
    
    // 获取商品分类树
    categoryTree: (state) => {
      const buildTree = (categories, parentId = null) => {
        return categories
          .filter(cat => cat.parentId === parentId)
          .map(cat => ({
            ...cat,
            children: buildTree(categories, cat.id)
          }))
      }
      
      return buildTree(state.categories)
    },
    
    // 获取热门分类
    popularCategories: (state) => {
      return state.categories
        .filter(cat => cat.productCount > 0)
        .sort((a, b) => b.productCount - a.productCount)
        .slice(0, 8)
    }
  },

  actions: {
    /**
     * 获取商品列表
     * @param {Object} params 查询参数
     */
    async fetchProductList(params = {}) {
      this.loading.productList = true
      
      try {
        const response = await mallApi.getProductList({
          page: this.pagination.productList.page,
          size: this.pagination.productList.size,
          keyword: this.searchKeyword,
          ...this.filters,
          ...params
        })
        
        const { data, total } = response.data
        
        if (params.page === 1) {
          this.productList = data
        } else {
          this.productList.push(...data)
        }
        
        this.pagination.productList.total = total
        this.mallStats.totalProducts = total
        
        return response
      } catch (error) {
        console.error('获取商品列表失败:', error)
        throw error
      } finally {
        this.loading.productList = false
      }
    },

    /**
     * 获取商品详情
     * @param {number} id 商品ID
     */
    async fetchProductDetail(id) {
      try {
        const response = await mallApi.getProductDetail(id)
        this.currentProduct = response.data
        
        return response
      } catch (error) {
        console.error('获取商品详情失败:', error)
        throw error
      }
    },

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

    /**
     * 获取推荐商品
     * @param {Object} params 查询参数
     */
    async fetchRecommendProducts(params = {}) {
      try {
        const response = await mallApi.getRecommendProducts(params)
        this.recommendProducts = response.data
        
        return response
      } catch (error) {
        console.error('获取推荐商品失败:', error)
        throw error
      }
    },

    /**
     * 获取热销商品
     * @param {Object} params 查询参数
     */
    async fetchHotProducts(params = {}) {
      try {
        const response = await mallApi.getHotProducts(params)
        this.hotProducts = response.data
        
        return response
      } catch (error) {
        console.error('获取热销商品失败:', error)
        throw error
      }
    },

    /**
     * 获取新品推荐
     * @param {Object} params 查询参数
     */
    async fetchNewProducts(params = {}) {
      try {
        const response = await mallApi.getNewProducts(params)
        this.newProducts = response.data
        
        return response
      } catch (error) {
        console.error('获取新品推荐失败:', error)
        throw error
      }
    },

    /**
     * 获取购物车商品
     */
    async fetchCartItems() {
      this.loading.cartItems = true
      
      try {
        const response = await mallApi.getCartItems()
        this.cartItems = response.data.map(item => ({
          ...item,
          selected: false
        }))
        
        return response
      } catch (error) {
        console.error('获取购物车失败:', error)
        throw error
      } finally {
        this.loading.cartItems = false
      }
    },

    /**
     * 添加商品到购物车
     * @param {Object} productData 商品数据
     */
    async addToCart(productData) {
      try {
        const response = await mallApi.addToCart(productData)
        
        // 检查购物车中是否已存在该商品
        const existingIndex = this.cartItems.findIndex(
          item => item.productId === productData.productId && 
                  item.skuId === productData.skuId
        )
        
        if (existingIndex > -1) {
          // 更新数量
          this.cartItems[existingIndex].quantity += productData.quantity
        } else {
          // 添加新商品
          this.cartItems.push({
            ...response.data,
            selected: false
          })
        }
        
        return response
      } catch (error) {
        console.error('添加购物车失败:', error)
        throw error
      }
    },

    /**
     * 更新购物车商品数量
     * @param {number} cartItemId 购物车商品ID
     * @param {number} quantity 数量
     */
    async updateCartItemQuantity(cartItemId, quantity) {
      try {
        const response = await mallApi.updateCartItem(cartItemId, { quantity })
        
        const index = this.cartItems.findIndex(item => item.id === cartItemId)
        if (index > -1) {
          if (quantity <= 0) {
            this.cartItems.splice(index, 1)
          } else {
            this.cartItems[index].quantity = quantity
          }
        }
        
        return response
      } catch (error) {
        console.error('更新购物车失败:', error)
        throw error
      }
    },

    /**
     * 删除购物车商品
     * @param {number} cartItemId 购物车商品ID
     */
    async removeCartItem(cartItemId) {
      try {
        const response = await mallApi.removeCartItem(cartItemId)
        
        const index = this.cartItems.findIndex(item => item.id === cartItemId)
        if (index > -1) {
          this.cartItems.splice(index, 1)
        }
        
        return response
      } catch (error) {
        console.error('删除购物车商品失败:', error)
        throw error
      }
    },

    /**
     * 清空购物车
     */
    async clearCart() {
      try {
        const response = await mallApi.clearCart()
        this.cartItems = []
        
        return response
      } catch (error) {
        console.error('清空购物车失败:', error)
        throw error
      }
    },

    /**
     * 选择/取消选择购物车商品
     * @param {number} cartItemId 购物车商品ID
     * @param {boolean} selected 是否选中
     */
    selectCartItem(cartItemId, selected) {
      const index = this.cartItems.findIndex(item => item.id === cartItemId)
      if (index > -1) {
        this.cartItems[index].selected = selected
      }
    },

    /**
     * 全选/取消全选购物车商品
     * @param {boolean} selected 是否选中
     */
    selectAllCartItems(selected) {
      this.cartItems.forEach(item => {
        item.selected = selected
      })
    },

    /**
     * 获取订单列表
     * @param {Object} params 查询参数
     */
    async fetchOrderList(params = {}) {
      this.loading.orderList = true
      
      try {
        const response = await mallApi.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
        this.mallStats.totalOrders = 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 mallApi.getOrderDetail(id)
        this.currentOrder = response.data
        
        return response
      } catch (error) {
        console.error('获取订单详情失败:', error)
        throw error
      }
    },

    /**
     * 创建订单
     * @param {Object} orderData 订单数据
     */
    async createOrder(orderData) {
      try {
        const response = await mallApi.createOrder(orderData)
        const newOrder = response.data
        
        this.orderList.unshift(newOrder)
        
        // 清除已购买的购物车商品
        if (orderData.cartItemIds) {
          this.cartItems = this.cartItems.filter(
            item => !orderData.cartItemIds.includes(item.id)
          )
        }
        
        return response
      } catch (error) {
        console.error('创建订单失败:', error)
        throw error
      }
    },

    /**
     * 支付订单
     * @param {number} orderId 订单ID
     * @param {Object} paymentData 支付数据
     */
    async payOrder(orderId, paymentData) {
      try {
        const response = await mallApi.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 mallApi.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 mallApi.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 fetchAddressList() {
      this.loading.addressList = true
      
      try {
        const response = await mallApi.getAddressList()
        this.addressList = response.data
        
        // 设置默认地址
        const defaultAddr = this.addressList.find(addr => addr.isDefault)
        if (defaultAddr) {
          this.defaultAddress = defaultAddr
        }
        
        return response
      } catch (error) {
        console.error('获取收货地址失败:', error)
        throw error
      } finally {
        this.loading.addressList = false
      }
    },

    /**
     * 添加收货地址
     * @param {Object} addressData 地址数据
     */
    async addAddress(addressData) {
      try {
        const response = await mallApi.addAddress(addressData)
        const newAddress = response.data
        
        this.addressList.push(newAddress)
        
        // 如果是默认地址，更新默认地址
        if (newAddress.isDefault) {
          this.defaultAddress = newAddress
          // 取消其他地址的默认状态
          this.addressList.forEach(addr => {
            if (addr.id !== newAddress.id) {
              addr.isDefault = false
            }
          })
        }
        
        return response
      } catch (error) {
        console.error('添加收货地址失败:', error)
        throw error
      }
    },

    /**
     * 更新收货地址
     * @param {number} id 地址ID
     * @param {Object} addressData 地址数据
     */
    async updateAddress(id, addressData) {
      try {
        const response = await mallApi.updateAddress(id, addressData)
        const updatedAddress = response.data
        
        const index = this.addressList.findIndex(addr => addr.id === id)
        if (index > -1) {
          this.addressList[index] = updatedAddress
        }
        
        // 如果是默认地址，更新默认地址
        if (updatedAddress.isDefault) {
          this.defaultAddress = updatedAddress
          // 取消其他地址的默认状态
          this.addressList.forEach(addr => {
            if (addr.id !== updatedAddress.id) {
              addr.isDefault = false
            }
          })
        }
        
        return response
      } catch (error) {
        console.error('更新收货地址失败:', error)
        throw error
      }
    },

    /**
     * 删除收货地址
     * @param {number} id 地址ID
     */
    async deleteAddress(id) {
      try {
        const response = await mallApi.deleteAddress(id)
        
        const index = this.addressList.findIndex(addr => addr.id === id)
        if (index > -1) {
          this.addressList.splice(index, 1)
        }
        
        // 如果删除的是默认地址，清除默认地址
        if (this.defaultAddress?.id === id) {
          this.defaultAddress = null
        }
        
        return response
      } catch (error) {
        console.error('删除收货地址失败:', error)
        throw error
      }
    },

    /**
     * 获取优惠券列表
     */
    async fetchCouponList() {
      this.loading.couponList = true
      
      try {
        const response = await mallApi.getCouponList()
        this.couponList = response.data
        
        return response
      } catch (error) {
        console.error('获取优惠券失败:', error)
        throw error
      } finally {
        this.loading.couponList = false
      }
    },

    /**
     * 获取可用优惠券
     * @param {number} totalAmount 订单总金额
     */
    async fetchAvailableCoupons(totalAmount) {
      try {
        const response = await mallApi.getAvailableCoupons({ totalAmount })
        this.availableCoupons = response.data
        
        return response
      } catch (error) {
        console.error('获取可用优惠券失败:', error)
        throw error
      }
    },

    /**
     * 领取优惠券
     * @param {number} couponId 优惠券ID
     */
    async receiveCoupon(couponId) {
      try {
        const response = await mallApi.receiveCoupon(couponId)
        
        // 更新优惠券状态
        const couponIndex = this.couponList.findIndex(coupon => coupon.id === couponId)
        if (couponIndex > -1) {
          this.couponList[couponIndex].received = true
          this.couponList[couponIndex].receiveCount++
        }
        
        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 = {
        categoryId: '',
        priceRange: [],
        brand: '',
        origin: '',
        sortBy: 'createTime',
        sortOrder: 'desc'
      }
      this.searchKeyword = ''
    },

    /**
     * 刷新数据
     */
    async refreshData() {
      try {
        await Promise.all([
          this.fetchProductList({ page: 1 }),
          this.fetchCategories(),
          this.fetchRecommendProducts(),
          this.fetchHotProducts(),
          this.fetchNewProducts()
        ])
      } catch (error) {
        console.error('刷新数据失败:', error)
        throw error
      }
    },

    /**
     * 清除数据
     */
    clearData() {
      this.productList = []
      this.currentProduct = null
      this.cartItems = []
      this.orderList = []
      this.currentOrder = null
      this.addressList = []
      this.defaultAddress = null
      this.couponList = []
      this.availableCoupons = []
      this.recommendProducts = []
      this.hotProducts = []
      this.newProducts = []
      
      // 重置分页
      Object.keys(this.pagination).forEach(key => {
        this.pagination[key].page = 1
        this.pagination[key].total = 0
      })
      
      // 重置筛选条件
      this.resetFilters()
      
      // 重置统计数据
      this.mallStats = {
        totalProducts: 0,
        totalOrders: 0,
        totalSales: 0,
        todayOrders: 0
      }
    }
  }
})