<template>
  <div class="dc-simple-chart-legend">
    <div class="legend-wrap" ref="simpleLegend">
      <div ref="legendScroll" class="legend-item-scroll">
        <div ref="legendWrap" class="legend-item-wrap" :style="legendStyle">
          <div
            ref="legendItem"
            v-for="series in legendData"
            :key="series.name"
            :class="['legend-item', series.selected ? '' : 'unselected']"
            @click="selectSeriesItem(series)"
          >
            <span class="legend-color" :style="{ backgroundColor: series.color }"></span>
            <span class="legend-name">{{ series.showName }}</span>
            <span
              :class="['legend-option', isFocused(series.name) ? 'selected-legend-option' : '']"
              @mouseenter="handleSeriesHighlight(series.name)"
              @mouseleave="handleSeriesDownplay(series.name)"
              @click.stop="handleSeriesFocusClick(series.name)"
            >
              <LegendItemIcon></LegendItemIcon>
            </span>
          </div>
        </div>
      </div>
    </div>
    <div class="page-wrap" v-if="totalPage > 1">
      <span :class="['page-prev', pageNumber === 1 ? 'disabled' : '']" @click="scrollPrev">
        <Icon type="md-arrow-dropleft" size="24" />
      </span>
      <span>{{ pageNumber }}/{{ totalPage }}</span>
      <span :class="['page-next', pageNumber === totalPage ? 'disabled' : '']" @click="scrollNext">
        <Icon type="md-arrow-dropright" size="24" />
      </span>
    </div>
  </div>
</template>

<script>
/* eslint-disable no-param-reassign,no-lonely-if */
import LegendItemIcon from '@/components/LegendItemIcon.vue';
import legendMixin from '@/components/legendMixin';
import { throttle } from 'echarts/core';
import { addListener, removeListener } from 'resize-detector';

export default {
  name: 'SimpleChartLegend',
  components: { LegendItemIcon },
  mixins: [legendMixin],
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    chartElement: {
      type: HTMLElement,
    },
  },
  data() {
    return {
      pageNumber: 1,
      legendStyle: {
        transform: '',
      },
      scrollable: false,
      totalPage: 1,
    };
  },
  computed: {
    selectedObj() {
      const obj = {};
      this.legendData.forEach(series => {
        obj[series.name] = series.selected;
      });
      return obj;
    },
    resizeHandler() {
      return throttle(this.updateNavScroll, 100);
    },
  },
  watch: {
    data(val) {
      console.log(val);
      if (val?.length) {
        this.$nextTick(() => {
          this.updateNavScroll();
        });
      }
    },
  },
  mounted() {
    addListener(this.$refs.simpleLegend, this.resizeHandler);
  },
  beforeDestroy() {
    removeListener(this.$refs.simpleLegend, this.resizeHandler);
  },
  methods: {
    handleSeriesFocusClick(seriesName) {
      if (this.isFocused(seriesName)) {
        this.legendData.forEach(series => {
          series.selected = true;
        });
      } else {
        this.legendData.forEach(series => {
          series.selected = series.name === seriesName;
        });
      }
      this.updateLegendStatus();
    },

    updateNavScroll() {
      const navWidth = this.$refs.legendWrap.offsetWidth;
      const containerWidth = this.$refs.legendScroll.offsetWidth;
      const currentOffset = this.getCurrentScrollOffset();
      this.totalPage = Math.ceil(navWidth / containerWidth);
      this.pageNumber = 1;
      this.setOffset(0);
      // if (containerWidth < navWidth) {
      //   console.log(containerWidth, currentOffset);
      //   if (navWidth - currentOffset < containerWidth) {
      //     this.setOffset(navWidth - containerWidth);
      //   }
      // } else {
      //   if (currentOffset > 0) {
      //     this.setOffset(0);
      //   }
      // }
    },

    scrollPrev() {
      const containerWidth = this.$refs.legendScroll.offsetWidth;
      const currentOffset = this.getCurrentScrollOffset();

      if (!currentOffset) return;

      const newOffset = currentOffset > containerWidth ? currentOffset - containerWidth : 0;

      this.setOffset(newOffset);
      this.pageNumber -= 1;
    },
    scrollNext() {
      const navWidth = this.$refs.legendWrap.offsetWidth;
      const containerWidth = this.$refs.legendScroll.offsetWidth;
      const currentOffset = this.getCurrentScrollOffset();
      if (navWidth - currentOffset <= containerWidth) return;

      const newOffset =
        navWidth - currentOffset > containerWidth * 2 ? currentOffset + containerWidth : navWidth - containerWidth;

      this.setOffset(newOffset);
      this.pageNumber += 1;
    },
    getCurrentScrollOffset() {
      const { legendStyle } = this;
      return legendStyle.transform ? Number(legendStyle.transform.match(/translateX\(-(\d+(\.\d+)*)px\)/)[1]) : 0;
    },

    setOffset(value) {
      this.legendStyle.transform = `translateX(-${value}px)`;
    },
  },
};
</script>

<style lang="less">
.dc-simple-chart-legend {
  position: relative;
  padding: 0 24px;
  display: flex;
  .legend-wrap {
    flex: 0 0 ~'calc(100% - 96px)';
    overflow: hidden;
    .legend-item-scroll {
      overflow: hidden;
    }
    .legend-item-wrap {
      display: flex;
      height: 20px;
      line-height: 20px;
      float: left;
      transition: transform 0.5s ease-in-out;
    }
    .legend-item {
      display: flex;
      align-items: center;
      padding-right: 12px;
      white-space: nowrap;
      cursor: pointer;
      &.unselected {
        opacity: 0.4;
      }
      .legend-color,
      .legend-name,
      .legend-option {
        display: inline-block;
        vertical-align: middle;
      }
      .legend-color {
        width: 8px;
        height: 8px;
        margin-right: 6px;
      }
      .legend-name {
        font-size: 12px;
        font-weight: 400;
        color: #545778;
        margin-right: 4px;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .legend-option {
        height: 16px;
        color: #d5dbe6;
        transition: color ease-in-out 0.2s, opacity ease-in-out 0.2s;
        opacity: 0;
        &:hover {
          color: #5d7092;
        }
      }
      .selected-legend-option {
        color: #5b8ff9;
        opacity: 1;
        &:hover {
          color: #5476d8;
        }
      }
      &:hover {
        .legend-option {
          opacity: 1;
        }
      }
    }
  }

  .page-wrap {
    flex: 0 0 96px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 20px;
    .page-prev,
    .page-next {
      cursor: pointer;
    }
  }

  .disabled {
    .ivu-icon {
      color: #c5c8ce;
    }
  }
}
</style>
