<template>
  <view class="container">
    <view class="top">
      <!-- 搜索 -->
      <Search background="rgba(255, 255, 255, 0.8)" backIcon="black" @toSearch="toSearch">
        <image class="food" src="../../static/index/food.png" mode="widthFix" />
      </Search>
      <!-- 类别选择 -->
      <view class="classification">
        <view class="classification-top">
          <view
            @tap="jingang(item.categoryId, item.pic, item.categoryName)"
            class="choice"
            v-for="(item, index) in classificationT"
            :key="index"
          >
            <image class="imgs" :src="item.icon" mode="widthFix" />
            <text class="introduce">{{ item.categoryName }}</text>
          </view>
        </view>
        <view class="classification-bottom">
          <view
            @tap="jingang(item.categoryId, item.pic, item.categoryName)"
            class="choice"
            v-for="(item, index) in classificationB"
            :key="index"
          >
            <image class="imgs" :src="item.icon" mode="widthFix" />
            <text class="introduce">{{ item.categoryName }}</text>
          </view>
        </view>
      </view>
    </view>
    <!-- 红包 -->
    <view class="redEnvelope">
      <view class="title">今日福利</view>
      <scroll-view class="box-red" scroll-x="true" @scroll="scroll">
        <view class="redBagBox" v-for="(item, index) in coupon" :key="index">
          <view class="content">
            <text class="textO">{{ item.activityName }}</text>
            <text class="textW">￥{{ item.discountValue }}</text>
          </view>
          <view v-if="item.numState === 0" class="textF" @tap="receive(item)">领取</view>
          <view v-else class="textF" @tap="toUse">去使用</view>
        </view>
      </scroll-view>
      <image
        @tap="toCoupon"
        class="discount"
        src="../../static/index/discount.png"
        mode="widthFix"
      />
    </view>
    <!-- 贵阳老味道 -->
    <!-- <view class="guiyang"></view> -->
    <wd-swiper
      :list="swiperList"
      autoplay
      v-model:current="current"
      @click="handleClick"
      @change="onChange"
      customClass="guiyang"
      height="68"
      imageMode="scaleToFill"
    ></wd-swiper>
    <!-- 附近人气美食 -->
    <view class="nearby">
      <view class="nearby-top">
        <view class="left">
          <image class="tou" src="../../static/index/eat.png" mode="widthFix" />
          <text class="">附近人气美食</text>
        </view>
        <view class="right" @tap="more">
          <text class="">立即查看</text>
          <image class="jian" src="../../static/index/rightJ.png" mode="widthFix" />
        </view>
      </view>
      <view class="nearby-bootom">
        <view
          @click="jumpProductDetails(item)"
          class="contentBox"
          v-for="(item, index) in foodNearbyData"
          :key="index"
        >
          <!-- <image class="img" src="../../static/index/eatFood.png" mode="widthFix" /> -->
          <image class="img" :src="item.shopLogo" mode="aspectFill" />
          <text class="one">{{ item.shopName }}</text>
          <view class="price">
            <text class="two">{{ item.grade }}推荐</text>
            <!-- <text class="three">￥36/人</text> -->
          </view>
          <text class="four" v-show="item.lastBuyTime <= 86400000">
            {{ timeConversion(item.lastBuyTime) }}前有人购买
          </text>
        </view>
      </view>
    </view>
    <!-- 推荐 -->
    <view class="recommend">
      <!-- <view class="tabs"> -->
      <scroll-view class="tabs" scroll-x="true">
        <text
          @tap="choice(index, item.categoryId)"
          v-for="(item, index) in tabsData"
          :key="index"
          class="text"
          :class="light === index ? 'light' : ''"
        >
          {{ item.categoryName }}
        </text>
      </scroll-view>
      <!-- </view> -->
      <view class="recommend-bottom">
        <view class="box" @tap="locationFiltering">
          <text class="text">位置距离</text>
          <wd-icon
            name="fill-arrow-down"
            size="22rpx"
            class="icon"
            :class="{ rotate: rotate }"
          ></wd-icon>
        </view>
        <view class="box">
          <text class="text2">排序筛选</text>
          <wd-icon name="fill-arrow-down" size="22rpx" class="icon2"></wd-icon>
        </view>
      </view>
      <!-- 位置定位 -->
      <Position v-show="rotate" @nearby="nearby" @popular="popular" @region="region" />
    </view>
    <!-- 美食卡片 -->
    <FoodDetails :cardData="cardData" />
    <!-- 店铺卡片推荐 -->
    <ShopCard :shopCardData="shopCardData" />
    <!-- 美食卡片 -->
    <FoodDetails :cardData="cardData1" />
    <!-- 营销模块 -->
    <Marketing />
    <!-- 美食卡片 -->
    <FoodDetails :cardData="cardData2" />
    <view
      style="width: 100%; text-align: center; font-size: 24rpx; margin: 10rpx 0; color: #888989"
      v-if="show"
    >
      没有更多啦~
    </view>
  </view>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { useCountStore } from '@/store';
import Search from '../../components/index/Search.vue';
import FoodDetails from '../../components/index/FoodDetails.vue';
import ShopCard from '../../components/index/ShopCard.vue';
import Marketing from '../../components/index/Marketing.vue';
import Position from '../../components/index/Position.vue';
import { orderStatus } from '../../utils/signIn';
import {
  getTokenUser,
  groupBuyList,
  groupImgList,
  popularityPage,
  getRecommList,
  merchantList,
  couponMainList,
  receiveCoupon,
} from '../../api/index';
import { timeConversion } from '../../utils/tool';
// import testJson from '../../static/json/test.json';
const nowTime = ref(new Date().getTime());
const title = ref('小程序平台');
const { countInfo, addCount } = useCountStore();
// 附近美食
const foodNearbyData = ref([]);
const tabsData = ref([]);
const show = ref(false);
const light = ref(0);
const rotate = ref(false);
const classificationT = ref([
  { img: 'hotPot', text: '火锅' },
  { img: 'barbecue', text: '烧烤烤肉' },
  { img: 'stirFriedDishes', text: '地方菜系' },
  { img: 'hamburg', text: '小吃快餐' },
]);
const classificationB = ref([
  { img: 'seafood', text: '鱼鲜海鲜' },
  { img: 'foreignLand', text: '异域风味' },
  { img: 'selfHelp', text: '自助餐' },
  { img: 'drink', text: '饮品店' },
  { img: 'bread', text: '面包蛋糕' },
]);
const cardData = ref([]);
const cardData1 = ref([]);
const cardData2 = ref([]);
const shopCardData = ref({});
const current = ref(0);
const swiperList = ref(['../../static/index/guiyang.png', '../../static/index/guiyang.png']);
const listParams = {
  current: 1,
  size: 10,
  lon: 106.68650025025502,
  lat: 26.567192352601154,
};
const coupon = ref([]);
let total;
// 轮播图数据
let lunboData;
onMounted(async () => {
  orderStatus();
  getClassification();
  rotatingBroadcast();
  nearbyFood();
  recommendedClassification();
  getMerchantList();
  getCouponMainList();
});

function jumpProductDetails(item) {
  xma.navigateTo({
    url: '/pages/shop/shop?shopId=' + item.shopId,
  });
}
// 登录
// const signIn = () => {
//   getTokenUser(testJson).then((res) => {
//     const token = res.data.access_token;
//     xma.setStorageSync('Authorization', token);
//     console.log('登录...');
//   });
// };
// 搜索
const toSearch = (keyword) => {
  listParams.keyword = keyword;
  getMerchantList();
};
// 获取优惠券
const getCouponMainList = () => {
  couponMainList().then((res) => {
    coupon.value = res.data.records.slice(0, 10);
  });
};
// 领取优惠券
const receive = (data) => {
  if (data.couponType === 'mch' && data.numState === 0) {
    receiveCoupon([data.couponYzfId]).then((res) => {
      // console.log('打印', res);
    });
  }
};
// TO优惠券详情
const toCoupon = () => {
  xma.navigateTo({
    url: '/pages/index/coupon',
  });
};
// 获取分类
const getClassification = () => {
  groupBuyList().then((res) => {
    res.data.forEach((item) => {
      item.icon = import.meta.env.VITE_APP_IMG_URL + item.icon;
      item.pic = import.meta.env.VITE_APP_IMG_URL + item.pic;
    });
    classificationT.value = res.data.slice(0, 4);
    classificationB.value = res.data.slice(4);
  });
};
// 附近人气美食分页
const nearbyFood = () => {
  // xma.getLocation({
  //   isHighAccuracy: true,
  //   success: function (res) {
  //     console.log('经度', res.longitude);
  //     console.log('维度', res.latitude);
  //   },
  //   fail: function (err) {
  //     console.log('获取位置失败：', err);
  //   },
  // });
  const data = {
    current: 1,
    size: 3,
    lon: 106.68650025025502,
    lat: 26.567192352601154,
  };
  popularityPage(data).then((res) => {
    res.data.content.forEach((item) => {
      item.shopLogo = import.meta.env.VITE_APP_IMG_URL + item.shopLogo;
      item.lastBuyTime = new Date().getTime() - new Date(item.lastBuyTime).getTime();
    });
    foodNearbyData.value = res.data.content;
  });
};
// 附近美食查看更多
const more = () => {
  xma.navigateTo({
    url: '/pages/index/listFood?type=2',
  });
};
// 轮播图
const rotatingBroadcast = () => {
  groupImgList().then((res) => {
    res.data.forEach((item) => {
      item.imgUrl = import.meta.env.VITE_APP_IMG_URL + item.imgUrl;
    });
    lunboData = res.data;
    swiperList.value = res.data.map((item) => {
      return item.imgUrl;
    });
  });
};
// 团购主页推荐分类
const recommendedClassification = () => {
  getRecommList().then((res) => {
    tabsData.value = res.data;
    tabsData.value.unshift({ categoryName: '推荐' });
  });
};
// 重置数据
const reset = () => {
  listParams.current = 1;
  shopCardData.value = {};
  cardData.value = [];
  cardData1.value = [];
  cardData2.value = [];
  show.value = false;
};

const toUse = () => {
  xma.navigateTo({
    url: '/pages/index/listFood?type=1',
  });
};
// 商家列表分页-搜索列表
const getMerchantList = () => {
  xma.showLoading({
    title: '加载中',
  });
  merchantList(listParams).then((res) => {
    xma.hideLoading();
    total = res.data.totalElements;
    res.data.content.forEach((item) => {
      item.shopLogo = import.meta.env.VITE_APP_IMG_URL + item.shopLogo;
      if (item.evaluationVos.length > 0) {
        item.simpleProds.forEach((item) => {
          item.avatar = import.meta.env.VITE_APP_IMG_URL + item.avatar;
        });
      }
      if (item.simpleProds.length > 0) {
        item.simpleProds.forEach((item) => {
          item.pic = import.meta.env.VITE_APP_IMG_URL + item.pic;
        });
      }
      if (item.labels) {
        item.labels = item.labels.split(',');
      }
    });
    shopCardData.value = res.data.content[0];
    cardData.value = res.data.content.slice(1, 3);
    cardData1.value = res.data.content.slice(3, 5);
    cardData2.value = res.data.content.slice(5);
  });
};
// 商家列表分页-搜索列表(分页)
const getMerchantListPaging = () => {
  // const data = {
  //   current: 1,
  //   size: 10,
  //   lon: 106.68650025025502,
  //   lat: 26.567192352601154,
  // };
  xma.showLoading({
    title: '加载中',
  });
  merchantList(listParams).then((res) => {
    xma.hideLoading();
    res.data.content.forEach((item) => {
      item.shopLogo = import.meta.env.VITE_APP_IMG_URL + item.shopLogo;
      if (item.evaluationVos.length > 0) {
        item.simpleProds.forEach((item) => {
          item.avatar = import.meta.env.VITE_APP_IMG_URL + item.avatar;
        });
      }
      if (item.simpleProds.length > 0) {
        item.simpleProds.forEach((item) => {
          item.pic = import.meta.env.VITE_APP_IMG_URL + item.pic;
        });
      }
      if (item.labels) {
        item.labels = item.labels.split(',');
      }
    });
    cardData2.value = [...cardData2.value, ...res.data.content];
  });
};
// distance参数来源
const nearby = (distance) => {
  console.log('distance', distance);
  reset();
  if (distance === 0) {
    delete listParams.distance;
  } else {
    listParams.distance = distance;
  }
  getMerchantList();
};
// communityName参数来源
const popular = (communityName) => {
  console.log('communityName', communityName);
  reset();
  listParams.communityName = communityName;
  if (listParams.area) {
    delete listParams.area;
  }
  getMerchantList();
};
// area参数来源
const region = (area) => {
  console.log('area', area);
  reset();
  listParams.area = area;
  if (listParams.communityName) {
    delete listParams.communityName;
  }
  getMerchantList();
};
// tabs
const choice = (index, categoryId) => {
  reset();
  light.value = index;
  listParams.categoryIds = [categoryId];
  if (index === 0) {
    delete listParams.categoryIds;
  }
  getMerchantList();
};
// 金刚区分类选择
const jingang = (id, pic, categoryName) => {
  // switch (index) {
  //   case 0:
  //     xma.navigateTo({
  //       url: '/pages/index/foodClassification',
  //     });
  //     break;
  //   case 1:
  //     xma.navigateTo({});
  //     break;
  //   case 2:
  //     xma.navigateTo({});
  // }
  xma.navigateTo({
    url: `/pages/index/foodClassification?parentId=${id}&pic=${pic}&page=index&categoryName=${categoryName}`,
  });
};
const locationFiltering = () => {
  rotate.value = !rotate.value;
};
const handleClick = (e) => {
  const index = e.index;
  xma.navigateTo({
    url: lunboData[index].link,
  });
};
const onChange = (e) => {
  // console.log(e);
};
// 触底加载
onReachBottom(() => {
  if (cardData2.value.length + 5 < total) {
    listParams.current++;
    getMerchantListPaging();
    return;
  }
  show.value = true;
});
</script>

<style lang="scss" scoped>
page {
  background: #f3f3f3;
}
.container {
  .top {
    width: 100%;
    height: 440rpx;
    background: linear-gradient(180deg, #fa5151 0%, rgba(243, 243, 243, 0) 100%);
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    overflow: hidden;
    .food {
      width: 178rpx;
      height: 45rpx;
      margin-left: 25rpx;
    }
    .classification {
      width: 710rpx;
      height: 304rpx;
      background: rgba(255, 255, 255, 0.94);
      border-radius: 16rpx 16rpx 16rpx 16rpx;
      margin: 0 auto;
      margin-top: 10rpx;
      overflow: hidden;
      box-sizing: border-box;
      .classification-top {
        display: flex;
        justify-content: space-evenly;
        margin-top: 32rpx;
        .choice {
          display: flex;
          flex-direction: column;
          align-items: center;
          font-size: 24rpx;
          color: #3d3d3d;
          font-weight: 500;
          font-family:
            Source Han Sans,
            Source Han Sans;
          .imgs {
            width: 88rpx;
          }
        }
      }
      .classification-bottom {
        display: flex;
        justify-content: space-evenly;
        margin-top: 34rpx;
        .choice {
          display: flex;
          flex-direction: column;
          align-items: center;
          font-size: 18rpx;
          color: #3d3d3d;
          justify-content: flex-end;
          font-family:
            Source Han Sans,
            Source Han Sans;
          .imgs {
            width: 68rpx;
            margin-bottom: 8rpx;
          }
        }
      }
    }
  }
  .redEnvelope {
    width: 710rpx;
    height: 172rpx;
    background: #ffffff;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    box-sizing: border-box;
    margin: 0 auto;
    margin-top: 12rpx;
    overflow: hidden;
    position: relative;
    .title {
      font-family: YouSheBiaoTiHei, YouSheBiaoTiHei;
      font-weight: bold;
      font-size: 28rpx;
      color: #3d3d3d;
      line-height: 28rpx;
      text-shadow: 2px 2px 0px rgba(255, 255, 255, 0.36);
      text-transform: none;
      margin: 10rpx 0 0 20rpx;
    }
    .box-red {
      padding: 10rpx 0 0 20rpx;
      box-sizing: border-box;
      white-space: nowrap;
      width: 80%;
      .redBagBox {
        margin-right: 8rpx;
        width: 124rpx;
        height: 104rpx;
        background: url('../../static/index/redBag.png') no-repeat;
        background-size: 100% 100%;
        flex-direction: column;
        align-items: center;
        display: inline-flex;
        position: relative;
        box-sizing: border-box;
        // overflow: hidden;
        // justify-content: space-evenly;
        .content {
          height: 70%;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          .textO {
            width: 124rpx;
            font-size: 12rpx;
            color: #fa5151;
            text-align: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .textW {
            font-size: 24rpx;
            color: #fa5151;
            font-weight: 600;
            font-family: Alimama FangYuanTi VF;
            // margin-top: 5rpx;
          }
        }
        .textF {
          width: 56rpx;
          height: 20rpx;
          background: linear-gradient(180deg, #ffe7d1 0%, #ffc893 100%, #f1ba84 100%);
          border-radius: 10rpx;
          font-size: 12rpx;
          color: #fa5151;
          text-align: center;
          position: absolute;
          line-height: 20rpx;
          bottom: 8rpx;
        }
      }
    }
    .discount {
      position: absolute;
      right: 0;
      top: 0;
      width: 208rpx;
      z-index: 99;
    }
  }
  .guiyang {
    width: 710rpx;
    margin: 0 auto;
    margin-top: 10rpx;
  }
  .nearby {
    width: 710rpx;
    height: 380rpx;
    border-radius: 16rpx;
    background: #ffffff;
    margin: 0 auto;
    box-sizing: border-box;
    overflow: hidden;
    padding-top: 20rpx;
    .nearby-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0 20rpx;
      .left {
        display: flex;
        align-items: center;
        font-size: 28rpx;
        font-family:
          Source Han Sans,
          Source Han Sans;
        font-weight: 500;
        .tou {
          width: 24rpx;
          margin-right: 12rpx;
        }
      }
      .right {
        display: flex;
        align-items: center;
        font-size: 20rpx;
        color: #abaaaa;
        font-family:
          Source Han Sans,
          Source Han Sans;
        font-weight: 400;
        .jian {
          width: 20rpx;
          margin-left: 8rpx;
        }
      }
    }
    .nearby-bootom {
      margin-top: 20rpx;
      display: flex;
      padding: 0 20rpx;
      box-sizing: border-box;
      overflow: hidden;
      justify-content: space-between;
      .contentBox {
        width: 220rpx;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        .img {
          height: 160rpx;
          width: 220rpx;
          border-radius: 16rpx;
        }
        .one {
          font-size: 28rpx;
          font-weight: bold;
          color: #3d3d3d;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          width: 100%;
        }
        .price {
          .two {
            font-size: 24rpx;
            color: #fa5151;
            font-weight: bold;
          }
          .three {
            font-size: 20rpx;
            color: #abaaaa;
            margin-left: 8rpx;
          }
        }
        .four {
          font-size: 20rpx;
          color: #abaaaa;
        }
      }
    }
  }
  .recommend {
    width: 710rpx;
    height: 140rpx;
    border-radius: 16rpx 16rpx 0rpx 0rpx;
    background: #ffffff;
    box-shadow: 0rpx 4rpx 16rpx 0rpx rgba(0, 0, 0, 0.08);
    margin: 0 auto;
    margin-top: 10rpx;
    position: sticky;
    top: 0;
    z-index: 99;
    uni-scroll-view .uni-scroll-view::-webkit-scrollbar {
      /* 隐藏滚动条，但依旧具备可以滚动的功能 */
      display: none;
      width: 0 !important;
      height: 0 !important;
      -webkit-appearance: none;
      background: transparent;
      color: transparent;
    }
    .tabs {
      padding-top: 20rpx;
      white-space: nowrap;
      height: 60rpx;
      .text {
        font-size: 24rpx;
        color: #d8d8d8;
        margin: 0 20rpx;
        font-weight: bold;
        display: inline-block;
      }
      .text:nth-child(1) {
        margin-left: 40rpx;
      }
      .light {
        background: linear-gradient(241deg, #ff8f1f -7%, #fa5151 93%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        text-fill-color: transparent;
        position: relative;
        &::after {
          content: '';
          width: 20rpx;
          height: 12rpx;
          background: url('../../static/index/subscript.png') no-repeat;
          background-size: 100% 100%;
          position: absolute;
          bottom: -16rpx;
          left: 50%;
          transform: translate(-50%);
        }
      }
    }
    .recommend-bottom {
      display: flex;
      padding: 0 40rpx;
      box-sizing: border-box;
      justify-content: space-between;
      align-items: center;
      margin-top: 20rpx;
      .box {
        display: flex;
        align-items: center;
        .text {
          font-size: 24rpx;
          color: #3d3d3d;
        }
        .text2 {
          font-size: 24rpx;
          color: #908f8f;
        }
        .icon {
          transform: rotate(-180deg);
          transition: all 0.3s linear;
        }
        .rotate {
          transform: rotate(0deg);
          transition: all 0.3s linear;
        }
        .icon2 {
          transform: rotate(180deg);
          color: #908f8f;
        }
      }
    }
  }
}
</style>
