<template>
  <div class="shop-good">
    <!-- 顶部检索 -->
    <div class="top">
      <!-- #ifdef MP-WEIXIN -->
      <MaterialInfo v-if="isMaterial && !isPurchase"></MaterialInfo>
      <!-- <div >
        <input v-model="searchKeyword" placeholder="请输入商品名称" @blur="changeKeyword" style="border:1rpx solid #eee;height: 70rpx;" />
      </div> -->
      <!-- v-else -->
      <SearchBtn v-else @click="handleClickSearch"></SearchBtn>
      <!-- #endif -->

      <!-- 搜索商品 -->
      <!-- #ifndef MP-WEIXIN -->

      <SearchBtn @click="handleClickSearch"></SearchBtn>
      <!-- #endif -->
    </div>
    <!-- 左侧菜单 style="margin-top:70rpx"-->
    <div class="flex-content" >
      <div class="left">
        <LeftCat ref="leftCat" :catL1="catL1" :current="catID1" @catChange="catChange"></LeftCat>
      </div>
      <div class="right">
        <!-- 顶部二级分类 -->
        <div class="top2">
          <TopCat ref="cat2Top" :cats="catL2filter" :current="catID2" @cat2Change="cat2Change" :up="wallShow" @toggleCat2="toggleCat2"></TopCat>
        </div>
        <!-- 二级分类选择面板 -->
        <div class="pick-cat2" v-if="wallShow">
          <div class="pick-cat2-top">
            <CatsWall :cats="catL2filter" :current="catID2" @clickCat2="clickCat2"></CatsWall>
          </div>
          <div class="pick-cat2-mask" @touchmove.stop.prevent @click="closeWall"></div>
        </div>
        <!-- 中间商品 -->
        <div class="goods-wrapper">
          <div class="content" @touchmove="touchmove" @touchstart="touchstart" @touchend="touchend">
            <scroll-view scroll-y class="scroll-view" :style="{transform}" >
              <good-cell 
                ref="goodCell" 
                v-for="(skuName, index) in skuNames" 
                :key="index" 
                :skuName="skuName" 
                :index="index" 
                @handleSkuNamePlus="handleSkuNamePlus" 
                @handleSkuNameMinus="handleSkuNameMinus" 
                @handleSkuNameChange="handleSkuNameChange">
              </good-cell>
            </scroll-view>
          </div>
        </div>
      </div>
    </div>

    <zy-loading></zy-loading>

  
    <!-- 购物车图标 -->
    <shopCarIcon v-if="isShowShop"></shopCarIcon>

    <jxEmpty v-if="!isGoods" :title="'暂无可售商品'"></jxEmpty>	
  </div>
</template>

<script>
import ZyLoading from "@/components/Loading/loading";
import SearchBtn from "@/components/goodCmp/Search/search-btn";
import LeftCat from "@/components/goodCmp/leftCats/left-cats";
import TopCat from "@/components/goodCmp/topCats/top-cats";
import CatsWall from "@/components/goodCmp/topCatsWall/top-cats-wall";
import GoodCell from "@/components/goodCmp/good-cell/good-cell.vue";
import { lazyLoad } from "@/utils";
import {modal,errToast, toast,jumpPage,setTabBarBadge } from "@/utils/uniapi.js";
import scroll from "@/mixins/scroll.js";
import reComputedCarCount from "@/mixins/reComputedCarCount.js";
import NoList from "@/components/commonCmp/list-none.vue";
import { mapGetters, mapActions } from "vuex";
import jxEmpty from '@/components/jxEmpty/index.vue'

// #ifdef MP-WEIXIN
import MaterialInfo from "@/components/material-info/index.vue";
// #endif

import shopCarIcon from '@/components/shopCarIcon/index'

// import { msgData } from "@/config";

import goodPage from '@/apis/goodPage';
import {store} from "@/store";
// const App = getApp().globalData;
export default {
  name: "shopGood",
  mixins: [scroll, reComputedCarCount],
  components: {
    ZyLoading,
    SearchBtn,
    LeftCat,
    TopCat,
    CatsWall,
    GoodCell,
    NoList,
    // #ifdef MP-WEIXIN
    MaterialInfo,
    // #endif
    jxEmpty,

    shopCarIcon
  },
  data() {
    return {
      catL1: [],
      catL2: [],
      catID1: null,
      catID1Index: -1,
      catID2: -1,
      catID2Index: -1,
      catL2filter: [],
      wallShow: false,
      page: 1,
      checked: false,
      totalCount: 0,
      skuNames: [],
      isOnLoad: false,
      timer: null,
      timer1: null,
      searchKeyword:"",  // 搜索关键字
      isGoods:true,       // 门店是否有商品
      // App:null
    };
  },
  computed: {
    ...mapGetters({
      loading: "loading",      
      confirmCheckShow: "confirmCheckShow",

      isShowShop: 'isShowShop',

      isLogin: "login/isLogin",
      storeID:"indexPage/storeID",
      isMaterial: "indexPage/isMaterial",
      isPurchase: "indexPage/isPurchase",
      bagOverload: "indexPage/bagOverload",
      canBuy: "indexPage/canBuy",
      bagSkuIDs: "indexPage/bagSkuIDs",
      newTopGood:'indexPage/topGoods',
      goodsNeedReload: "goodPage/goodsNeedReload",
      sideNum:'goodPage/sideNum',
      iSExistWeixinApp:"login/iSExistWeixinApp",
      carCount: "cartPage/carCount",
      cartList:"cartPage/cartList",

      cat:"goodPage/cat"
    })
  },
  watch: {
		carCount: {
      handler(val) {
        if (val) {
          setTabBarBadge('set',val)
          this.skuNames.map((item,index) => {
            let findItem = this.cartList.find(i => item.id === i.id)
            if (findItem && findItem.count) this.skuNames[index].count = findItem.count
            else this.skuNames[index].count = 0
          })
        }
			},
			immediate:true
    }
	},
  async onShow() {
    // this.App = getApp().globalData
    console.log(this.isOnLoad,'查看你点击的数据,99999999999',this.sideNum)
    // return
    // console.log(this.isLogin,'再次进入',this.isOnLoad,'skuName',this.skuNames)
    // if (!this.isOnLoad) {
    //   this.isOnLoad = true;
    //   return false;
    // }
    try {
      this.showLoad();
      // console.log(this.App,'onLoad未执行9999999时',this.isOnLoad,'this.catL1',this.catL1)
      // if (this.App.catID) {
      //   if (this.catL1.length === 0) {
      //     let { catL1, catL2 } = await goodPage.getCat(this.storeID[0])
      //     await this.getSideMenu(catL1)
      //     this.catL2 = catL2; 
      //   }
      //   let index = this.catL1.findIndex((item) => item.id === this.App.catID);
      //   this.catChange({
      //     id: index !== -1 ? this.App.catID : this.catL1[0].id,
      //     index: index !== -1 ? index : 0,
      //   });
      //   // App.catID = null;
      //   this.App.catID = null;
      // } else 
      this.pageInit();
      // if (this.sideNum[0] !== -1 && this.sideNum[1] !== -1 && !this.goodsNeedReload) {
      //   this.catID1Index = this.sideNum[0]
      //   this.catID2Index = this.sideNum[1]
      //   this.hideLoad()
      // } else {
      //   this.pageInit();
      // }

      // if(this.carCount) setTabBarBadge('set',this.carCount)
      // #ifdef MP-WEIXIN
      // if (this.isMaterial) {
      //   await getMatterStoreOrderStatus();
      // }
      // #endif

      // console.log("goods onShow,進入之后的值",this.sideNum,this.catID);
      // 获取商品
      // await this.searchGoods()
      // 计算购物车数量
    } catch (e) {
      console.error(e);
      errToast(e);
    } finally {
      this.hideLoad();
    }
    
  },
  // async onLoad() {
  //   if(this.cat.catL1 && this.cat.catL1.length>0) return
  //   this.pageInit()
  // },
  // onHide() {
  //   // this.App.catID = null;
  //   console.log('离开页面时,打印一级分类',this.catL1)
  //   store.commit('goodPage/saveSideNum',[this.catID1Index,this.catID2Index])  // 离开页面时存储侧边栏索引
  //   // if(this.timer){
  //   //   clearTimeout(this.timer)
  //   // }
  //   // if (this.timer1) {
  //   //   clearTimeout(this.timer1)
  //   // }
   
  //   // if (this.catL1.length !== 0)  store.commit('goodPage/changeIsNeedReload',false)  // 去掉重载标识
   
  // },
  methods: {
    ...mapActions({
      getCarList: "cartPage/getCarList",
      changeCar: "cartPage/changeCar"
    }),
    // 关键字改变
    changeKeyword(){
      console.log('searchKeyword',this.searchKeyword)
    },
    async pageInit() {
      try {
        this.showLoad();
        // 获取分类 storeID变化时再重新加载分类
        this.isGoods = true
        if (this.goodsNeedReload) {
          // 初始化
          this.catID1Index = -1
          this.catL1 = []
          this.catL2filter = []
          this.skuNames = []
        
          let { catL1, catL2 } = await goodPage.getCat(this.storeID[0])
          await this.getSideMenu(catL1)
          this.catL2 = catL2;
          store.commit('goodPage/saveCat',{
            catL1:this.catL1,
            catL2:this.catL2
          })
          if(this.catL1.length === 0) {
            this.isGoods = false
            return toast('暂无商品') 
          }
          this.catID1 = this.catL1[0].id; // 'act' catL1[0].id || 0 // 设置默认的catID
          this.catChange({
            id: this.catL1[0].id,
            index: 0,
          })
        }else{
          this.catL1 = this.cat.catL1
          this.catL2 = this.cat.catL2
          if(!this.catL1) {
            store.commit('goodPage/changeIsNeedReload',true)
            this.pageInit()
            return
          }
          this.catID1 =  this.catL1[this.sideNum[0]].id;
          console.log('this.sideNum,9999',this.sideNum)
          this.catChange({
            id: this.catID1,
            index: this.sideNum[0], // 一级索引
          })
          // console.log('this0',this.catID1)
          // this.catChange({
          //   id: this.catID1 !== -1 ? this.catID1:this.catL1[0].id,
          //   index: this.sideNum[1] !== -1 ? this.sideNum[1] : 0,
          // });
        }
        // 如果有从其他页面传入商品分类ID
        // console.log('打印--------，pageInit',this.cat)
        // if (this.App.catID) {
        //   let findIndex = this.catL1.findIndex((item) => item.id ===this.App.catID);
        //   let index = findIndex === -1 ? this.catL1[0].id : findIndex
         
        //   this.catChange({
        //     id: index !== -1 ? this.App.catID:this.catL1[0].id,
        //     index: index !== -1 ? index : 0,
        //   });
        //   // App.catID = null;
        //   this.App.catID = null;
        // } else {
          // if(this.catL1.length>0){

        //   // }

        // }
      } catch (e) {
        console.error(e);
        errToast(e);
      } finally {
        // uni.showTabBar()		// 显示tabbar
        this.hideLoad();
      }
    },
    // 点击检索
    handleClickSearch() {
      if(!this.isGoods) return
      // console.log("点击检索");
      jumpPage('navigateTo',`/pagesGoods/good-search/index?type=cat`)
    },
    // 过滤二级分类
    async filterCat2(id) {
      // id指的是父级分类id
      let result = []
      let catL2filter = this.catL2.filter((item) => item.parentID === id);
      if (catL2filter.length === 0) {
        catL2filter.unshift({
          id: -1,
          name: "全部",
        });
      } else {
        let catL2Length=catL2filter.length
        for (let i = 0; i < catL2Length; i++){
          let res = await goodPage.getStoresSkus({ categoryID: catL2filter[i].id,pageSize:1,offset:0 })
          if(res.totalCount){
            result.push({...catL2filter[i]})
          }
        }

        catL2filter = result
      }
      return catL2filter;
    },
    // 一级分类改变
    async catChange({ id, index },type) {
      if (this.catID1Index === index) return
      this.catID1 = id === "act" ? id : +id;
      this.catID2 = -1
      this.catID1Index = index;
     
      this.catID2Index = this.sideNum[1]!==-1?this.sideNum[1]:0;
      // if (!type && type !== undefined) this.catID2Index = this.sideNum[1]
      // 滚动菜单
      if (this.$refs) {
        this.$refs.leftCat.scrollInToID(id);
      }
      // 过滤二级分类
      if (this.catL1[index].children && this.catL1[index].children.length > 0) {
        this.catL2filter = this.catL1[index].children
        // console.log('走的if')
        if (type === 'prev') {
          this.catID2 = this.catL2filter[this.catL2filter.length-1].id;
          this.searchGoods('',this.catL2filter[this.catL2filter.length-1].id === -1?this.catL1[index].id:this.catL2filter[this.catL2filter.length-1].id)
          this.catID2Index = this.catL2filter.length - 1
          this.timer1 = setTimeout(() => {
            this.$refs.cat2Top.scrollInToIndex(this.catL2filter.length - 1);
          },500)
         
        } else {
          this.catID2 = this.catL2filter[this.catID2Index].id;
          this.searchGoods('',this.catL2filter[this.catID2Index].id === -1?this.catL1[index].id:this.catL2filter[this.catID2Index].id)
        }
      } else {
        this.catL2filter = await this.filterCat2(id)
        this.catID2Index = 0
        this.catID2 = this.catL2filter[this.catID2Index].id
        this.catL1[index].children = [...this.catL2filter]
        this.searchGoods('',  this.catL2filter[0].id === -1?id:this.catL2filter[0].id)
      }
      store.commit('goodPage/saveSideNum',[this.catID1Index,this.catID2Index])  // 离开页面时存储侧边栏索引
    },
    // 二级分类改变
    cat2Change({ id, index }) {
      if (this.catID2Index === index) return
      this.catID2 = id;
      this.catID2Index = index;
      this.$refs.cat2Top.scrollInToIndex(index);
      if (this.catL1[this.catID1Index].children) {
        this.searchGoods('',this.catL1[this.catID1Index].children[index].id)
      }
      store.commit('goodPage/saveSideNum',[this.catID1Index,this.catID2Index])
    },
    // 点击顶部二级分类
    clickCat2({ id, index }) {
      if (this.catID2Index === index) return
      this.catID2 = id;
      this.catID2Index = index;
      // this.$refs.cat2Top.setScroll(id)
      this.$refs.cat2Top.scrollInToIndex(index);
      this.searchGoods('',this.catL1[this.catID1Index].children[index].id);
    },
    // 点击下拉分类选择按钮
    toggleCat2() {
      if(!this.isGoods) return
      this.wallShow = !this.wallShow;
    },
    // 关闭下拉分类选择
    closeWall() {
      this.wallShow = false;
    },
    // 查询商品 type in ['next', 'prev']
    async searchGoods(type,categoryID) {
      try {
        this.showLoad()
        if (type === "prev") {
          // ---- 处理下拉 ----
          const { catID1Index, catID2Index, catL1, catL2filter } = this;
          if (catID1Index === 0 && catID2Index === 0) {
            toast("已经到顶啦");
          } else if (catID2Index === 0) {
            // 到上一个大类
            this.catChange({
              id: catL1[catID1Index - 1].id,
              index: catID1Index - 1,
            },'prev')
          } else if (catID2Index > 0) {
            // 到上一个小类
            this.cat2Change({
              id: catL2filter[catID2Index - 1].id,
              index: catID2Index - 1,
            });
          }
        } else if (type === "next") {
          // ---- 处理上滑 ----
          const { catID1Index, catID2Index, catL1, catL2filter,} = this;
          if ( catID1Index === catL1.length - 1 && catID2Index === catL2filter.length - 1) {
            toast("已经到底啦");
            this.hideLoad()
          } else if ( catID1Index < catL1.length - 1 && catID2Index === catL2filter.length - 1) {
            // 到下一个大类
            this.catChange({
              id: catL1[catID1Index + 1].id,
              index: catID1Index + 1,
            });
          } else if (catID2Index < catL2filter.length - 1) {
            // 到下一个小类
            this.cat2Change({
              id: catL2filter[catID2Index + 1].id,
              index: catID2Index + 1,
            });
          }
        } else {
          // 处理请求
          this.showLoad();
          this.skuNames = [];
          this.closeWall();
          let { totalCount, skuNames } = await goodPage.getStoresSkus({ categoryID,isBySku:true})
          this.totalCount = totalCount;
          // 计算包包价格
          if (this.isMaterial) this.computedBagsPrice(skuNames);
          // 延迟加载
          lazyLoad({ target: this.skuNames, arr: skuNames, totalCount });
          // 初始化获取一级分类时不关闭loading
          this.hideLoad()
        }
      } catch (e) {
        console.error(e);
        this.hideLoad();
        throw e;
        
        } finally {
        this.hideLoad()
      }
    },
    // 商品 +
    async handleSkuNamePlus(index) {
      const skuName = this.skuNames[index];
      await this.changeCar({
          skuName,
          count:skuName.count + 1
        })
    },
    // 商品 -
    async handleSkuNameMinus(index) {
      let skuName = this.skuNames[index];
      await this.changeCar({
        skuName,
        count:skuName.count - 1
      })
    },
    async handleSkuNameChange({ index, count }) {
      let skuName = this.skuNames[index];
      await this.changeCar({
        skuName,
        count:count
      })
      // // 检查商品是否已经背修改
      // let res = await goodPage.getStoresSkus({ skuIDs:[skuName.id]})
      // this.$set(this.skuNames[index],'count',res.skuNames[0].count)
      // // this.skuNames[index].count = res.skuNames[0].count
      // console.log(this.skuNames[index],'this.skuNames',res,'this.skuNames',this.skuNames)
    },
    // 获取侧边栏一级分类数据
    async getSideMenu(catL1){
      try {
        if (!this.goodsNeedReload) return
        this.showLoad()
        let catL1Length=catL1.length
        let result = []
        // 过滤一级分类
        for (let i = 0; i < catL1Length; i++){
          let res = await goodPage.getStoresSkus({ categoryID: catL1[i].id,pageSize:1,offset:0 })
          if(res.totalCount){
            result.push({ ...catL1[i] })
          }
        }
        this.catL1 = result

        console.log('获取以及分类的值',this.catL1)
      } catch(e) {
        console.error(e)
      } finally {
        this.hideLoad()
      }

    }
  }
};
</script>

<style lang="scss">
@import "./good.scss";
</style>