<template>
  <div ref="browse" class="browse">
    <browse-header
      :is-edit.sync="isEdit"
      :show-right-btn="showEmpy"
      :result-len="resultList.length"
      @clear="clearHistory"
      @height="onOffsetHeight"
    />
    <!-- <cr-sticky v-if="showCalendar" :offset-top="stickyOffsetTop" fill @scroll="onStickyScrollEvent"> -->
    <div v-if="showCalendar" class="browse-calendar" :style="{ top: stickyOffsetTop }">
      <browse-calendar
        ref="calendar"
        :chose-date-list="choseDateList"
        @select-time="selectTimeEvent"
        @update-down="calendarArrowChange"
      />
    </div>
    <!-- </cr-sticky> -->
    <cr-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <template v-if="resultList.length">
        <div
          class="browse-list"
          :class="{ pdTop: showCalendar }"
          :style="{ marginTop: `${calendarMtop}px` }"
        >
          <cr-list
            v-model="loading"
            :finished="finished"
            finished-text="- 到底啦，仅展示30天记录哦 -"
            :offset="100"
            @load="getBrowseList"
          >
            <div v-for="item in resultList" :key="item.name" class="browse-list-block">
              <div class="browse-list-time">{{ parseTime(item.name, '{m}月{d}日') }}</div>
              <div class="browse-list-shop" :class="{ mark: isEdit }">
                <div v-for="child in item.value" :key="child.id" class="browse-list-item">
                  <div v-show="isEdit" class="browse-list-checkbox">
                    <cr-checkbox
                      v-model="checkboxList[child.id]"
                      shape="round"
                      :name="child.id"
                      @change="checkboxChange"
                    />
                  </div>
                  <browse-shop-card
                    :ref="`card-${child.id}`"
                    :product="child"
                    @delete="delBrowseList"
                    @open="resetSwipe"
                  />
                </div>
              </div>
            </div>
          </cr-list>
        </div>
      </template>
      <cr-empty
        v-else-if="showEmpy"
        :image="empyImg"
        image-size="4rem"
        description="浏览记录空空如也~"
      />
      <div v-else class="browse-loading">
        <cr-loading size="16px">加载中...</cr-loading>
      </div>
      <browse-goods-list v-if="showGoods" />
    </cr-pull-refresh>

    <browse-footer
      v-if="isEdit"
      :checkbox-all.sync="checkboxAll"
      @change="checkAllEvent"
      @delete="checkboxDelete"
    />
    <browse-shop-icon />
    <cr-back-top ref="backTopRef" />
  </div>
</template>
<script>
import browseHeader from './components/browseHeader';
import browseFooter from './components/browseFooter';
import browseCalendar from './components/browseCalendar.vue';
import browseShopCard from './components/browseShopCard.vue';
import browseGoodsList from './components/browseGoodsList.vue';
import browseShopIcon from './components/browseShopIcon.vue';
import empyImg from '@/assets/images/electronicInvoice/empy.png';
import { getBrowseList, delBrowseList, getBrowseCalendar, browseDeleteAll } from '@/api/browse.api';
import { cleanUndefinedOrNull, throttle } from '@/service/utils.service';
import appBackRefreshMixin from '@/mixins/appBackRefresh.mixin';
import { parseTime } from '@/service/utils.service';
// import { filterSortList } from './utils';
export default {
  components: {
    browseHeader,
    browseFooter,
    browseCalendar,
    browseShopCard,
    browseGoodsList,
    browseShopIcon
  },
  mixins: [appBackRefreshMixin],
  data() {
    return {
      paegLoading: false,
      showGoods: false,
      stickyOffsetTop: 44,
      stickyScrollTop: 0,
      empyImg,
      isEdit: false,
      calendarHeight: 0,
      choseDateList: [],
      refreshing: false,
      loading: false,
      finished: false,
      isInited: false,
      queryParams: {
        /*selectDate: '', lastId: ''*/
      },
      resultList: [],
      checkboxList: {},
      checkboxAll: false
    };
  },
  computed: {
    showEmpy() {
      return this.finished && !this.resultList.length;
    },
    shopCarCount() {
      return this.$store.getters['shopCart/cartCount'];
    },
    showCalendar() {
      // return Object.keys(this.checkboxList).length > 3 && !this.showEmpy;
      return (
        // this.choseDateList.length && Object.keys(this.checkboxList).length > 3 && !this.showEmpy
        this.choseDateList.length > 3 && !this.showEmpy
      );
    },
    calendarMtop() {
      return this.showCalendar ? this.calendarHeight : 0;
    }
  },
  watch: {
    isEdit(value) {
      if (value) return this.resetSwipe();
      this.setCheckbox(this.checkboxList, false);
      this.checkboxAll = false;
    }
  },
  created() {
    // this.getBrowseCalendar();
    this.onRefresh(true);
  },
  methods: {
    parseTime,
    calendarArrowChange(options) {
      this.calendarHeight = options.height;
    },
    clearHistory() {
      this.$dialog({
        message: '确定清空浏览记录?',
        onConfirm: () => {
          this.browseDeleteAll();
        }
      });
    },
    // App返回到当前页面刷新
    refreshChange() {
      this.$store.dispatch('shopCart/queryCartCount');
    },

    onOffsetHeight(height) {
      this.stickyOffsetTop = height;
    },

    onStickyScrollEvent: throttle(function() {
      const scrollTop = document.documentElement.scrollTop;

      // console.log(scrollTop, this.stickyScrollTop);
      // && scrollTop < this.stickyScrollTop
      if (scrollTop > 10) {
        this.$refs.calendar.arrowUpOrDown = false;
      }
      // this.stickyScrollTop = scrollTop;
    }, 500),

    onRefresh(getData) {
      if (this.refreshing || getData) {
        this.getBrowseCalendar(true);
        this.selectTimeEvent(null);
        this.resetSwipe();
        const timer = setTimeout(() => {
          this.refreshing = false;
          clearTimeout(timer);
        }, 500);
      }
    },

    resetSwipe(id) {
      Object.keys(this.checkboxList).forEach(item => {
        if (+item !== id) {
          this.$refs[`card-${item}`][0]?.closeSwipe();
        }
      });
      !id && this.$refs.backTopRef && this.$refs.backTopRef.handleBackTop(); // 不是删除单个到上面
    },
    selectTimeEvent(time) {
      // this.finished = false;
      this.isEdit = false;
      // this.$set(this, 'checkboxList', {});
      // this.$set(this, 'resultList', []);
      this.queryParams.selectDate = time;
      this.queryParams.lastId = null;
      this.getBrowseList(true);
      this.$refs.backTopRef && this.$refs.backTopRef.handleBackTop();
    },
    onUpdateEvent() {
      this.isEdit = !this.isEdit;
    },

    checkboxDelete() {
      const checkboxList = this.checkboxList;
      const selectCheckList = Object.keys(checkboxList).filter(key => checkboxList[key]);
      if (selectCheckList.length) {
        this.$dialog({
          message: '确定全部删除当前选中记录?',
          onConfirm: () => {
            this.delBrowseList(selectCheckList.map(item => +item));
          }
        });
        return;
      }
      this.$toast('请选择要删除的记录！');
    },

    setCheckbox(checkboxList, flag) {
      const newCheckList = Object.keys(checkboxList).reduce((origin, key) => {
        origin[key] = flag;
        return origin;
      }, {});
      this.$set(this, 'checkboxList', newCheckList);
    },
    checkAllEvent() {
      const checkboxList = this.checkboxList;
      if (this.checkboxAll) {
        this.setCheckbox(checkboxList, true);
        return;
      }
      const nChecked = !Object.values(checkboxList).some(item => !item);
      if (nChecked) {
        this.setCheckbox(checkboxList, false);
      }
    },
    checkboxChange() {
      this.checkboxAll = !Object.values(this.checkboxList).includes(false);
    },
    isDeleteFrist(checkList) {
      const choseDateList = this.choseDateList;
      const selectDate = this.queryParams.selectDate;
      if (this.choseDateList.length > 1 && selectDate) {
        const end = choseDateList[choseDateList.length - 1];
        if (end === selectDate) {
          const currentList = this.resultList.find(item => item.name === selectDate).value;
          // console.log('条件成立！currentList', currentList);
          // console.log('条件成立！', checkList);
          // console.log('条件结果！', checkList.length === currentList.length);
          return checkList.length === currentList.length;
        }
      }
      return false;
    },
    async delBrowseList(checkList) {
      const [, error] = await delBrowseList(checkList);
      if (!error) {
        this.$toast('记录已删除！');
        // 是否删除最早的数据，需要刷新列表
        if (this.isDeleteFrist(checkList)) {
          // 刷新列表
          this.refreshing = true;
          this.onRefresh();
          return;
        }
        this.selectTimeEvent(this.queryParams.selectDate);
      }
    },
    filterResultList(records) {
      const resultList = this.resultList;
      return (records || []).reduce(
        (origin, item) => {
          const itemIndex = origin.findIndex(itm => item.dateStr === itm.name);
          if (itemIndex === -1) {
            origin.push({
              name: item.dateStr,
              value: [item]
            });
          } else {
            origin[itemIndex].value.push(item);
          }
          this.$set(this.checkboxList, item.id, false);
          return origin;
        },
        [...resultList]
      );
    },
    async getBrowseList(isClear) {
      this.loading = true;
      const [res, error] = await getBrowseList(cleanUndefinedOrNull(this.queryParams));
      if (!error) {
        if (isClear) {
          this.$set(this, 'resultList', []);
          this.$set(this, 'checkboxList', {});
        }
        this.$set(this, 'resultList', this.filterResultList(res?.records));
        this.checkboxChange();
        this.loading = false;
        if (res.hasNext) {
          this.queryParams.lastId = res?.lastId;
          return;
        }
        this.finished = true;
        this.showGoods = true;
        return;
      }
      this.loading = false;
      this.finished = true;
      this.showGoods = true;
    },
    async getBrowseCalendar(clear) {
      const [res, error] = await getBrowseCalendar();
      if (!error) {
        this.choseDateList = [...res?.calendarList];
        if (clear) {
          this.$refs?.calendar?.refresh();
        }
      }
    },
    async browseDeleteAll() {
      const [, error] = await browseDeleteAll();
      if (!error) {
        this.$toast('清空成功！');
        this.getBrowseCalendar(false);
        this.selectTimeEvent(null);
      }
    }
  }
};
</script>
<style lang="less" scoped src="./index.less"></style>
