<template>
  <div class="container" v-loading="loading">
    <PageHeader :title="$t('field.marketData')">
      <span class="updateTime">{{ $t('field.updateTime') }}：{{ updateTime }}</span>
      <template #icon>
        <i class="el-icon-refresh-right refresh-icon" @click="handleRefresh"></i>
      </template>
    </PageHeader>

    <div class="chartBox" >
      <div class="pairsBox">
        <div v-for="item in showData" :key="item.pairs"
          :class="['pairsItem', active === item.pairs ? 'activeItem' : '']" @click="handlePairs(item.pairs)">
          <div :class="[item.status === 'N' || item.status === '1' ? 'upValue' : 'downValue', 'num']">
            <div class="pairs">{{ item.pairs }}</div>
            <div style="margin-left:8px; margin-right: 6px;">{{ Number(item.currentValue).toFixed(4) }}</div>
            <i :class="[item.status === 'N' || item.status === '1' ? 'el-icon-top' : 'el-icon-bottom', 'icon']"></i>
            <!-- <i v-if="item.status === '1' || item.status === 'N'" class="el-icon-top upValue"
              style="font-size: 12px;font-weight: 800"></i>
            <i v-if="item.status === '0'" class="el-icon-bottom " style="font-size: 0.7vw;font-weight: 800"></i> -->
          </div>
        </div>
      </div>
      <div v-if="chartData.length" ref="marketDataCharts" id="marketDataCharts"></div>
      <Empty style="flex: 1;" v-else />
    </div>
  </div>
</template>

<script>
import PageHeader from '../../components/PageHeader.vue';
import { themeChangeMixin } from '@/mixins/themeChangeMixin'
import { chartThemeMap } from '../../common/chartTheme'
import { formatterDate } from '../../common/formatterFun.js'
import Empty from '../../components/Empty/index.vue'
export default {
  name: 'marketData',
  mixins: [themeChangeMixin],
  components: {
    PageHeader,
    Empty
  },
  data() {
    return {
      updateTime: '',
      active: '',
      loading: true,
      showData: [],
      chart: null,
      chartData: []
    }
  },
  watch: {
    theme(val) {
      this.chart?.clear()
      this.buildCharts()
    }
  },
  async mounted() {
    // await this.getCurrentDate()
    await this.getChartsData();
    window.addEventListener('resize', () => {
      // 调用图表实例的resize方法，使图表自适应
      this.chart?.resize();
    });
  },
  methods: {
    async getCurrentDate() {
      this.loading = true
      const res = await this.$apis.getSystemDate()
      this.loading = false
      if (res.success) {
        this.updateTime = res.data.result.datetime
      }
    },

    async handleRefresh() {
      await this.getChartsData()
      await this.getChartsData()
    },

    async getChartsData() {
      this.loading = true
      const res = await this.$apis.queryPriceList({})
      this.loading = false
      if (res.success) {
        this.showData = res.data.result
        this.handlePairs(this.showData[0]?.pairs)
      } else {
        this.chartData = []
        this.buildCharts()
      }
    },

    async handlePairs(pairs) {
      this.active = pairs
      this.loading = true
      const res = await this.$apis.queryHistoryPriceList({ 'queryParam.pairs': pairs })
      this.loading = false
      this.chart?.clear()
      this.chart = null
      if (res.success) {
        this.chartData = res.data.result
        this.buildCharts()
      } else {
        this.chartData = []
        this.buildCharts()
      }
    },

    buildCharts() {
      if (!this.chartData.length) return
      this.$nextTick(() => {
        if (!this.chart) {
          const chartEl = this.$refs.marketDataCharts
          this.chart = this.$echarts.init(chartEl);
        }
        const option = {
          tooltip: {
            // 提示tip
            show: true,
            trigger: 'axis',
            axisPointer: {
              show: true,
              type: 'line',
              snap: true
            }
          },
          grid: {
            left: 60, // 调整左侧边距，给纵坐标添加额外空间
            top: 40,
            right: 10,
            bottom: 20 // 调整底部边距，给横坐标添加额外空间
          },
          xAxis: {
            // 横坐标设置
            type: 'category',
            data: [],
            axisLabel: {
              interval: 'auto', // 设置横坐标文字全部显示
              color: chartThemeMap[this.theme]['axisColor'],
              fontSize: 10,
              textStyle: {
                color: chartThemeMap[this.theme]['axisColor']
              }
            },

            axisLine: {
              lineStyle: {
                color: chartThemeMap[this.theme]['axisColor']
              }
            }
          },
          yAxis: [
            {
              // 纵坐标设置
              type: 'value',
              name: this.$t('field.spotPrice'),
              scale: true,
              nameTextStyle: {
                color: chartThemeMap[this.theme]['axisColor']
              },
              axisLabel: {
                color: chartThemeMap[this.theme]['axisColor'],
                fontSize: 10,
              },
              splitLine: {
                lineStyle: {
                  color: chartThemeMap[this.theme]['splitLine']
                }
              },
              axisLine: {
                show: false,
              },
              axisTick: {
                show: false
              }
            }
          ],
          series: [
            {
              data: [],
              type: 'line',
              color: 'rgb(0, 108, 255)',
              smooth: true,
              areaStyle: { // 添加 areaStyle 属性
                color: 'rgba(0, 108, 255, 0.3)', // 设置背景色，可以是颜色值或渐变色等
                fontSize: 10,
              },
            }
          ]
        };
        const xArr = []
        const yArr = []
        this.chartData.forEach((item) => {
          xArr.push(formatterDate(item.time))
          yArr.push(Number(item.value).toFixed(4))
        })
        option.xAxis.data = xArr
        option.series[0].data = yArr
        this.chart.setOption(option);
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  padding: 8px 9px;
  // overflow-y: scroll;
}

.title {
  // height: 10px !important;
}

.updateTime {
  // margin-top: 5px;
  color: var(--color-44);
  font-size: 12px;
}

.chartBox {
  // flex-grow: 0;

  flex: auto;
  width: 100%;
  margin-top: 30px;
  // height: 17vh;
  display: flex;
  min-height: 0;
}

.pairsBox {
  font-size: 10px;
  width: 160px;
  height: 100%;
  overflow-y: auto;

  /* 滚动条整体样式 */
  &::-webkit-scrollbar {
    width: 8px;
    /* 垂直滚动条的宽度 */
    height: 8px;
    /* 水平滚动条的高度 */
  }

  /* 滚动条轨道 */
  // &::-webkit-scrollbar-track {
  //   background: #f1f1f1; /* 轨道的背景色 */
  //   border-radius: 10px; /* 轨道的圆角 */
  // }

  /* 滚动条滑块 */
  &::-webkit-scrollbar-thumb {
    background: var(--scrollBar);
    /* 滑块的背景色 */
    border-radius: 5px;
    /* 滑块的圆角 */
  }

  /* 滑块悬停样式 */
  &::-webkit-scrollbar-thumb:hover {
    background: var(--scrollBarHover);
    /* 悬停时滑块的背景色 */
  }

  .pairsItem {
    padding-left: 7px;
    font-weight: 700;

    .num {
      position: relative;
      display: flex;
      align-items: center;
      height: 30px;

      .icon {
        font-size: 14px;
        font-weight: 900;
      }
    }


    .pairs {
      font-size: 10px;
      color: var(--color-90);
    }

    .upValue {
      color: var(--red-60);
    }

    .downValue {
      color: var(--green-50);
    }
  }

  .activeItem {
    background: rgba(0, 255, 255, 0.07);
    border-radius: 2px;
    border: 1px solid rgba(0, 255, 255, 0.07);
  }
}

#marketDataCharts {
  flex: 1;
  margin-left: 12px;
  height: 100%;
}
</style>