// composables/useProductComparison.js
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';

export function useProductComparison() {
  // 存储已选择的对比产品
  const selectedProducts = ref([]);
  // 最大可选产品数量
  const maxCount = 3;
  
  const router = useRouter();
  
  // 检查是否已选择该产品
  const isSelected = (productId) => {
    return selectedProducts.value.some(item => item.id === productId);
  };
  
  // 添加产品到对比列表
  const addToComparison = (product) => {
    if (selectedProducts.value.length >= maxCount) {
      uni.showToast({
        title: `最多只能选择${maxCount}个产品进行对比`,
        icon: 'none'
      });
      return false;
    }
    
    // 检查是否同险种
    if (selectedProducts.value.length > 0) {
      const firstType = selectedProducts.value[0].typeId;
      if (product.typeId !== firstType) {
        uni.showToast({
          title: '只能选择同险种产品进行对比',
          icon: 'none'
        });
        return false;
      }
    }
    
    if (!isSelected(product.id)) {
      selectedProducts.value.push(product);
      return true;
    }
    return false;
  };
  
  // 从对比列表移除产品
  const removeFromComparison = (productId) => {
    selectedProducts.value = selectedProducts.value.filter(
      item => item.id !== productId
    );
  };
  
  // 清空对比列表
  const clearComparison = () => {
    selectedProducts.value = [];
  };
  
  // 跳转到对比结果页
  const goToComparisonResult = () => {
    if (selectedProducts.value.length < 2) {
      uni.showToast({
        title: '至少选择2个产品才能进行对比',
        icon: 'none'
      });
      return;
    }
    
    const productIds = selectedProducts.value.map(item => item.id).join(',');
    router.push({
      path: '/pages/compare-result/compare-result',
      query: { productIds }
    });
  };
  
  return {
    selectedProducts,
    maxCount,
    isSelected,
    addToComparison,
    removeFromComparison,
    clearComparison,
    goToComparisonResult
  };
}