<template>
  <!-- 首页 -->
  <view class="content">
    <!-- 顶部 -->
    <image :src="getFileUrl('img/icon/zptj.png')" mode="aspectFill" class="top-img"></image>

    <!-- 内容 -->
    <view class="content-box">
      <view class="shop-info">
        <image :src="getFileUrl('img/icon/shop.png')" mode="aspectFill" class="shop-img"></image>
        <view class="shop-name">{{ storeInfo.storeName || '店铺名称' }}</view>
      </view>

      <!-- 登录卡片 -->
      <view class='login-card' v-if="!userStore.getToken">
        <view class="login-card-left">
          <view class="welcome-title">欢迎来到{{ storeInfo.storeName || 'xxx' }}店铺</view>
          <view class="welcome-desc">注册登录即可体验更好的服务</view>
          <view class="login-btn" hover-class="hover-active" @click="showLoginModal = true">立即登录</view>
        </view>
        <view class="login-card-right">
          <image :src="getFileUrl('img/icon/welcom.png')" mode="widthFix" class="welcome-img"></image>
        </view>
      </view>

      <view class="banner-box">
        <image :src="getFileUrl('img/icon/zptj.png')" mode="widthFix" class="banner-img"></image>
      </view>

      <!-- 列表 -->
      <view class="list-box">
        <view class="food-card" v-for="(item, index) in foodList" :key="item.id || index" hover-class="hover-active" @click="handleFoodClick(item)">
          <!-- 菜品图片 -->
          <image :src="getFileUrl(item.image)" mode="aspectFill" class="food-image"></image>

          <!-- 菜品信息 -->
          <view class="food-info">
            <!-- 标题和月售 -->
            <view class="food-header">
              <view class="food-left">
                <view class="food-name">{{ item.name }}</view>
                <view class="food-sales">
                  <image :src="getFileUrl('img/icon/star.png')" mode="aspectFill" class="star-icon"></image>
                  <text class="sales-text">月售:{{ item.sales }}</text>
                </view>
              </view>
              <view class="food-right">

                <view class="food-price">
                  <text class="price-symbol">¥</text>
                  <text class="price-main">{{ getPriceMain(item.price) }}</text>
                  <text class="price-decimal">.{{ getPriceDecimal(item.price) }}</text>
                </view>
              </view>
            </view>

            <!-- 标签 -->
            <view class="food-tags">
              <view v-for="(tag, tagIndex) in item.tags" :key="tagIndex" class="food-tag" :class="tag.type">
                {{ tag.text }}
              </view>
            </view>

            <!-- 描述 -->
            <view class="food-desc">{{ item.dishReview }}</view>
          </view>
        </view>
      </view>

    </view>
    <!-- 登录弹窗组件 -->
    <view class="login-modal-wrapper">
      <LoginModal v-model:open="showLoginModal" @success="handleLoginSuccess" @cancel="handleLoginCancel" />
    </view>

    <!-- 底部导航 -->
    <TabBar />
  </view>
</template>

<script setup>
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import TabBar from "@/components/TabBar.vue";
import LoginModal from "@/pages/components/LoginModal.vue";
import { go } from "@/utils/utils.js";
import { getFileUrl } from '@/utils/file.js';
import { useUserStore } from '@/store/user.js';
import { TOKEN } from '@/settings/enums.js';
import { GetStoreDetail } from '@/api/dining.js';

const userStore = useUserStore();
const showLoginModal = ref(false);
/** 门店信息（接口返回的 storeInfo，绑定 storeName 等） */
const storeInfo = ref({});

// 首页菜品列表（绑定接口 homepageCuisines，兼容多种字段名）
const foodList = ref([]);

function normalizeHomeCuisine(item) {
  const tags = item?.tags ?? [];
  const tagArr = Array.isArray(tags) ? tags : [];
  const images = item?.images;
  const imageUrl = Array.isArray(images) ? images[0] : images;
  return {
    id: item?.id ?? item?.cuisineId ?? '',
    image: imageUrl ?? item?.cuisineImage ?? item?.image ?? 'img/icon/shop.png',
    name: item?.cuisineName ?? item?.name ?? '',
    sales: item?.monthlySales ?? item?.sales ?? 0,
    tags: tagArr.map((t) => (typeof t === 'string' ? { text: t, type: 'normal' } : { text: t?.text ?? t?.tagName ?? '', type: t?.type ?? 'normal' })),
    description: item?.description ?? item?.desc ?? '',
    price: item?.totalPrice ?? item?.unitPrice ?? item?.price ?? ''
  };
}

// 格式化为保留两位小数的价格字符串
const formatPriceFixed2 = (price) => {
  if (price === '' || price === null || price === undefined) return '0.00';
  const num = Number(price);
  return Number.isNaN(num) ? '0.00' : num.toFixed(2);
};

// 获取价格整数部分
const getPriceMain = (price) => {
  const priceStr = formatPriceFixed2(price);
  const dotIndex = priceStr.indexOf('.');
  return dotIndex > -1 ? priceStr.substring(0, dotIndex) : priceStr;
};

// 获取价格小数部分（两位）
const getPriceDecimal = (price) => {
  const priceStr = formatPriceFixed2(price);
  const dotIndex = priceStr.indexOf('.');
  return dotIndex > -1 ? priceStr.substring(dotIndex + 1) : '00';
};

// 登录成功回调：跳转点餐页
const handleLoginSuccess = () => {
  const tableid = uni.getStorageSync('currentTableId') || '';
  const diners = uni.getStorageSync('currentDiners') || '1';
  const q = [];
  if (tableid) q.push(`tableid=${encodeURIComponent(tableid)}`);
  if (diners) q.push(`diners=${encodeURIComponent(diners)}`);
  const url = q.length ? `/pages/orderFood/index?${q.join('&')}` : '/pages/orderFood/index';
  go(url);
};

// 取消登录回调
const handleLoginCancel = () => {
  console.log('用户取消登录');
};

// 点击菜品：先校验登录，未登录提示请登录；已登录则跳转菜品详情页
const handleFoodClick = (item) => {
  const token = userStore.getToken || uni.getStorageSync(TOKEN) || '';
  if (!token) {
    uni.showToast({ title: '请登录', icon: 'none' });
    return;
  }
  const cuisineId = item?.id ?? item?.cuisineId ?? '';
  if (!cuisineId) return;
  const tableId = uni.getStorageSync('currentTableId') ?? '';
  const q = [`cuisineId=${encodeURIComponent(String(cuisineId))}`];
  if (tableId !== '') q.push(`tableId=${encodeURIComponent(String(tableId))}`);
  go(`/pages/foodDetail/index?${q.join('&')}`);
};

onLoad(async (options) => {
  const storeId = options?.storeId ?? uni.getStorageSync('currentStoreId') ?? '';
  if (storeId) {
    try {
      const res = await GetStoreDetail(storeId);
      const data = res?.data ?? res;
      storeInfo.value = data?.storeInfo ?? data ?? {};
      const list = data?.homepageCuisines ?? data?.storeInfo?.homepageCuisines ?? [];
      foodList.value = (Array.isArray(list) ? list : []).map(normalizeHomeCuisine);
    } catch (e) {
      console.error('门店详情加载失败:', e);
    }
  }
});
</script>

<style scoped lang="scss">
.content {
  .top-img {
    width: 100%;
    height: 572rpx;
  }

  .content-box {
    width: 100%;
    box-sizing: border-box;
    padding: 0 30rpx 140rpx;

    .shop-info {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100rpx;
      background-color: #fff;
      border-radius: 17rpx;
      margin-top: -50rpx;
      position: relative;
      z-index: 2;
      box-shadow: 0rpx 0rpx 11rpx 0rpx rgba(0, 0, 0, 0.06);

      .shop-img {
        width: 45rpx;
        height: 38rpx;
        margin-right: 20rpx;
      }

      .shop-name {
        font-weight: bold;
        font-size: 31rpx;
        color: #151515;
      }
    }
  }

  .login-card {
    width: 100%;
    min-height: 240rpx;
    background-color: #fff;
    border-radius: 17rpx;
    margin-top: 20rpx;
    box-sizing: border-box;
    padding: 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0rpx 0rpx 11rpx 0rpx rgba(0, 0, 0, 0.06);

    .login-card-left {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding-right: 20rpx;

      .welcome-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #151515;
        margin-bottom: 16rpx;
        line-height: 1.4;
      }

      .welcome-desc {
        font-size: 27rpx;
        color: #666666;
        margin-bottom: 24rpx;
        line-height: 1.4;
      }

      .login-btn {
        width: 160rpx;
        height: 53rpx;
        background: #2E2E2E;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 27rpx;
        color: #FFFFFF;
        font-weight: 500;
        cursor: pointer;
        transition: opacity 0.3s;

        &:active {
          opacity: 0.8;
        }
      }
    }

    .login-card-right {
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: center;

      .welcome-img {
        width: 200rpx;
        height: auto;
      }
    }
  }

  // 登录弹窗层级设置（盖住底部 tabbar）
  .login-modal-wrapper {
    position: relative;
    z-index: 99999;

    :deep(.uni-popup) {
      z-index: 99999 !important;
      top: 0 !important;
      left: 0 !important;
      right: 0 !important;
      bottom: 0 !important;
    }
    :deep(.uni-popup__wrapper) {
      z-index: 99999 !important;
    }
  }

  .banner-box {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 40rpx;

    .banner-img {
      width: 480rpx;
      height: 66rpx;
      margin: 0 auto;
    }
  }

  .list-box {
    width: 100%;
    margin-top: 40rpx;
    padding-bottom: 40rpx;

    .food-card {
      width: 100%;
      background-color: #fff;
      border-radius: 17rpx;
      overflow: hidden;
      margin-bottom: 30rpx;
      box-shadow: 0rpx 0rpx 11rpx 0rpx rgba(0, 0, 0, 0.06);

      .food-image {
        width: 100%;
        height: 400rpx;
        display: block;
      }

      .food-info {
        padding: 30rpx;
        position: relative;
        box-sizing: border-box;

        .food-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 20rpx;

          .food-name {
            font-size: 32rpx;
            font-weight: bold;
            color: #151515;
            flex: 1;
            max-width: 360rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .food-left {
            display: flex;
            align-items: center;
            gap: 20rpx;
          }

          .food-right {
            display: flex;
            align-items: center;
            gap: 20rpx;
            flex-shrink: 0;
          }

          .food-sales {
            display: flex;
            align-items: center;
            font-size: 24rpx;
            color: #999999;

            .star-icon {
              width: 20rpx;
              height: 20rpx;
              margin-right: 8rpx;
            }

            .sales-text {
              font-size: 24rpx;
              color: #999999;
            }
          }

          .food-price {
            display: flex;
            align-items: baseline;
            color: #FF3B30;
            line-height: 1;

            .price-symbol {
              font-size: 24rpx;
              font-weight: bold;
            }

            .price-main {
              font-size: 44rpx;
              font-weight: bold;
            }

            .price-decimal {
              font-size: 24rpx;
              font-weight: bold;
            }
          }
        }

        .food-tags {
          display: flex;
          align-items: center;
          gap: 12rpx;
          margin-bottom: 20rpx;

          .food-tag {
            padding: 6rpx 16rpx;
            border-radius: 6rpx;
            font-size: 22rpx;
            color: #FFFFFF;
            line-height: 1.2;

            &.signature {
              background: linear-gradient(90deg, #FCB13F 0%, #FC793D 100%);
            }

            &.spicy {
              background: #2E2E2E;
            }
          }
        }

        .food-desc {
          font-size: 26rpx;
          color: #151515;
          line-height: 1.6;
          margin-top: 20rpx;
        }
      }
    }
  }
}
</style>
