<template>
  <view class="category-list" :style="{ '--primary-color': primaryColor }">
    <scroll-view scroll-y class="left-aside">
      <view
        v-for="item in categoryList"
        :key="item.key"
        class="f-item b-b"
        :class="{ active: item.key === currentCate }"
        @click="handleTapCate(item)"
      >
        {{ item.name }}
      </view>
    </scroll-view>
    <scroll-view scroll-with-animation scroll-y class="right-aside">
      <view v-show="!hasThreeLevel" class="sub-cate-list-2">
        <view
          v-for="(subItem, idx) in subCategoryListLevel2"
          :id="'main-' + subItem.key"
          :key="subItem.key"
          class="sub-cate-item-2"
          @click="navToList(subItem)"
        >
          <view class="cate-image-wrap">
            <image
              class="cate-image"
              :lazy-load="false"
              style="height: auto"
              :src="originImgPath + subItem.icon"
              mode="widthFix"
              :class="[subItem.loaded]"
              @load="onImageLoad('subCategoryListLevel2', idx)"
            ></image>
          </view>
          <text class="sub-cate-name">{{ subItem.name }}</text>
        </view>
      </view>
      <view v-show="hasThreeLevel">
        <view
          v-for="(subItem, sidx) in subCategoryList"
          :id="'main-' + subItem.key"
          :key="subItem.key"
          class="sub-cate-list"
        >
          <view class="sub-cate-item">
            <text class="sub-cate-name">{{ subItem.name }}</text>
            <view class="third-cate-list">
              <view
                v-for="(titem, tidx) in subItem.childArray"
                :key="titem.key"
                class="third-cate-item"
                @click="navToList(titem)"
              >
                <view class="cate-image-wrap">
                  <image
                    class="cate-image"
                    :lazy-load="false"
                    style="height: auto"
                    :src="originImgPath + titem.icon"
                    mode="widthFix"
                    :class="[titem.loaded]"
                    @load="onImageLoad('subCategoryList', sidx, tidx)"
                  ></image>
                </view>
                <text class="third-cate-name">{{ titem.name }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { Setting } from '../../index';
import { queryCategoryList } from '../../mall/api';
import { mapState } from 'vuex';
export default {
  name: 'Category',
  data() {
    return {
      sizeCalcState: false,
      tabScrollTop: 0,
      originImgPath: Setting.getImgPath(),
      currentCate: '', // 当前选中的一级分类
      hasThreeLevel: false, // 是否有三级分类
      subCategoryList: [], // 二级分类(包含三级分类)
      subCategoryListLevel2: [], // 二级分类(不含三级分类)
      preCateKey: null,
      categoryList: [],
    };
  },
  computed: {
    ...mapState({
      primaryColor: state => state.primaryColor,
    }),
  },
  async mounted() {
    console.log('%c [fetchCategoryList]: ', 'color:#1989fa;');
    await this.fetchCategoryList();
  },
  methods: {
    //一级分类点击
    handleTapCate(cate) {
      this.subCategoryList = [];
      this.subCategoryListLevel2 = [];
      if (cate.childArray[0].childArray && cate.childArray[0].childArray.length > 0) {
        // console.log(cate.name, ' 有三级分类 --> ');
        this.hasThreeLevel = true;
        this.subCategoryList = cate.childArray.filter(
          cateItem => cateItem.childArray && cateItem.childArray.length > 0,
        );
      }
      if (cate.childArray[0].childArray && cate.childArray[0].childArray.length === 0) {
        // console.log(cate.name, ' 没有三级分类 --> ');
        this.hasThreeLevel = false;
        this.subCategoryListLevel2 = cate.childArray.filter(
          cateItem => cateItem.childArray && cateItem.childArray.length === 0,
        );
      }
      this.currentCate = cate.key;

      // 标记图片状态为未加载
      if (cate.key !== this.preCateKey) {
        this.subCategoryListLevel2.forEach(item => {
          delete item.loaded;
        });
        this.subCategoryList.forEach(cateItem => {
          cateItem.childArray.forEach(item => {
            delete item.loaded;
          });
        });
      }
    },
    // 跳转到商品列表
    navToList(cate) {
      this.$emit('click-category', cate);
    },

    // 获取一级分类(品牌列表)
    async fetchCategoryList() {
      const params = {
        query: {
          limit: 100,
          page: 0,
          keyJson: JSON.stringify({ status: 0, parent: '' }),
        },
      };
      const { data } = await queryCategoryList(params);
      const categoryList = data;
      categoryList.forEach(cate => {
        if (cate.childArray) {
          cate.childArray.forEach(item => {
            if (item.childArray && item.childArray.length > 0) {
              cate.hasThreeLevel = true;
            } else {
              cate.hasThreeLevel = false;
            }
          });
        }
      });
      this.categoryList = categoryList;
      this.handleTapCate(categoryList[0]);
    },
    /**
     * 图片加载后 标记分类的图片为已加载状态
     * @param type
     * @param index
     * @param subIndex
     */
    onImageLoad(type, index, subIndex) {
      // console.log('%c [图片加载后]: ', 'color:#1989fa;', this[type][index]);
      this.preCateKey = this[type][index].parent;
      if (type === 'subCategoryListLevel2') {
        this.$set(this[type][index], 'loaded', 'loaded');
      }
      if (type === 'subCategoryList') {
        this.$set(this[type][index].childArray[subIndex], 'loaded', 'loaded');
      }
    },
  },
};
</script>

<style lang="scss">
$primary-color: var(--primary-color);
.category-list {
  height: 100vh;
  background-color: #f8f8f8;
  display: flex;

  .left-aside {
    flex-shrink: 0;
    width: 200rpx;
    height: 100%;
    background-color: #fff;
  }

  .f-item {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100rpx;
    font-size: 28rpx;
    color: #606266;
    position: relative;

    &.active {
      color: $primary-color;
      background: #f8f8f8;

      &:before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        height: 36rpx;
        width: 8rpx;
        background-color: $primary-color;
        border-radius: 0 4px 4px 0;
        opacity: 0.8;
      }
    }
  }

  .right-aside {
    flex: 1;
    overflow: hidden;
    padding-left: 20rpx;
    height: 100vw;
  }

  // 二级分类不包含三级分类布局样式
  .sub-cate-list-2 {
    width: 100%;
    display: flex;
    flex-direction: row;
    background-color: #fff;
    flex-wrap: wrap;

    .sub-cate-item-2 {
      width: 32%;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 30rpx 10rpx;
      margin-top: calc(4% / 2);

      &:not(:nth-child(3n)) {
        margin-right: calc(4% / 2);
      }

      /*image {
      width: 102rpx;
    }*/
      .sub-cate-name {
        font-size: 26rpx;
        margin-top: 15rpx;
        color: #303133;
      }
    }
  }

  // 二级分类包含三级分类布局样式
  .sub-cate-list {
    .sub-cate-item {
      flex: 1;

      .sub-cate-name {
        display: flex;
        align-items: center;
        height: 70rpx;
        padding-top: 8rpx;
        font-size: 28rpx;
        color: #303133;
      }
    }

    .third-cate-list {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      /*justify-content: space-around;*/
      background-color: #fff;

      .third-cate-item {
        overflow: hidden;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 30rpx 10rpx;
        width: 33.3%;
        /*image {
        width: 102rpx;
      }*/
        .third-cate-name {
          font-size: 26rpx;
          margin-top: 15rpx;
          color: #303133;
        }
      }
    }
  }

  .cate-image-wrap {
    width: 56px;
    height: 56px;
    /*background: url('../../static/loadingImage.png') no-repeat center;*/
    background-color: #fff;
    background-size: 100%;
    overflow: hidden;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;

    .cate-image {
      width: 56px;
      height: 56px;
      transition: 0.2s;
      opacity: 0;

      &.loaded {
        opacity: 1;
      }
    }
  }
}
.loading-wrap {
  width: 100%;
  height: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
