<template>
  <div class="nav">
    <cr-dropdown-menu ref="dropdown" :class="{ activeTitle: rankType == 1 || rankType == 6 }">
      <div
        v-if="rankType != 1 && rankType != 6"
        class="dropdownOverLay"
        @click="clickDropMenu($event)"
      />
      <cr-dropdown-item v-model="filterType" :options="option1" />
    </cr-dropdown-menu>
    <div class="nav-item" :class="{ active: rankType == 4 }" @click="tabClick(4)">
      <span class="nav-item-title">销量</span>
      <span v-if="rankType == 4" class="sort" />
    </div>
    <div
      class="nav-item"
      :class="{ active: rankType == 2 || rankType == 3 }"
      @click="tabClick(2, 3)"
    >
      <span class="nav-item-title">价格</span>
      <span
        v-if="rankType == 2 || rankType == 3"
        class="sort"
        :class="{
          rotate: rankType == 3
        }"
      />
      <svg-icon v-if="rankType != 2 && rankType != 3" icon-class="arrow" class="defaultFilter" />
    </div>
    <div
      class="nav-item last"
      :class="{
        active: filterConditionHighLight
      }"
      @click.stop="showMoreFilter"
    >
      <span class="nav-item-title">筛选</span>
      <svg-icon v-if="!filterConditionHighLight" icon-class="filter" class="filter" />
      <svg-icon v-else icon-class="filterHighLight" class="filter" />
    </div>
    <cr-popup
      v-model="showMoreFilterPopup"
      position="right"
      class="filterPopup"
      get-container="body"
      @close="closeMoreFilterPopup"
    >
      <filters
        :price-data="priceData"
        :brand-data="brandData"
        :category-data="categoryData"
        :total-cnt-str="totalCntStr"
        @close="showMoreFilterPopup = false"
        @filterCondition="filterConditionEmit"
        @showSortBrand="showSortBrand"
        @showSortCategory="showSortCategory"
      />
    </cr-popup>
    <cr-popup
      v-model="showSortBrandPopup"
      position="right"
      class="filterPopup noPaddingBottom"
      get-container="body"
      @close="closeAlphabeticallyPopup"
    >
      <alphabetically
        ref="alphabetically"
        :sort-data="deepBrandPopupData"
        title="品牌"
        right-btn="确定"
        @back="showSortBrandPopup = false"
      />
    </cr-popup>
    <cr-popup
      v-model="showSortCategoryPopup"
      position="right"
      class="filterPopup noPaddingBottom"
      get-container="body"
      @close="closeNoAlphabeticallyPopup"
    >
      <noalphabetically
        ref="noalphabetically"
        :sort-data="deepCategoryPopupData"
        title="更多分类"
        right-btn="确定"
        @back="showSortCategoryPopup = false"
      />
    </cr-popup>
  </div>
</template>
<script>
const CHANGE_TABEVT = 'change';
import filters from './filters.vue';
import alphabetically from './alphabetically.vue'; // 字母排序
import noalphabetically from './noalphabetically.vue';
const SORT_INDEX = '#abcdefghijklmnopqrstuvwxyz';

export default {
  components: { filters, alphabetically, noalphabetically },
  props: {
    filterData: {
      type: Object,
      default() {
        return {};
      }
    },
    totalCntStr: {
      type: [Number, String],
      default: 0
    },
    searchText: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      filterConditionHighLight: false,
      moreFilter: false,
      showMoreFilterPopup: false,
      filterType: 1,
      option1: [
        { text: '综合推荐', value: 1 },
        { text: '新品推荐', value: 6 }
      ],
      rankType: 1,
      filterIndex: 0,
      filterItem: [
        { name: '价格', select: { up: 3, down: 2 } },
        { name: '销量', select: { up: 5, down: 4 } },
        { name: '筛选', select: { up: 5, down: 4 } }
      ],
      showSortBrandPopup: false,
      showSortCategoryPopup: false,
      deepBrandPopupData: null,
      deepCategoryPopupData: null,
      dropdownRankType: 1
    };
  },
  computed: {
    priceData() {
      return this.filterData && this.filterData.price ? this.filterData.price : null;
    },
    brandData() {
      return this.filterData && this.filterData.nexpandSorts
        ? this.filterData.nexpandSorts.filter(item => item.expandSortType == '1')[0]
        : {};
    },
    categoryData() {
      return this.filterData && this.filterData.nexpandSorts
        ? this.filterData.nexpandSorts.filter(item => item.expandSortType == '2')[0]
        : {};
    }
  },
  watch: {
    rankType(val) {
      if (val == 1 || val == 6) {
        this.dropdownRankType = val;
      }
    },
    filterType(val) {
      this.rankType = val;
      this.$emit(CHANGE_TABEVT, this.rankType);
    },
    brandData(val) {
      const { alphabeticalItems, needKeepLastData } = val;
      if (!alphabeticalItems) {
        this.deepBrandPopupData = {};
        this.showSortBrandPopup = true;
        return;
      }
      if (!needKeepLastData) {
        const index = SORT_INDEX.toUpperCase().split('');
        const alphabeticalMap = {};
        index.map(item => {
          alphabeticalMap[item] = [];
        });
        alphabeticalItems.map(item => {
          alphabeticalMap[item.letter] = alphabeticalMap[item.letter].concat(
            item.items ? item.items : []
          );
        });
        this.deepBrandPopupData = alphabeticalMap;
      }
    },
    categoryData(val) {
      const { noAlphabeticalItems, needKeepLastData } = val;
      if (!noAlphabeticalItems) {
        this.deepCategoryPopupData = [];
        this.showSortCategoryPopup = true;
        return;
      }
      if (!needKeepLastData) {
        this.deepCategoryPopupData = noAlphabeticalItems;
      }
    }
  },
  methods: {
    clickDropMenu() {
      if (this.filterType == this.dropdownRankType) {
        this.rankType = this.dropdownRankType;
        this.$emit(CHANGE_TABEVT, this.rankType);
        return;
      }
      this.filterType = this.dropdownRankType;
    },
    closeAlphabeticallyPopup() {
      try {
        this.$refs.alphabetically.$refs.content.scrollTop = 0;
      } catch (err) {
        console.log(err);
      }
    },
    closeNoAlphabeticallyPopup() {
      try {
        this.$refs.noalphabetically.$refs.content.scrollTop = 0;
      } catch (err) {
        console.log(err);
      }
    },
    showSortBrand() {
      const { alphabeticalItems, needKeepLastData } = this.brandData;
      if (!alphabeticalItems) {
        this.deepBrandPopupData = {};
        this.showSortBrandPopup = true;
        return;
      }
      if (!needKeepLastData) {
        const index = SORT_INDEX.toUpperCase().split('');
        const alphabeticalMap = {};
        index.map(item => {
          alphabeticalMap[item] = [];
        });
        alphabeticalItems.map(item => {
          alphabeticalMap[item.letter] = alphabeticalMap[item.letter].concat(
            item.items ? item.items : []
          );
        });
        this.deepBrandPopupData = alphabeticalMap;
      }
      this.showSortBrandPopup = true;
    },
    showSortCategory() {
      const { noAlphabeticalItems, needKeepLastData } = this.categoryData;
      if (!noAlphabeticalItems) {
        this.deepCategoryPopupData = [];
        this.showSortCategoryPopup = true;
        return;
      }
      if (!needKeepLastData) {
        this.deepCategoryPopupData = noAlphabeticalItems;
      }
      this.showSortCategoryPopup = true;
    },
    filterConditionEmit({ eventData, reset }) {
      // 筛选条件向上广播
      if (reset) {
        this.filterConditionHighLight = false;
      } else {
        this.filterConditionHighLight = true;
      }
      this.$emit('filterCondition', eventData ? eventData : {});
    },
    showMoreFilter() {
      if (this.totalCntStr == 0) return this.$toast('暂无匹配商品，换个选项试试吧');
      this.$track.registeredEvents('H5_SearchingSecPageSelectBtnClick', {
        search_content: this.searchText
      });
      this.showMoreFilterPopup = true;
    },
    closeMoreFilterPopup() {
      // 关闭筛选弹出层
      this.showMoreFilterPopup = false;
    },
    computedActive(selectIndex, selectItem) {
      let className = `icon-sort-${selectIndex}-round`;
      const rankType = this.rankType;
      return rankType === selectItem ? `${className} active` : className;
    },
    tabClick(index, secIndex) {
      if (secIndex) {
        this.rankType =
          this.rankType != index && this.rankType != secIndex
            ? secIndex
            : this.rankType == secIndex
            ? index
            : secIndex;
      } else {
        this.rankType = index;
      }
      this.$emit(CHANGE_TABEVT, this.rankType);
    }
  }
};
</script>
<style scoped lang="less">
.nav {
  display: flex;
  width: 100%;
  height: 45px;
  background: @white;
  position: relative;
  z-index: 10;
  padding: 5px 5px 0;
  box-sizing: border-box;
  box-shadow: 0px 10px 12px -10px rgba(100, 101, 102, 0.08);
  /deep/ .cr-dropdown-menu {
    flex: 0 1 auto;
    width: 80px;
    padding-right: 10px;
    height: 100%;
    background: transparent;
    box-shadow: none;
    position: relative;
    &.activeTitle {
      .cr-dropdown-menu__title {
        color: @red;
        &::after {
          border-color: transparent transparent @red @red;
        }
      }
    }
    .cr-cell {
      padding: 10px 17px;
      box-sizing: border-box;
      &__title {
        display: flex;
        &::before {
          display: inline;
          content: '根据';
        }
      }
    }
    .cr-dropdown-menu__title {
      font-size: 14px;
      padding: 0 7px 0 8px;
      color: @black;
      &--active {
        color: @red;
        &::after {
          border-color: transparent transparent @red @red !important;
        }
      }
      &::after {
        border-color: transparent transparent #dcdee0 #dcdee0;
      }
    }
    .cr-dropdown-item__content {
      border-radius: 0 0 12px 12px;
    }
    .cr-dropdown-item__option--selected {
      color: @red;
    }
  }
  &-item {
    .text-size(14);
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: @black;
    &.last {
      width: 70px;
      flex: 0 1 auto;
    }
    &-title {
      line-height: 15px;
    }
    &.active {
      color: @red;
      .sort {
        &::after {
          border-color: transparent transparent @red @red;
        }
      }
    }
    .sort {
      margin-left: @padding-unit;
      display: flex;
      align-items: center;
      &::after {
        display: inline-block;
        margin-top: -0.133333rem;
        border: 0.08rem solid;
        border-color: transparent transparent #dcdee0 #dcdee0;
        transform: rotate(-45deg);
        opacity: 0.8;
        content: '';
      }
      &.rotate {
        transform: rotate(180deg);
      }
    }
    &.current {
      color: @black;
      font-weight: @font-weight-bold;
      .nav-item-title {
        font-weight: @font-weight-bold;
      }
    }

    &-container {
      display: flex;
      flex-direction: column;
      margin-left: @padding-unit / 2;
      justify-content: center;
      span {
        .text-size(10);
        color: @gray-4;
        &.active {
          color: @black;
        }
        &:nth-child(1) {
          margin-bottom: -13px;
        }
      }
    }
  }
}
.filter {
  width: 10px;
  height: 10px;
  margin-left: @padding-unit;
}
.defaultFilter {
  width: 8px;
  height: 13px;
  margin-left: @padding-unit;
}
// 更多筛选
.filterPopup {
  width: 89.8%;
  border-radius: 16px 0 0 16px;
  // padding: 20px 0 24px;
  // position: relative;
  padding: 20px 0 84px;
  box-sizing: border-box;
  &.noPaddingBottom {
    padding-bottom: 20px;
  }
}
.dropdownOverLay {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}
</style>
