<template>
  <div class="container" v-loading="loading">
    <PageHeader :title="$t('field.profitLoss')">
      <el-radio-group v-model="queryData.queryModule" @change="getChartsData" border size="medium">
        <el-radio-button v-for="item in labels" :key="item.value" :label="item.label"></el-radio-button>
      </el-radio-group>
      <el-select style="margin: 0px 8px 0px 8px; width: 70px" v-model="queryData.dateType"
        :placeholder="$t('field.pleaseChoose')" @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" v-model="queryData.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.length" ref="profitLossCharts" id="profitLossCharts"></div>
    <Empty v-else />
  </div>
</template>

<script>
import dayjs from 'dayjs'
import PageHeader from '../../components/PageHeader.vue';
import { dateType } from '../../common/dataSource.js'
import { formatterDate } from '../../common/formatterFun.js'
import { themeChangeMixin } from '@/mixins/themeChangeMixin'
import { chartThemeMap } from '../../common/chartTheme'
import Empty from '../../components/Empty/index.vue'
export default {
  name: 'profitLoss',
  mixins: [themeChangeMixin],
  components: {
    PageHeader,
    Empty
  },
  data() {
    return {
      labels: [
        { label: this.$t('field.yearProfitLoss'), value: 'YEAR' },
        { label: this.$t('field.monthProfitLoss'), value: 'MONTH' },
        { label: this.$t('field.dayProfitLoss'), value: 'DAY' }
      ],
      selectOptions: [],
      queryData: {
        queryModule: '',
        dateType: '',
        date: ''
      },
      disabled: false,
      loading: true,
      folderObj: {},
      chart: null,
      chartData: [],
      plType: '',
      timer: null
    };
  },
  watch: {
    async theme(val) {
      this.chart?.clear()
      await this.buildCharts()
    }
  },
  mounted() {
    this.$bus.$on('folderChange', (folderObj) => {
      if (folderObj.folder) {
        this.folderObj = { ...folderObj }
        this.getChartsData();
      }
    })

    this.queryData.queryModule = this.labels[0].label
    this.selectOptions = dateType
    this.queryData.dateType = 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)
  },
  methods: {
    // 获取数据
    async getChartsData(e) {
      const plType = this.labels.find(item => item.label === this.queryData.queryModule)?.value
      let folder = this.folderObj.folder
      if (folder && folder.split('@@')[0] === 'F') {
        folder = folder.split('@@')[1]
      }
      let startDate = ''
      let endDate = ''
      if (this.queryData.date?.length === 2) {
        startDate = dayjs(this.queryData.date[0]).format('YYYYMMDD')
        endDate = dayjs(this.queryData.date[1]).format('YYYYMMDD')
      }
      this.loading = true
      const param = {
        'queryParam.plType': plType,
        'queryParam.dateType': this.queryData.dateType,
        'queryParam.startDate': startDate,
        'queryParam.endDate': endDate,
        'queryParam.folder': folder
      }
      const res = await this.$apis.queryPlByType(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])
          }
        }
      }
      this.chart?.clear()
      this.chart = null
      await this.buildCharts();
    },

    async handleRefresh() {
      this.folderObj.folder && this.getChartsData()
    },

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

    // 构建图表
    async buildCharts() {
      if (!this.chartData.length) return
      await this.$nextTick()
      if (!this.chart) {
        const chartEl = this.$refs['profitLossCharts']
        this.chart = this.$echarts.init(chartEl);
      }
      const that = this
      const option = {
        legend: {
          // 图例配置
          data: [
            {
              name: this.queryData.queryModule,
              icon: 'roundRect'
            },
            {
              name: `${this.queryData.queryModule}${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: 'auto', // 设置横坐标文字全部显示
            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: 'line',
            color: chartThemeMap[this.theme]['serie_1'],
            areaStyle: { // 添加 areaStyle 属性
              color: '#BFDAFF', // 设置背景色，可以是颜色值或渐变色等
              fontSize: 10
            },
            smooth: true,
            name: this.queryData.queryModule,
            barWidth: 26 // 调整柱状图宽度
          },
          {
            data: [],
            type: 'line',
            color: chartThemeMap[this.theme]['serie_2'],
            areaStyle: { // 添加 areaStyle 属性
              color: '#E3F8ED', // 设置背景色，可以是颜色值或渐变色等
              fontSize: 10
            },
            smooth: true,
            name: `${this.queryData.queryModule}${this.$t('field.limitValue')}`
          }
        ]
      };
      const xArr = [];
      const valueArr = [];
      const limitArr = [];
      this.chartData.forEach((item) => {
        xArr.push(formatterDate(item.indexId));
        valueArr.push(item.realAmount);
        limitArr.push(item.limitAmt);
      });
      option.xAxis.data = xArr;
      option.series[0].data = valueArr;
      option.series[1].data = limitArr;
      this.chart.setOption(option);

    }
  }
};
</script>

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

// ::v-deep .el-radio-button__orig-radio:checked+.el-radio-button__inner {
//   color: #409eff;
//   background-color: white;
// }


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