<template>
  <view class="container" :style="appThemeStyle">
	<!-- 店招 -->
	<shop-banner :shop="shop" @onFollow="onFollow" @event="onSearch" />
    <!-- 一级分类 -->
    <primary v-if="setting.style == PageCategoryStyleEnum.ONE_LEVEL_BIG.value || setting.style == PageCategoryStyleEnum.ONE_LEVEL_SMALL.value"
      :display="setting.style" :list="list" />

    <!-- 二级分类 -->
    <secondary v-if="setting.style == PageCategoryStyleEnum.TWO_LEVEL.value" :list="list" />

    <!-- 分类+商品 -->
    <commodity v-if="setting.style == PageCategoryStyleEnum.COMMODITY.value" ref="mescrollItem" :equipmentName="searchValue" :list="list" :shopId="shopId" :setting="setting" @addCart="onRefreshPage"/>
	
	<!-- 底部选项卡 -->
	<view class="footer-fixed" style="display: none;">
	  <view class="footer-container">
	    <!-- 导航图标 -->
	    <view class="foo-item-fast">
	      <!-- 首页 -->
	      <view class="fast-item fast-item--home" @click="onTargetHome">
	        <view class="fast-icon">
	          <text class="iconfont icon-shouye"></text>
	        </view>
	        <view class="fast-text">
	          <text>首页</text>
	        </view>
	      </view>
	      <!-- 客服 (仅微信小程序端显示) -->
	      <!-- #ifdef MP-WEIXIN -->
	      <button class="btn-normal" open-type="contact">
	        <view class="fast-item">
	          <view class="fast-icon">
	            <text class="iconfont icon-kefu1"></text>
	          </view>
	          <view class="fast-text">
	            <text>客服</text>
	          </view>
	        </view>
	      </button>
	      <!-- #endif -->
	      <!-- 购物车 -->
	      <view class="fast-item fast-item--cart" @click="onTargetCart">
	        <view v-if="cartTotal > 0" class="fast-badge fast-badge--fixed">{{ cartTotal > 99 ? '99+' : cartTotal }}
	        </view>
	        <view class="fast-icon">
	          <text class="iconfont icon-gouwuche"></text>
	        </view>
	        <view class="fast-text">
	          <text>购物车</text>
	        </view>
	      </view>
	    </view>
	    <!-- 操作按钮 -->
	    <view class="foo-item-btn">
	      <view class="btn-wrapper">
	        <view class="btn-item btn-item-main" @click="onTargetCart(3)">
	          <text>去结算</text>
	        </view>
	      </view>
	    </view>
	  </view>
	</view>
  </view>
</template>

<script>
  import MescrollCompMixin from '@/components/mescroll-uni/mixins/mescroll-comp'
  import { setCartTabBadge } from '@/core/app'
  import SettingKeyEnum from '@/common/enum/setting/Key'
  import { PageCategoryStyleEnum } from '@/common/enum/store/page/category'
  import SettingModel from '@/common/model/Setting'
  import * as CategoryApi from '@/api/category'
  import * as EquipmentApi from '@/api/equipment'
  import * as CartApi from '@/api/cart'
  import * as ShopApi from '@/api/shop.js'
  import Empty from '@/components/empty'
  import Search from './components/search'
  import ShopBanner from './components/shop-banner'
  import Primary from './components/primary'
  import Secondary from './components/secondary'
  import Commodity from './components/commodity'
  import storage from '@/utils/storage'

  // 最后一次刷新时间
  let lastRefreshTime;

  export default {
    components: {
      Search,
      Empty,
      Primary,
      Secondary,
      Commodity,
	  ShopBanner
    },
    mixins: [MescrollCompMixin],
    data() {
      return {
		// 店铺信息
		shop: {},
		// 店铺ID
		shopId: null,
        // 枚举类
        PageCategoryStyleEnum,
        // 分类列表
        list: [],
        // 分类模板设置
        setting: {},
        // 正在加载中
        isLoading: true,
		
		// 购物车总数量
		cartTotal: 0,
		// 显示/隐藏SKU弹窗
		showSkuPopup: false,
		// 模式 1:都显示 2:只显示购物车 3:只显示立即购买
		skuMode: 1,
		// 显示/隐藏分享菜单
		showShareSheet: false,
		// 获取商品海报图api方法
		posterApiCall: EquipmentApi.poster,
		// 搜索关键词
		searchValue: '',
		// 刷新组件
		isRefresh: true
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad({ shopId }) {
	  // 店铺ID
	  this.shopId = parseInt(shopId),
      // 加载页面数据
      this.onRefreshPage()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      // 每间隔5分钟自动刷新一次页面数据
      const curTime = new Date().getTime()
      if ((curTime - lastRefreshTime) > 5 * 60 * 1000) {
        this.onRefreshPage()
      }
    },
	watch: {
		searchValue(val){
			this.searchValue = val
			this.$navTo('pages/search/index')
		}
	},
    methods: {

      // 刷新页面
      onRefreshPage() {
        // 记录刷新时间
        lastRefreshTime = new Date().getTime()
        // 获取页面数据
        this.getPageData()
        // 更新购物车角标
        setCartTabBadge()
      },
	  
	  // 关注
	  onFollow(shopId){
		  ShopApi.setFollow({shopId}).then(res => {
			  this.getPageData()
		  })
	  },

      // 获取页面数据
      getPageData() {
        const app = this
		const equipmentName = storage.get('shopSearchValue')
        app.isLoading = true
        Promise.all([
            // 获取分类模板设置
            // 优化建议: 可以将此处的false改为true 启用缓存
            SettingModel.data(true),
            // 获取分类列表
            CategoryApi.list({shopId:app.shopId,equipmentName}),
			// 店铺信息
			ShopApi.detail(app.shopId)
          ])
          .then(result => {
            // 初始化分类模板设置
            app.initSetting(result[0])
            // 初始化分类列表数据
            app.initCategory(result[1])
			// 更新购物车角标
			app.getCartTotal()
			// 初始化店铺信息
            app.initShop(result[2])
			// 刷新子组件
			app.isRefresh = true
          })
          .finally(() => app.isLoading = false)
      },

      /**
       * 初始化分类模板设置
       * @param {Object} result
       */
      initSetting(setting) {
        this.setting = setting[SettingKeyEnum.PAGE_CATEGORY_TEMPLATE.value]
      },

      /**
       * 初始化分类列表数据
       * @param {Object} result
       */
      initCategory(result) {
        this.list = result.data.list
      },
	  
	  /**
	   * 初始化店铺信息
	   * @param {Object} result
	   */
	  initShop(result){
		  this.shop = result.data.detail
	  },
	  
	  // 获取购物车总数量
	  getCartTotal() {
	    const app = this
	    return new Promise((resolve, reject) => {
	      CartApi.total()
	        .then(result => {
	          app.cartTotal = result.data.cartTotal
	          resolve(result)
	        })
	        .catch(reject)
	    })
	  },
	  
	  // 更新购物车数量
	  onAddCart(total) {
	    this.cartTotal = total
	  },
	  
	  /**
	   * 显示/隐藏SKU弹窗
	   * @param {skuMode} 模式 1:都显示 2:只显示购物车 3:只显示立即购买
	   */
	  onShowSkuPopup(skuMode = 1) {
	    this.skuMode = skuMode
	    this.showSkuPopup = !this.showSkuPopup
	  },
	  
	  // 搜索
	  onSearch(searchValue){
		  this.searchValue = searchValue
	  },
	  
	  // 跳转到首页
	  onTargetHome(e) {
	    this.$navTo('pages/index/index')
	  },
	  
	  // 跳转到购物车页
	  onTargetCart() {
	    this.$navTo('pages/cart/index')
	  },

    },

    /**
     * 设置分享内容
     */
    onShareAppMessage() {
      const app = this
      return {
        title: _this.templet.shareTitle,
        path: '/pages/category/index?' + app.$getShareUrlParams()
      }
    },

    /**
     * 分享到朋友圈
     * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
     */
    onShareTimeline() {
      const app = this
      return {
        title: _this.templet.shareTitle,
        path: '/pages/category/index?' + app.$getShareUrlParams()
      }
    }
  }
</script>

<style>
  page {
    background: #fff;
  }
</style>
<style lang="scss" scoped>
	@import "./index.scss";
  // 搜索框
  .search {
    position: fixed;
    top: var(--window-top);
    left: var(--window-left);
    right: var(--window-right);
    z-index: 9;
	top: 200rpx;
    padding-bottom: 20rpx;
  }

</style>