<template>
  <!-- 点餐页 -->
  <view class="content">
    <view class="top-info">桌号：A08 &nbsp;&nbsp;就餐人数：{{ currentDiners }}人</view>
    <!-- 搜索 -->
    <input type="text" placeholder="请输入菜品名称" class="search-input" />

    <!-- 内容 -->
    <view class="content-box">
      <!-- 左侧分类列表 -->
      <scroll-view class="category-list" scroll-y>
        <view v-for="(category, index) in categories" :key="index" class="category-item"
          :class="{ active: currentCategoryIndex === index }" @click="selectCategory(index)">
          {{ category.name }}
        </view>
      </scroll-view>

      <!-- 右侧菜品列表 -->
      <scroll-view class="food-list" scroll-y>
        <FoodCard v-for="(food, index) in currentFoodList" :key="food.id || index" :food="food"
          @increase="handleIncrease" @decrease="handleDecrease"/>
      </scroll-view>
    </view>

    <!-- 底部下单 -->
    <BottomActionBar :cart-list="cartList" @coupon-click="handleCouponClick" @cart-click="handleCartClick"
      @order-click="handleOrderClick" />

    <!-- 领取优惠券弹窗 -->
    <CouponModal v-model:open="couponModalOpen" :coupon-list="couponList" @receive="handleCouponReceive"
      @close="handleCouponClose" />

    <!-- 购物车弹窗 -->
    <CartModal v-model:open="cartModalOpen" :cart-list="cartList" :discount-amount="discountAmount"
      @increase="handleIncrease" @decrease="handleDecrease" @clear="handleCartClear"
      @coupon-click="handleSelectCouponClick" @order-click="handleOrderClick" @close="handleCartClose" />

    <!-- 选择优惠券弹窗 -->
    <SelectCouponModal v-model:open="selectCouponModalOpen" :coupon-list="availableCoupons"
      :selected-coupon-id="selectedCouponId" @select="handleCouponSelect" @close="handleSelectCouponClose" />
  </view>
</template>

<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { ref, computed } from "vue";
import FoodCard from "./components/FoodCard.vue";
import BottomActionBar from "./components/BottomActionBar.vue";
import CouponModal from "./components/CouponModal.vue";
import CartModal from "./components/CartModal.vue";
import SelectCouponModal from "./components/SelectCouponModal.vue";
import { go } from "@/utils/utils.js";

const currentDiners = ref(uni.getStorageSync('currentDiners'));
const currentCategoryIndex = ref(0);
const couponModalOpen = ref(false);
const cartModalOpen = ref(false);
const selectCouponModalOpen = ref(false);
const discountAmount = ref(12); // 优惠金额，示例数据
const selectedCouponId = ref(null); // 选中的优惠券ID

// 分类列表
const categories = ref([
  { name: '推荐菜品', id: 'recommend' },
  { name: '招牌川菜', id: 'signature' },
  { name: '凉菜', id: 'cold' },
  { name: '热菜', id: 'hot' },
  { name: '汤品', id: 'soup' },
  { name: '主食', id: 'staple' },
  { name: '饮品', id: 'drink' }
]);

// 菜品列表数据（示例数据）
const foodList = ref([
  {
    id: 1,
    name: '炭烤牛排',
    price: 26,
    desc: '正宗川味, 麻辣鲜香, 豆腐滑嫩',
    image: '/static/demo.png',
    tags: [
      { text: '招牌', type: 'signature' },
      { text: '中辣', type: 'spicy' }
    ],
    monthlySales: 160,
    quantity: 0,
    categoryId: 'recommend'
  },
  {
    id: 2,
    name: '炭烤牛排',
    price: 26,
    desc: '正宗川味, 麻辣鲜香, 豆腐滑嫩',
    image: '/static/demo.png',
    tags: [
      { text: '招牌', type: 'signature' },
      { text: '中辣', type: 'spicy' }
    ],
    monthlySales: 160,
    quantity: 99,
    categoryId: 'recommend'
  },
  {
    id: 3,
    name: '炭烤牛排',
    price: 26,
    desc: '正宗川味, 麻辣鲜香, 豆腐滑嫩',
    image: '/static/demo.png',
    tags: [
      { text: '招牌', type: 'signature' },
      { text: '中辣', type: 'spicy' }
    ],
    monthlySales: 160,
    quantity: 23,
    categoryId: 'cold'
  },
  {
    id: 4,
    name: '炭烤牛排',
    price: 26,
    desc: '正宗川味, 麻辣鲜香, 豆腐滑嫩',
    image: '/static/demo.png',
    tags: [
      { text: '招牌', type: 'signature' },
      { text: '中辣', type: 'spicy' }
    ],
    monthlySales: 160,
    quantity: 0,
    categoryId: 'cold'
  }
]);

// 当前分类的菜品列表
const currentFoodList = computed(() => {
  const categoryId = categories.value[currentCategoryIndex.value].id;
  return foodList.value.filter(food => food.categoryId === categoryId);
});

// 购物车列表（只包含数量大于0的菜品）
const cartList = computed(() => {
  return foodList.value.filter(food => food.quantity > 0);
});

// 优惠券列表（示例数据）
const couponList = ref([
  {
    id: 1,
    amount: 38,
    minAmount: 158,
    name: '优惠券名称',
    expireDate: '2024/07/28',
    isReceived: false
  },
  {
    id: 2,
    amount: 8,
    minAmount: 158,
    name: '优惠券名称',
    expireDate: '2024/07/28',
    isReceived: false
  },
  {
    id: 3,
    amount: 682,
    minAmount: 1580,
    name: '优惠券名称',
    expireDate: '2024/07/28',
    isReceived: true
  },
  {
    id: 4,
    amount: 1038,
    minAmount: 1580,
    name: '优惠券名称',
    expireDate: '2024/07/28',
    isReceived: true
  }
]);

// 可用的优惠券列表（已领取的优惠券）
const availableCoupons = computed(() => {
  return couponList.value.filter(coupon => coupon.isReceived);
});

// 选择分类
const selectCategory = (index) => {
  currentCategoryIndex.value = index;
};

// 增加数量
const handleIncrease = (food) => {
  if (food) {
    food.quantity = (food.quantity || 0) + 1;
  }
};

// 减少数量
const handleDecrease = (food) => {
  if (food && food.quantity > 0) {
    food.quantity -= 1;
  }
};

// 优惠券点击（领取优惠券弹窗）
const handleCouponClick = () => {
  // 先关闭其他弹窗
  if (cartModalOpen.value) {
    cartModalOpen.value = false;
  }
  if (selectCouponModalOpen.value) {
    selectCouponModalOpen.value = false;
  }
  couponModalOpen.value = true;
};

// 选择优惠券点击（从购物车弹窗中点击）
const handleSelectCouponClick = () => {
  // 先关闭其他弹窗
  if (cartModalOpen.value) {
    cartModalOpen.value = false;
  }
  if (couponModalOpen.value) {
    couponModalOpen.value = false;
  }
  // 打开选择优惠券弹窗
  selectCouponModalOpen.value = true;
};

// 处理优惠券选择
const handleCouponSelect = ({ coupon, index, selectedId }) => {
  selectedCouponId.value = selectedId;
  // 根据选中的优惠券更新优惠金额
  if (selectedId) {
    discountAmount.value = coupon.amount;
  } else {
    discountAmount.value = 0;
  }
  // 选择后关闭选择优惠券弹窗，打开购物车弹窗
  selectCouponModalOpen.value = false;
  // 延迟打开购物车弹窗，确保选择优惠券弹窗完全关闭
  setTimeout(() => {
    cartModalOpen.value = true;
  }, 100);
};

// 选择优惠券弹窗关闭
const handleSelectCouponClose = () => {
  selectCouponModalOpen.value = false;
};

// 优惠券领取
const handleCouponReceive = ({ coupon, index }) => {
  console.log('领取优惠券:', coupon);
  // 更新优惠券状态
  couponList.value[index].isReceived = true;
  uni.showToast({
    title: '领取成功',
    icon: 'success'
  });
  // TODO: 调用接口领取优惠券
};

// 优惠券弹窗关闭
const handleCouponClose = () => {
  couponModalOpen.value = false;
};

// 购物车点击
const handleCartClick = () => {
  if (cartList.value.length === 0) {
    uni.showToast({
      title: '购物车为空',
      icon: 'none'
    });
    return;
  }
  // 先关闭其他弹窗
  if (couponModalOpen.value) {
    couponModalOpen.value = false;
  }
  if (selectCouponModalOpen.value) {
    selectCouponModalOpen.value = false;
  }
  cartModalOpen.value = true;
};

// 购物车弹窗关闭
const handleCartClose = () => {
  cartModalOpen.value = false;
};

// 清空购物车
const handleCartClear = () => {
  foodList.value.forEach(food => {
    food.quantity = 0;
  });
  cartModalOpen.value = false;
  uni.showToast({
    title: '已清空购物车',
    icon: 'success'
  });
};

// 下单点击
const handleOrderClick = (data) => {
  go('/pages/placeOrder/index');
};

onLoad((e) => {
  uni.setNavigationBarTitle({
    title: '店铺名称'
  });
});
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f9fa;
  padding-bottom: 100rpx;
  box-sizing: border-box;
}

.top-info {
  font-size: 28rpx;
  color: #888888;
  text-align: center;
  width: 100%;
  padding: 20rpx 0;
  background-color: #fff;
}

.search-input {
  width: 90%;
  margin-left: 5%;
  height: 80rpx;
  background-color: #fff;
  border-radius: 40rpx;
  padding: 0 20rpx;
  margin-top: 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  text-align: center;
}

.content-box {
  display: flex;
  flex: 1;
  overflow: hidden;
  margin-top: 20rpx;
}

// 左侧分类列表
.category-list {
  width: 180rpx;
  background-color: #fff;
  height: 100%;
}

.category-item {
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #999;
  background-color: #fff;
  transition: all 0.3s;

  &.active {
    background-color: #fff4e6;
    color: #333;
    font-weight: 600;
  }
}

// 右侧菜品列表
.food-list {
  flex: 1;
  // background-color: #fff;
  // padding: 0 20rpx;
  margin: 0 20rpx;
}
</style>
