<template>
  <div class="container" v-loading="loading">
    <PageHeader :title="$t('field.riskPos')">
      <el-select v-model="selectValue" :placeholder="$t('field.pleaseChoose')" style="width: 70px"
        @change="dateTypeChange">
        <el-option v-for="item in selectOptions" :key="item.value" :label="$t(`field.${item.value}`)"
          :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker style="width: 250px;margin-left: 8px;" v-model="date" type="daterange" value-format="yyyyMMdd"
        :start-placeholder="$t('field.startDate')" :end-placeholder="$t('field.endDate')" :disabled="disabled"
        @change="getChartsData">
      </el-date-picker>
      <template #icon>
        <i class="el-icon-refresh-right refresh-icon" @click="handleRefresh"></i>
      </template>
    </PageHeader>

    <div v-if="chartData && chartData.length" ref="riskPosCharts" id="riskPosCharts"></div>
    <Empty v-else />
  </div>
</template>

<script>
import dayjs from 'dayjs'
import PageHeader from '../../components/PageHeader.vue';
import { dateType } from '../../common/dataSource.js'
import { themeChangeMixin } from '@/mixins/themeChangeMixin'
import { chartThemeMap } from '../../common/chartTheme'
import Empty from '../../components/Empty/index.vue'
export default {
  name: 'riskPos',
  mixins: [themeChangeMixin],
  components: {
    PageHeader,
    Empty
  },
  data() {
    return {
      selectOptions: [],
      selectValue: '',
      loading: true,
      date: '',
      disabled: false,
      folderObj: {},
      chart: null,
      chartData: [],
      timer: null
    };
  },
  async mounted() {
    this.$bus.$on('folderChange', (folderObj) => {
      if (folderObj.folder) {
        this.folderObj = { ...folderObj }
        this.getChartsData();
      }
    })

    this.selectOptions = dateType
    this.selectValue = this.selectOptions[0].value
    this.disabled = true

    this.folderObj.folder && this.getChartsData()

    window.addEventListener('resize', () => {
      // 调用图表实例的resize方法，使图表自适应
      this.chart?.resize();
    });

    this.timer = setInterval(() => {
      this.getChartsData()
    }, 20000)
  },
  destroyed() {
    clearInterval(this.timer)
  },
  watch: {
    async theme(val) {
      this.chart?.clear()
      await this.buildCharts()
    }
  },
  methods: {
    async handleRefresh() {
      this.folderObj.folder && this.getChartsData()
    },

    async getChartsData() {
      let folder = this.folderObj.folder
      if (folder && folder.split('@@')[0] === 'F') {
        folder = folder.split('@@')[1]
      }
      let startDate = ''
      let endDate = ''
      if (this.date?.length === 2) {
        startDate = dayjs(this.date[0]).format('YYYYMMDD')
        endDate = dayjs(this.date[1]).format('YYYYMMDD')
      }
      const param = {
        'queryParam.dateType': this.selectValue,
        'queryParam.startDate': startDate,
        'queryParam.endDate': endDate,
        'queryParam.folder': folder
      }
      this.loading = true
      const res = await this.$apis.queryRiskPositionByType(param)
      this.loading = false
      this.chartData = []
      if (res.success) {
        const data = res.data.result?.domain;
        if (!data?.unit) {
          for (const key in data) {
            this.chartData.push({ ...data[key], indexId: key })
          }
        }
      }
      this.chart?.clear()
      this.chart = null
      await this.buildCharts();
    },

    dateTypeChange(type) {
      if (type === 'RealTime') {
        this.date = ''
        this.disabled = true
      } else {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        this.date = [start, end]
        this.disabled = false
      }
      this.getChartsData()
    },

    async buildCharts() {
      if (!this.chartData.length) return
      await this.$nextTick()
      if (!this.chart) {
        const chartEl = this.$refs['riskPosCharts']
        this.chart = this.$echarts.init(chartEl);
      }
      const that = this
      const option = {
        legend: {
          // 图例配置
          data: [
            {
              name: this.$t('field.riskValue'),
              icon: 'roundRect'
            },
            {
              name: this.$t('field.limitValue'),
              icon: 'roundRect'
            }
          ],
          right: 0,
          top: 5,
          textStyle: {
            color: chartThemeMap[this.theme]['legendText']
          }
        },
        tooltip: {
          // 提示tip
          show: true,
          trigger: 'axis',
          axisPointer: {
            show: true,
            type: 'line',
            snap: true
          },
          formatter(params) {
            const titles = [params[0].name + ':'];
            params.forEach(item => {
              let seriesItem = option.series.find(series => series.name === item.seriesName);
              titles.push(`<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:${seriesItem.color}"></span>
              ${item.seriesName}：${item.value.toFixed(6)}${that.$t('field.wYuan')}`);
            });
            return titles.join('<br />');
          }
        },
        grid: {
          left: 55, // 调整左侧边距，给纵坐标添加额外空间
          top: 40,
          right: 10,
          bottom: 20 // 调整底部边距，给横坐标添加额外空间
        },
        xAxis: {
          // 横坐标设置
          type: 'category',
          data: [],
          axisLabel: {
            interval: 0, // 设置横坐标文字全部显示
            color: chartThemeMap[this.theme]['axisColor'],
            fontSize: 10,
          },

          axisLine: {
            lineStyle: {
              color: chartThemeMap[this.theme]['axisColor']
            }
          }
        },
        yAxis: [
          {
            // 纵坐标设置
            type: 'value',
            name: this.$t('field.wYuan'),
            nameTextStyle: {
              color: chartThemeMap[this.theme]['axisColor']
            },
            axisLabel: {
              // label格式化
              formatter: function (value) {
                if (value === 0) {
                  return '0';
                }
                return value
              },
              color: chartThemeMap[this.theme]['axisColor'],
              fontSize: 10,
            },
            splitLine: {
              lineStyle: {
                color: chartThemeMap[this.theme]['splitLine']
              }
            },
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            }
          }
        ],
        series: [
          // 具体数据以及图表形状
          {
            data: [],
            type: 'bar',
            color: chartThemeMap[this.theme]['serie_1'],
            name: this.$t('field.riskValue'),
            label: {
              color: '#fff'
            },
            barWidth: 26 // 调整柱状图宽度
          },
          {
            data: [],
            type: 'line',
            color: chartThemeMap[this.theme]['serie_2'],
            name: this.$t('field.limitValue')
          }
        ]
      };
      const xArr = []
      const riskArr = []
      const limitArr = []
      this.chartData.forEach((item) => {
        xArr.push(item.indexId)
        riskArr.push(item.realAmount)
        limitArr.push(item.limitAmt)
      })
      option.xAxis.data = xArr
      option.series[0].data = riskArr
      option.series[1].data = limitArr
      this.chart.setOption(option);
      // 监听窗口大小改变事件

    }
  }
};
</script>

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

#riskPosCharts {
  width: 80%;
  flex: 1;
  min-height: 0px;
  margin-top: 8px;
  margin-left: auto;
  margin-right: auto;
}
</style>
