<template>
  <div class="container" style="padding-bottom: 10rpx">
    <view class="bg-img"></view>
    <view class="top">
      <!-- 搜索 -->
      <Search @toSearch="toSearch">
        <text class="title-icon">{{ categoryNames }}</text>
        <!-- <image class="food" :src="pics" mode="widthFix" /> -->
      </Search>
      <!-- 类别选择 -->
      <scroll-view
        v-if="topDiscountedProducts.length > 0"
        class="scroll-x"
        scroll-x="true"
        @scroll="scroll"
      >
        <view
          @click="jumpProductDetails(item.prodId)"
          class="foodCard"
          v-for="(item, index) in topDiscountedProducts"
          :key="index"
        >
          <view class="test5">
            <image class="img1" :src="imgUrl + item.pic" />
            <image class="img2" src="../../static/index/icon-tab.png" />
          </view>
          <view class="content">
            <text class="title">{{ item.prodName }}</text>
            <view class="labelBox">
              <view class="item" v-for="(lab, index) in item.labels" :key="index">{{ lab }}</view>
              <view
                style="background: transparent"
                class="item"
                v-if="!item.labels || item.labels.length === 0"
              ></view>
            </view>
            <view class="price">
              <!-- <view class="discounts">4.5折</view> -->
              <text class="text">￥{{ item.price }}</text>
              <text class="text2">￥{{ item.oriPrice }}</text>
              <view class="btn">
                <!-- <text class="text3">仅剩余5张</text> -->
                <text class="text3">立即抢购</text>
                <!-- <image class="qiang" src="../../static/index/qiang.png" mode="widthFix" /> -->
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="bootom">
      <view class="bootom-top">
        <view class="option" @tap="locationFiltering(0)">
          <text :class="{ rotate: rotate }">全部{{ categoryNames }}</text>
          <wd-icon
            :class="{ rotate: rotate }"
            name="fill-arrow-down"
            size="24rpx"
            class="icon"
          ></wd-icon>
        </view>
        <view class="option" @tap="locationFiltering(1)">
          <text :class="{ rotate: rotate2 }">附近</text>
          <wd-icon
            :class="{ rotate: rotate2 }"
            name="fill-arrow-down"
            size="24rpx"
            class="icon"
          ></wd-icon>
        </view>
        <view class="option" @tap="locationFiltering(2)">
          <text :class="{ rotate: rotate3 }">智能排序</text>
          <wd-icon
            :class="{ rotate: rotate3 }"
            name="fill-arrow-down"
            size="24rpx"
            class="icon"
          ></wd-icon>
        </view>
      </view>
      <!-- <view class="bootom-bottom">
        <view
          @tap="choice(index)"
          class="item"
          :class="{ light: active === index }"
          v-for="(item, index) in business"
          :key="index"
        >
          {{ item }}
        </view>
      </view> -->
      <!-- 美食类别 -->
      <Classification v-show="rotate" :category="categoryData" @foodCategory="foodCategory" />
      <!-- 附近筛选 -->
      <Position
        v-show="rotate2"
        @nearby="nearby"
        @popular="popular"
        @region="region"
        @refresh="refreshList"
      />
      <!-- 排序筛选 -->
      <Sort v-show="rotate3" @sortParams="sortParams" />
    </view>
    <FoodDetails :cardData="cardData" />
    <wd-status-tip v-if="cardData.length === 0" image="content" tip="暂无内容" />
    <view
      style="width: 100%; text-align: center; font-size: 24rpx; margin-top: 10rpx; color: #888989"
      v-if="params.isEnd"
    >
      没有更多啦~
    </view>
  </div>
</template>

<script setup>
import FoodDetails from '../../components/index/FoodDetails.vue';
import Search from '../../components/index/Search.vue';
import Classification from '../../components/index/Classification.vue';
import Position from '../../components/index/Position.vue';
import Sort from '../../components/index/Sort.vue';
import { getByParentId, merchantList, prodSpecial } from '../../api/index';

const isLoadReachBottom = ref(null);
const imgUrl = import.meta.env.VITE_APP_IMG_URL;
const business = reactive(['优选商家', '超值半价', '今日可订', '经典单人']);
const active = ref(null);
const categoryNames = ref('');
const categoryData = ref([]);
const rotate = ref(false);
const rotate2 = ref(false);
const rotate3 = ref(false);
const categoryId = ref(null);
const topDiscountedProducts = ref([]);
const params = ref({
  current: 1,
  size: 15,
  // lon,
  // lat,
  lon: '',
  lat: '',
  isEnd: false,
});
const pics = ref(null);
onLoad((option) => {
  const { parentId, pic, categoryName } = option;
  categoryNames.value = categoryName;
  categoryId.value = parentId;
  params.value.categoryIds = [parentId];
  pics.value = pic;
  query(parentId);
  prodSpecialFn();
  getLocationFn().then((res) => {
    getMerchantList();
  });
});
// distance参数来源
const nearby = (distance) => {
  console.log('distance', distance);
  if (distance === 0) {
    delete params.value.distance;
  } else {
    params.value.distance = distance;
  }
  refresh().then(() => {
    getMerchantList();
  });
};
function refreshList() {
  delete params.value.distance;
  delete params.value.area;
  delete params.value.communityName;
  params.value.isEnd = false;
  params.value.current = 1;
  setTimeout(() => {
    rotate2.value = false;
  }, 400);
  getMerchantList();
}
// communityName参数来源
const popular = (communityName) => {
  params.value.communityName = communityName;
  if (params.value.area) {
    delete params.value.area;
  }
  refresh().then(() => {
    getMerchantList();
  });
};
// 搜索
const toSearch = (keyword) => {
  params.value.keyword = keyword;
  refresh().then(() => {
    getMerchantList();
  });
};
// 排序参数来源
const sortParams = (sortType) => {
  const { sortName, sortMode } = sortType;
  params.value.sortName = sortName;
  params.value.sortMode = sortMode;
  refresh().then(() => {
    getMerchantList();
  });
};
// area参数来源
const region = (area) => {
  console.log('area', area);
  params.value.area = area;
  if (params.value.communityName) {
    delete params.value.communityName;
  }
  refresh().then(() => {
    getMerchantList();
  });
};
onReachBottom(() => {
  console.log('到底了');
  if (isLoadReachBottom.value === true) return;
  isLoadReachBottom.value = true;
  getMerchantList().then(() => {
    isLoadReachBottom.value = false;
  });
});
// categoryId参数来源
const foodCategory = (categoryId) => {
  params.value.categoryIds = [categoryId];
  refresh().then(() => {
    getMerchantList();
  });
};
/**
 * @description: 刷新
 */
function refresh() {
  return new Promise((resolve, reject) => {
    cardData.value = [];
    params.value.current = 1;
    params.value.isEnd = false;
    resolve();
  });
}
onPullDownRefresh(() => {
  refresh().then(() => {
    getMerchantList().then(() => {
      xma.stopPullDownRefresh();
    });
  });
});
// 根据父级分类id查询子分类列表
const query = (parentId) => {
  getByParentId(parentId).then((res) => {
    categoryData.value = res.data;
  });
};
function jumpProductDetails(prodId) {
  xma.navigateTo({
    url: `/pages/packageDetails/packageDetails?prodId=${prodId}`,
    params: {
      productId: 123,
    },
  });
}
const prodSpecialFn = () => {
  prodSpecial({ categoryId: categoryId.value }).then((res) => {
    if (res.data.data) {
      res.data.data = res.data.data.map((el) => {
        if (el.labels && el.labels !== '') {
          el.labels = el.labels.split(',');
        }
        return el;
      });
      topDiscountedProducts.value = res.data.data;
    }
  });
};
const choice = (index) => {
  active.value = index;
};
const cardData = ref([]);

const locationFiltering = (index) => {
  switch (index) {
    case 0:
      rotate.value = !rotate.value;
      rotate2.value = false;
      rotate3.value = false;
      break;
    case 1:
      rotate2.value = !rotate2.value;
      rotate.value = false;
      rotate3.value = false;
      break;
    case 2:
      rotate3.value = !rotate3.value;
      rotate.value = false;
      rotate2.value = false;
      break;
  }
};
// 商家列表分页-搜索列表
const getMerchantList = () => {
  if (params.value.isEnd === true)
    return new Promise((resolve) => {
      resolve();
    });
  xma.showLoading({
    title: '加载中...',
    mask: true,
  });
  return merchantList(params.value).then((res) => {
    if (res.data.content.length < params.value.size) {
      params.value.isEnd = true;
    }
    params.value.current += 1;
    res.data.content.forEach((item) => {
      item.shopLogo = import.meta.env.VITE_APP_IMG_URL + item.shopLogo;
      if (item.evaluationVos.length > 0) {
        item.evaluationVos[0].avatar =
          import.meta.env.VITE_APP_IMG_URL + item.evaluationVos[0].avatar;
      }
      if (item.labels) {
        item.labels = item.labels.split(',');
      }
    });
    cardData.value = cardData.value.concat(res.data.content);
    xma.hideLoading();
  });
};
function getLocationFn() {
  return new Promise((resolve, reject) => {
    xma.getLocation({
      type: 'wgs84',
      isHighAccuracy: true,
      success: function (res) {
        params.value.lat = res.latitude;
        params.value.lon = res.longitude;
        // 经纬度
        resolve({ lat: res.latitude, lon: res.longitude });
      },
      fail: function (err) {
        return err;
      },
    });
  });
}
</script>

<style lang="scss" scoped>
page {
  background: #f3f3f3;
}
.container {
  .bg-img {
    width: 100%;
    height: 440rpx;
    background: url('../../static/index/barbecueBg.png') no-repeat;
    background-size: 100% 100%;
    position: absolute;
    top: 0;
  }
  .top {
    width: 100%;
    min-height: 420rpx;
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    overflow: hidden;
    .title-icon {
      font-family: 'YSBTH';
      font-size: 24 * 2rpx;
      margin-left: 30rpx;
      color: #ffffff;
    }
    .food {
      width: 178rpx;
      height: 45rpx;
      margin-left: 25rpx;
    }
    .scroll-x {
      padding-top: 26rpx;
      white-space: nowrap;
      width: 100%;
      .foodCard {
        width: 536rpx;
        height: 516rpx;
        border-radius: 16rpx;
        background: #ffffff;
        margin-left: 20rpx;
        display: inline-block;
        box-sizing: border-box;
        overflow: hidden;
        .test5 {
          width: 100%;
          height: 168 * 2rpx;
          position: relative;
          .img1 {
            width: 100%;
            height: 168 * 2rpx;
            position: absolute;
            top: 0;
            left: 0;
          }
          .img2 {
            width: 100%;
            position: absolute;
            left: 0;
            bottom: 0;
            height: 56rpx;
          }
        }
        .content {
          display: flex;
          flex-direction: column;
          box-sizing: border-box;
          .title {
            font-size: 24rpx;
            color: #3d3d3d;
            font-weight: bold;
            margin-left: 10rpx;
            margin-top: 8rpx;
          }
          .labelBox {
            display: flex;
            margin-left: 20rpx;
            align-items: center;
            margin-top: 16rpx;
            .item {
              width: 100rpx;
              height: 36rpx;
              border-radius: 6rpx;
              background: #fcdbdb;
              font-size: 20rpx;
              color: #fa5151;
              text-align: center;
              line-height: 36rpx;
              margin-right: 8rpx;
            }
          }
          .price {
            display: flex;
            align-items: center;
            padding-left: 20rpx;
            margin-top: 16rpx;
            .discounts {
              width: 56rpx;
              height: 36rpx;
              border-radius: 6rpx 6rpx 0rpx 6rpx;
              background: #fa5151;
              color: #ffffff;
              font-size: 20rpx;
              text-align: center;
              line-height: 36rpx;
            }
            .text {
              font-size: 28rpx;
              color: #fa5151;
              font-weight: bold;
              margin-left: 12rpx;
            }
            .text2 {
              text-decoration: line-through;
              font-size: 22rpx;
              margin-left: 12rpx;
              color: #abaaaa;
            }
            .btn {
              position: relative;
              min-width: 224rpx;
              height: 48rpx;
              border-radius: 10rpx;
              background: #fcdbdb;
              box-sizing: border-box;
              margin-left: auto;
              margin-right: 20rpx;
              display: flex;
              justify-content: center;
              align-items: center;
              .text3 {
                font-size: 20rpx;
                color: #fa5151;
                line-height: 47rpx;
                text-align: center;
                margin-left: 14rpx;
              }
              .qiang {
                width: 94rpx;
                position: absolute;
                right: 0;
              }
            }
          }
        }
      }
    }
  }
  .bootom {
    position: sticky;
    top: 0;
    height: 70rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    border-radius: 6rpx;
    background: #ffffff;
    margin-top: 10rpx;
    margin-bottom: 20rpx;
    z-index: 999;
    .bootom-top {
      display: flex;
      align-items: center;
      padding: 0 20rpx;
      justify-content: space-between;
      .option {
        text {
          font-size: 24rpx;
          color: #343434;
        }
        .red {
          color: #fa5151;
        }
        .icon {
          color: #d8d8d8;
          transform: rotate(-180deg);
          transition: all 0.3s linear;
        }
        .rotate {
          transform: rotate(0deg);
          transition: all 0.3s linear;
          color: #fa5151;
        }
      }
    }
    .bootom-bottom {
      display: flex;
      align-items: center;
      padding-left: 40rpx;
      .item {
        height: 36rpx;
        width: 96rpx;
        border-radius: 6rpx;
        font-size: 20rpx;
        text-align: center;
        line-height: 36rpx;
        color: #abaaaa;
        background: #eeeeee;
        margin-right: 20rpx;
      }
      .light {
        color: #ff7c00;
        background: #ffdcbb;
      }
    }
  }
}
</style>
