<template>
  <view>
    <u-navbar :border-bottom="false" back-icon-color="#000000" :background="{ background: '#ffffff' }">
      <view class="w-full">
        <u-search placeholder="搜索商品" @change="Change" @search="Search" v-model="searchText" :show-action="false"></u-search>
      </view>
      <view slot="right" class="pr-26rpx pl-14rpx flex items-center" @tap="$u.route('/pageB/select_product/cart', { mid })">
        <image class="w-48rpx h-48rpx" src="/static/images/cart/short-cart.png" mode="scaleToFill" />
      </view>
    </u-navbar>
    <!-- tabs -->
    <view class="fixed left-0 right-0 z-8 text-txGray text-lg w-full bg-white h-90rpx shadow-down flex items-center justify-around">
      <view @tap.stop="handType('')" :class="!sort ? 'text-primary' : ''">综合</view>
      <view @tap.stop="onPriceSort" class="flex items-center" :class="sort == 'price' || sort == '-price' ? 'text-primary' : ''">
        <view>价格</view>
        <view>
          <trigonometry :key="'a' + key" direction="up" :color="sort == 'price' ? '#378264' : '#808080'"></trigonometry>
          <trigonometry :key="'b' + key" direction="down" :color="sort == '-price' ? '#378264' : '#808080'"></trigonometry>
        </view>
      </view>
      <view @tap.stop="onSaleSort" :class="sort == 'sales' || sort == '-sales' ? 'text-primary' : ''" class="flex items-center">
        <view>销量</view>
        <view class="flex items-center justify-center flex-col ml-5rpx">
          <trigonometry :key="'c' + key" direction="up" :color="sort == 'sales' ? '#378264' : '#808080'"></trigonometry>
          <trigonometry :key="'d' + key" direction="down" :color="sort == '-sales' ? '#378264' : '#808080'"></trigonometry>
        </view>
      </view>
      <view @tap.stop="handType('release_at')" :class="sort == 'release_at' ? 'text-primary' : ''">上新</view>
    </view>
    <mescroll-body
      top="90"
      :height="height"
      ref="mescrollRef"
      @init="mescrollInit"
      @down="downCallback"
      @up="upCallback"
      :down="downOption"
      :up="upOption"
    >
      <view class="px-rowSm mt-20rpx">
        <u-waterfall v-model="dataList" ref="uWaterfall">
          <template v-slot:left="{ leftList }">
            <view v-for="(item, index) in leftList" :key="index" class="px-rowSm mb-base">
              <goods-item :goods="item" :detail="false" cart @cartClick="cartClick"></goods-item>
            </view>
          </template>
          <template v-slot:right="{ rightList }">
            <view v-for="(item, index) in rightList" :key="index" class="px-rowSm mb-base">
              <goods-item :goods="item" :detail="false" cart @cartClick="cartClick"></goods-item>
            </view>
          </template>
        </u-waterfall>
      </view>
    </mescroll-body>

    <!-- 规格弹窗 -->
    <spec-popup
      :key="productId"
      :loading="loading"
      :specs="specs"
      :sku="sku"
      v-model="show"
      :quota-used="number"
      :show-cart="popupType == 1 || popupType == 0"
      :show-buy="popupType == 2 || popupType == 0"
      :show-confirm="popupType == 3"
      @add-cart="onAddCart"
      @stepper-change="onChangeNumber"
      @sku-selected="handleSkuSelect"
    >
    </spec-popup>

    <u-mask :show="loading">
      <view style="display: flex; justify-content: center; align-items: center; height: 100%">
        <text style="color: white">加载中</text>
        <u-loading mode="flower" size="60" />
      </view>
    </u-mask>
  </view>
</template>

<script>
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js';
export default {
  mixins: [MescrollMixin],
  data() {
    return {
      mid: '',// 店铺 id
      category: '',// 分类 id
      searchText: '',// 搜索关键字
      sku: {},// 当前选择的sku
      key: 0,
      sort: '', //price 价格，sales 销量，release_at 上架时间。示例：price 按价格升序，-price 按价格降序
      loading: false,
      popupType: 1,
      number: 1,
      products: {},
      productId: '',
      skuId: '',
      downOption: {
        auto: false,
      },
      upOption: {
        page: {
          size: 20,
        },
        noMoreSize: 1,
      },
      show: false,
      dataList: [], //获取到的数据
    };
  },
  computed: {
    specs() {
      return this.products?.spu_specs ?? [];
    },
    height() {
      const { windowHeight, statusBarHeight } = this.$u.sys();
      return windowHeight - statusBarHeight - 44 + 'px';
    },
  },
  onLoad(e) {
    this.searchText = e.keywords;
    this.category = e.cid;
    this.mid = e.mid;
  },
  methods: {
    Change(e) {
      if (e == '') uni.navigateBack();
    },
    Search() {
      this.category = '';
      this.downCallback();
    },
    onChangeNumber(e) {
      this.number = e;
    },
    // 点击购物车图标
    async cartClick(e) {
      this.productId = e.id;
      this.number = 1;
      await this.getProducts();
      this.show = true;
    },
    // 添加购物车
    onAddCart(e) {
      this.$store.dispatch('storeCart/add', { id: e.id, number: this.number }).then(res => {
        this.$u.toast('添加成功')
        this.show = false
      })
    },
    //获取商品详情
    async getProducts() {
      try {
        this.loading = true;
        const resData = await this.$api.get(`/v1/store/${this.mid}/product-spu/${this.productId}`);
        this.products = resData;
        this.skuId = this.products?.sku.id;
        this.sku = this.products?.sku
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    downCallback() {
      this.dataList = [];
      this.$refs.uWaterfall.clear();
      this.mescroll.resetUpScroll();
    },
    async upCallback(page) {
      this.loadData(page);
    },
    loadData(page) {
      let params = {
        page: page.num,
        per_page: page.size,
        category: this.category,
        keyword: this.searchText,
        sort: this.sort,
      };
      let url = this.mid ? `/v1/store/${this.mid}/product-spus` : `/v1/product/products`
      this.$api.get(url, { params })
        .then((res) => {
          this.mescroll.endSuccess(res.data.length);
          if (page.num == 1) this.dataList = [];
          this.dataList = this.dataList.concat(res.data);
        })
        .catch((err) => {
          this.mescroll.endErr();
        });
    },
    //筛选
    handType(val) {
      if (this.sort == val) return;
      this.$u.throttle(() => {
        this.sort = val;
        this.downCallback();
      });
    },
    //价格排序
    onPriceSort() {
      this.Refresh();
      this.sort = this.sort == 'price' ? '-price' : 'price';
      this.downCallback();
    },
    //销量排序
    onSaleSort() {
      this.Refresh();
      this.sort = this.sort == 'sales' ? '-sales' : 'sales';
      this.downCallback();
    },
    //刷新子组件
    Refresh() {
      this.$nextTick(() => {
        this.key++;
      });
    },
    // 选择sku, 更新价格
    handleSkuSelect(e) {
      this.skuId = e.sku_id
      this.$api.get(`/v1/store/${this.mid}/product-sku/${e.sku_id}`).then(res => {
        this.sku = res
      })
    }
  },
};
</script>

<style lang="scss"></style>
