<template>
  <div
    style="
    overflow: auto;
    height: 100%;
"
  >
    <div v-if="priceData" class="priceFilter filterContent">
      <div class="title">{{ priceData.key }}</div>
      <div class="priceInput">
        <cr-field
          v-model="minPrice"
          input-align="center"
          type="number"
          placeholder="最低价"
          @input="selectPriceIndex = ''"
        />
        <span />
        <cr-field
          v-model="maxPrice"
          input-align="center"
          type="number"
          placeholder="最高价"
          @input="selectPriceIndex = ''"
        />
      </div>
      <div class="priceSec">
        <template v-for="(item, index) in priceData.priceSpaces">
          <div
            v-if="index < 3"
            :key="`priceSpaces-${index}`"
            class="presetItem"
            :class="{ selected: selectPriceIndex === index }"
            @click.stop="selectPrice(item, index)"
          >
            {{ item.value }}
          </div>
        </template>
      </div>
    </div>
    <div class="cutline" />
    <div v-if="brandDataOrigin" class="brandFilter filterContent">
      <div class="title">
        <div class="titleText">{{ brandDataOrigin.expandSortName }}</div>
        <div class="select">{{ brandNames }}</div>
      </div>
      <div class="brandList">
        <div
          v-for="(item, index) in brandDataOrigin.items"
          :key="`brand-${index}`"
          class="brandItem"
          @click="clickBrandItem(item)"
        >
          <template v-if="brandDataOrigin.showLogo">
            <div
              class="img"
              :class="{ selected: brandIds.indexOf(item.valueId) > -1 && !hideBrandSelect }"
            >
              <img :src="item.logourl" alt="" />
            </div>
          </template>
          <template v-else>
            <div
              v-if="item.showName"
              class="brandText"
              :class="{ selected: brandIds.indexOf(item.valueId) > -1 && !hideBrandSelect }"
            >
              <template v-if="item.showName.indexOf('（') > -1 || item.showName.indexOf('(') > -1">
                <p>{{ item.showName | chinese }}</p>
                <p>{{ item.showName | english }}</p>
              </template>
              <template v-else>{{ item.showName }}</template>
            </div>
          </template>
        </div>
        <div v-if="showAllBrandOption" class="brandItem" @click.stop="showSortBrand">
          <div class="brandText">全部品牌</div>
        </div>
      </div>
    </div>
    <div v-if="categoryDataOrigin" class="brandFilter filterContent">
      <div class="title">
        <div class="titleText">{{ categoryDataOrigin.expandSortName }}</div>
        <div class="select">{{ categorySelect.showName }}</div>
      </div>
      <div class="brandList">
        <div
          v-for="(item, index) in categoryDataOrigin.items"
          :key="`category-${index}`"
          class="brandItem"
          @click="clickCategoryItem(item)"
        >
          <template v-if="categoryDataOrigin.showLogo">
            <div class="img" :class="{ selected: categorySelect.valueId == item.valueId }">
              <img :src="item.logourl" alt="" />
            </div>
          </template>
          <template v-else>
            <div class="brandText" :class="{ selected: categorySelect.valueId == item.valueId }">
              {{ item.showName }}
            </div>
          </template>
        </div>
        <div v-if="showAllCategoryOption" class="brandItem" @click.stop="showSortCategory">
          <div class="brandText">更多分类</div>
        </div>
      </div>
    </div>
    <div class="buttonContent">
      <cr-button type="default" shape="circle" block @click.stop="reset">重置</cr-button>
      <button class="normal" block @click.stop="search">
        确定
        <span v-if="totalCntStr">({{ totalCntStr }}件商品)</span>
      </button>
    </div>
  </div>
</template>
<script>
import { EventBus } from '@/service/utils.service';
const SELECT_BRAND_BY_SORT_LIST = 'selectBrandBySortList';
const SELECT_CATEGORY_BY_SORT_LIST = 'selectCategoryBySortList';
const CLEAR_BRAND_SELECT_LIST = 'clearBrandSelectList';
export default {
  filters: {
    english(val) {
      if (val.indexOf('（') > -1) {
        let arr = val.split('（');
        return arr[1] ? arr[1].replace('）', '') : '';
      }
      const en = /\((.+?)\)/g;
      return val.match(en);
    },
    chinese(val) {
      if (val.indexOf('（') > -1) {
        return val.split('（')[0] || '';
      }
      return val.split('(')[0] || '';
    }
  },
  props: {
    priceData: {
      type: [Object, null],
      default: null
    },
    brandData: {
      type: [Object, null],
      default: null
    },
    categoryData: {
      type: [Object, null],
      default: null
    },
    totalCntStr: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
      selectPriceIndex: '',
      minPrice: '',
      maxPrice: '',
      brandSelectList: [],
      categorySelect: {},
      categoryDataOrigin: null,
      brandDataOrigin: null,
      lastOperateType: '',
      hideBrandSelect: false,
      hideCategorySelect: false
    };
  },
  computed: {
    brandNames() {
      return this.brandSelectList.map(item => item.showName).join();
    },
    brandIds() {
      return this.brandSelectList.map(item => item.valueId);
    },
    showAllBrandOption() {
      // 是否显示所有品牌的选项
      if (this.brandDataOrigin.items && this.brandDataOrigin.items.length >= 15) {
        let count = 0;
        const allItems = this.brandDataOrigin.alphabeticalItems;
        if (allItems) {
          for (let i = 0; i < allItems.length; i++) {
            if (allItems[i].items) {
              count += allItems[i].items.length;
            }
          }
          if (count > 15) return true;
        }
        return false;
      }
      return false;
    },
    showAllCategoryOption() {
      const noAlphabeticalItems = this.categoryDataOrigin.noAlphabeticalItems;
      return noAlphabeticalItems && noAlphabeticalItems.length > 1 ? true : false;
    }
  },
  watch: {
    brandData: {
      immediate: true,
      deep: true,
      handler(val) {
        if (!val.needKeepLastData) {
          this.brandDataOrigin = val;
        }
      }
    },
    categoryData: {
      immediate: true,
      deep: true,
      handler(val) {
        if (!val.needKeepLastData) {
          this.categoryDataOrigin = val;
        }
      }
    }
  },
  beforeDestroy() {
    EventBus.$off(SELECT_BRAND_BY_SORT_LIST);
    EventBus.$off(SELECT_CATEGORY_BY_SORT_LIST);
  },
  created() {
    EventBus.$on(SELECT_BRAND_BY_SORT_LIST, res => {
      this.brandSelectList = res;
      this.hideBrandSelect = true;
      this.emitFilterCondition(1);
    });
    EventBus.$on(SELECT_CATEGORY_BY_SORT_LIST, res => {
      this.categorySelect = res;
      this.hideCategorySelect = true;
      this.emitFilterCondition(2);
    });
  },
  methods: {
    showSortBrand() {
      this.$emit('showSortBrand', {});
    },
    showSortCategory() {
      this.$emit('showSortCategory', {});
    },
    search() {
      // 点击确定按钮搜索
      if (this.lastOperateType != 1 && this.lastOperateType != 2) {
        // 操作品类品牌后，不用再次搜索，当且仅当价格_手动_修改时才需要点击确认按钮搜索
        this.emitFilterCondition();
      }
      this.$emit('close');
    },
    clickCategoryItem(item) {
      if (this.hideCategorySelect) {
        this.categorySelect = {};
        this.hideCategorySelect = false;
      }
      // 选择类目，仅单选
      if (item.valueId == this.categorySelect.valueId) {
        this.categorySelect = {};
      } else {
        this.categorySelect = item;
      }
      this.emitFilterCondition(2);
    },
    clickBrandItem(item) {
      if (this.hideBrandSelect) {
        this.brandSelectList = [];
        this.hideBrandSelect = false;
      }
      // 选择品牌
      const { valueId } = item;
      if (!valueId) return;
      const index = this.brandSelectList.findIndex(item => item.valueId == valueId);
      if (index == -1) {
        this.brandSelectList.push(item);
      } else {
        // 已经存在进行去除
        this.brandSelectList.splice(index, 1);
      }
      EventBus.$emit(CLEAR_BRAND_SELECT_LIST);
      this.emitFilterCondition(1);
    },
    reset() {
      this.selectPriceIndex = '';
      this.minPrice = '';
      this.maxPrice = '';
      this.brandSelectList = [];
      this.categorySelect = {};
      this.emitFilterCondition('', true);
    },
    comparePrice(price) {
      if (!price || price.indexOf('-') == -1) return { min: 0, max: 0 };
      const priceStr = price + '';
      const arr = priceStr
        .split('-')
        .map(item => {
          item = item.trim();
          return parseFloat(item);
        })
        .sort((a, b) => b - a);
      return {
        min: String(arr[1]),
        max: String(arr[0])
      };
    },
    selectPrice(priceInfo, index) {
      this.lastOperateType = '';
      if (index === this.selectPriceIndex) {
        this.minPrice = '';
        this.maxPrice = '';
        this.selectPriceIndex = '';
        // this.emitFilterCondition();
        return;
      }
      const { value } = priceInfo;
      if (value) {
        // const
        const { min, max } = this.comparePrice(value);
        this.minPrice = min;
        this.maxPrice = max;
      }
      this.selectPriceIndex = index;
      // this.emitFilterCondition();
    },
    emitFilterCondition(lastOperateType, reset) {
      // 请求前处理附加搜索条件
      this.lastOperateType = lastOperateType;
      let minPrice =
        this.minPrice && !isNaN(parseFloat(this.minPrice)) ? parseFloat(this.minPrice) : 0;
      let maxPrice =
        this.maxPrice && !isNaN(parseFloat(this.maxPrice)) ? parseFloat(this.maxPrice) : 0;
      const priceArrSort = [minPrice, maxPrice].sort((a, b) => a - b);
      // 广播筛选条件
      this.minPrice = priceArrSort[0] == 0 ? '' : priceArrSort[0].toString();
      this.maxPrice = priceArrSort[1] == 0 ? '' : priceArrSort[1].toString();
      const eventData = {
        minPrice: reset ? '' : priceArrSort[0] ? priceArrSort[0] : '',
        maxPrice: reset ? '' : priceArrSort[1] ? priceArrSort[1] : '',
        brandIds: this.brandSelectList.map(item => item.valueId).join(),
        categoryId: this.categorySelect.valueId || ''
      };
      if (lastOperateType) {
        eventData.lastOperateType = lastOperateType;
      }
      reset = this.validateCondition(eventData);
      this.$track.registeredEvents('H5_SearchingSecPageSelectConfirmBtnClick', {
        brand: eventData.brandIds,
        classify: eventData.categoryId,
        price_interval_left: eventData.minPrice,
        price_interval_right: eventData.maxPrice
      });
      this.$emit('filterCondition', { eventData, reset });
    },
    validateCondition(condition) {
      let data = Object.assign({}, condition);
      if (data.lastOperateType) delete data.lastOperateType;
      let valid = false;
      for (let i in data) {
        if (data[i]) {
          valid = true;
          break;
        }
      }
      return !valid;
    }
  }
};
</script>
<style lang="less" scoped>
@grayBg: #f7f8f9;
.buttonContent {
  padding: 20px 20px 0px;
  box-sizing: border-box;
  position: absolute;
  bottom: 24px;
  left: 0;
  height: 60px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  button {
    width: 48%;
    flex-shrink: 0;
    padding: 0 10px;
    box-sizing: border-box;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 999px;
    &.normal {
      background: linear-gradient(90deg, #ff1900, #ff5d00);
      color: @white;
    }
    span {
      font-size: 12px;
    }
    &.cr-button--default {
      color: @black;
      background: @white;
      border: 1px solid #dcdee0;
    }
  }
}
.filterContent {
  padding: 0 20px;
  box-sizing: border-box;
  .title {
    font-weight: bold;
    font-size: 16px;
    color: @black;
  }
  &.priceFilter {
    .priceInput {
      margin-top: @padding-sm;
      display: flex;
      align-items: center;
      span {
        font-size: 0;
        background-color: #dcdee0;
        width: 9px;
        height: 1px;
        margin: 0 @padding-unit;
      }
      div.cr-cell {
        flex: 1;
        height: 32px;
        display: flex;
        align-items: center;
        padding: 0;
        /deep/ .cr-cell__value,
        /deep/ .cr-field--body,
        /deep/ .cr-field--control {
          height: 100%;
        }
        /deep/ input {
          display: inline-block;
          margin: 0;
          width: 100%;
          height: 100%;
          background: @grayBg;
          box-sizing: border-box;
          color: @black;
          border-radius: 16px;
          text-align: center;
          padding: 0 @padding-unit;
          font-size: 12px;
          &::input-placeholder {
            color: @gray-4;
          }
          &::-webkit-input-placeholder {
            color: @gray-4;
          }
          &:-moz-placeholder {
            color: @gray-4;
          }
          &::-moz-placeholder {
            color: @gray-4;
          }
          &:-ms-input-placeholder {
            color: @gray-4;
          }
        }
      }
    }
    .priceSec {
      height: 32px;
      margin-top: @padding-sm;
      display: flex;
      .presetItem {
        border-radius: 16px;
        flex: 1;
        height: 32px;
        background: @grayBg;
        margin-right: @padding-sm - 2;
        text-align: center;
        color: @gray-4;
        font-size: 12px;
        line-height: 32px;
        box-sizing: border-box;
        border: 0.5px solid transparent;
        &.selected {
          color: @red;
          font-weight: bold;
          background: #fff3f3;
          border: 0.5px solid @red;
          border-radius: 16px;
        }
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
  &.brandFilter {
    width: 100%;
    padding-top: @padding-md;
    .title {
      width: 100%;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .titleText {
        width: 75px;
        font-weight: bold;
        font-size: 16px;
        color: @black;
      }
      .select {
        width: calc(100% - 75px);
        text-align: right;
        font-size: 10px;
        color: @red;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
    .brandList {
      display: flex;
      flex-wrap: wrap;
      .brandItem {
        width: 31.3%;
        height: 32px;
        border-radius: 16px;
        // overflow: hidden;
        margin: @padding-sm 1% 0;
        // margin-top: @padding-sm;
        .img {
          width: 100%;
          height: 100%;
          border-radius: 16px;
          overflow: hidden;
          box-sizing: border-box;
          border: 1px solid #f2f3f5;
          padding: @padding-unit;
          &.selected {
            border: 1px solid @red;
          }
          img {
            display: block;
            border-radius: 16px;
            max-width: 100%;
            max-height: 100%;
            margin: 0 auto;
          }
        }
        .brandText {
          width: 100%;
          height: 100%;
          background: @grayBg;
          font-size: 12px;
          color: @black;
          line-height: 32px;
          text-align: center;
          padding: 0 @padding-xs;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          box-sizing: border-box;
          user-select: none;
          border-radius: 16px;
          border: 1px solid transparent;
          p {
            box-sizing: border-box;
            height: 16px;
            font-size: 10px;
            line-height: 16px;
          }
          &.selected {
            color: @red;
            font-weight: bold;
            background: #fff3f3;
            border: 1px solid @red;
            border-radius: 16px;
          }
        }
      }
    }
  }
}
.cutline {
  height: 8px;
  background: @grayBg;
  margin-top: @padding-lg;
}

.filterPopup {
  width: 89.8%;
  border-radius: 16px 0 0 16px;
  padding: 20px 0 64px;
  box-sizing: border-box;
}
</style>
