<template>
  <div class="container" v-loading="loading">
    <PageHeader :title="$t('field.assetStatus')">
      <el-radio-group v-model="queryData.queryModule" @change="loadChartData" border size="medium">
        <el-radio-button v-for="label in labels" :key="label.id" :label="label.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: 150px" v-model="queryData.date" type="date" value-format="yyyyMMdd"
        :placeholder="$t('field.chooseDate')" :disabled="disabled" @change="loadChartData">
      </el-date-picker>
      <template #icon>
        <i class="el-icon-refresh-right refresh-icon" @click="handleRefresh"></i>
      </template>
    </PageHeader>

    <div v-if="(chartData.value && chartData.value.length || chartData.datals && chartData.datals)" ref="assetCharts"
      id="assetCharts"></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: 'assetStatus',
  mixins: [themeChangeMixin],
  components: {
    PageHeader,
    Empty
  },
  data() {
    return {
      labels: [
        {
          id: 1,
          value: 'folder',
          label: this.$t('field.folderPl')
        },
        {
          id: 2,
          value: 'product',
          label: this.$t('field.productPl')
        },
        {
          id: 3,
          value: 'ccy',
          label: this.$t('field.ccyPl')
        },
        {
          id: 4,
          value: 'term',
          label: this.$t('field.termPl')
        }
      ],
      selectOptions: [],
      queryData: {
        queryModule: '',
        dateType: '',
        date: ''
      },
      disabled: true,
      loading: true,
      folderObj: {},
      chart: null,
      chartData: {},
      plType: '',
      timer: null
    }
  },
  watch: {
    async theme(val) {
      this.chart?.clear()
      if (this.plType === 'ccy') {
        await this.buildCcyCharts()
      } else if (this.plType === 'term') {
        await this.buildTermCharts()
      } else {
        await this.buildCharts()
      }
    }
  },
  mounted() {
    this.$bus.$on('folderChange', (folderObj) => {
      if (folderObj.folder) {
        this.folderObj = { ...folderObj }
        this.initData()
      }
    })

    this.selectOptions = dateType
    this.queryData.dateType = this.selectOptions[0].value
    this.folderObj.folder && this.initData()
    this.disabled = this.queryData.dateType === 'RealTime'

    
    this.timer = setInterval(() => {
      this.loadChartData()
    }, 20000)
  },
  destroyed() {
    clearInterval(this.timer)
  },
  methods: {
    async initData() {
      this.loading = true
      const timeRes = await this.$apis.getSystemDate()
      this.loading = false
      if (timeRes.success) {
        if (this.disabled) {
          this.queryData.date = ''
        } else {
          this.queryData.date = `${timeRes.data.result.date}`
        }
      }
      this.queryData.queryModule = this.labels[0].label
      await this.loadChartData()
    },

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

    async loadChartData() {
      const date = dayjs(this.queryData.date).format('YYYYMMDD')
      this.plType = this.labels.find(item => item.label === this.queryData.queryModule)?.value
      const dateType = this.queryData.dateType
      const folder = this.folderObj.folder
      const pnlCcy = this.folderObj.pnlCcy
      const param = { 
        'queryParam.date': date, 
        'queryParam.plType': this.plType,
        'queryParam.dateType': dateType,
        'queryParam.folder': folder,
        'queryParam.pnlCcy': pnlCcy 
      }
      this.loading = true

      let res = {}
      if (this.plType === 'term') {
        res = await this.$apis.queryTermCash(param)
      } else {
        res = await this.$apis.queryPlChartByType(param)
      }
      this.loading = false
      this.chart?.clear()
      this.chart = null
      if (res.success) {
        if (this.plType === 'ccy') {
          this.chartData = res.data.result
          await this.buildCcyCharts()
        } else if (this.plType === 'term') {
          this.chartData = res.data?.result?.data?.result
          await this.buildTermCharts()
        } else {
          this.chartData = res.data.result
          await this.buildCharts()
        }
      }
    },

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

    // 构建账户损益，产品损益图表
    async buildCharts() {
      if (!this.chartData.value?.length) return
      await this.$nextTick()
      if (!this.chart) {
        const chartEl = this.$refs['assetCharts']
        this.chart = this.$echarts.init(chartEl);
      }
      const option = {
        legend: {
          right: 0,
          top: 5,
          textStyle: {
            color: chartThemeMap[this.theme]['legendText']
          }
        },
        tooltip: {
          // 提示tip
          show: true,
          trigger: 'axis',
          axisPointer: {
            show: true,
            type: 'line',
            snap: true
          }
        },
        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']
            }
          },
          axisTick: {
            show: true,
            color: chartThemeMap[this.theme]['axisColor']
          }
        },
        yAxis: [
          {
            // 纵坐标设置
            type: 'value',
            name: this.$t('field.wYuan'),
            scale: true,
            nameTextStyle: {
              color: chartThemeMap[this.theme]['axisColor']
            },
            axisLabel: {
              // label格式化
              formatter: function (value) {
                if (value === 0) {
                  return '0';
                }
                return Number(value / 10000).toFixed(2);
              },
              color: chartThemeMap[this.theme]['axisColor'],
              fontSize: 10
            },
            splitLine: {
              lineStyle: {
                color: chartThemeMap[this.theme]['splitLine']
              }
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            }
          }
        ],
        series: [
          // 具体数据以及图表形状
          {
            data: [],
            type: 'bar',
            color: chartThemeMap[this.theme]['serie_1'],
            name: this.$t('field.cash'),
            barWidth: 16 // 调整柱状图宽度
          },
          {
            data: [],
            type: 'bar',
            color: chartThemeMap[this.theme]['serie_2'],
            name: this.$t('field.pv'),
            barWidth: 16 // 调整柱状图宽度
          },
          {
            data: [],
            type: 'bar',
            color: chartThemeMap[this.theme]['serie_3'],
            name: this.$t('field.pnlYear'),
            barWidth: 16 // 调整柱状图宽度
          },
          {
            data: [],
            type: 'bar',
            color: chartThemeMap[this.theme]['serie_4'],
            name: this.$t('field.pnlDay'),
            barWidth: 16 // 调整柱状图宽度
          }
        ]
      };
      const cashArr = []
      const pvArr = []
      const pnlYearArr = []
      const pnlDayArr = []

      this.chartData.value?.forEach((item) => {
        if (cashArr.length < 5) {
          cashArr.push(item.cash)
          pvArr.push(item.pv)
          pnlYearArr.push(item.pnlYear)
          pnlDayArr.push(item.pnlDay)
        }
      })
      option.series[0].data = cashArr
      option.series[1].data = pvArr
      option.series[2].data = pnlYearArr
      option.series[3].data = pnlDayArr

      option.xAxis.data = this.chartData.title?.slice(0, 5)

      this.chart.setOption(option);
      // 监听窗口大小改变事件
      window.addEventListener('resize', () => {
        // 调用图表实例的resize方法，使图表自适应
        this.chart?.resize();
      });
    },

    // 构建货币图表
    async buildCcyCharts() {
      if (!this.chartData.value?.length) return
      await this.$nextTick()
      if (!this.chart) {
        const chartEl = this.$refs['assetCharts']
        this.chart = this.$echarts.init(chartEl);
      }
      const option = {
        legend: {
          right: 0,
          top: 0,
          textStyle: {
            color: chartThemeMap[this.theme]['color']
          }
        },
        tooltip: {
          // 提示tip
          show: true,
          trigger: 'axis',
          axisPointer: {
            show: true,
            type: 'line',
            snap: true
          }
        },
        grid: {
          left: 55, // 调整左侧边距，给纵坐标添加额外空间
          top: 40,
          right: 10,
          bottom: 20 // 调整底部边距，给横坐标添加额外空间
        },
        xAxis: {
          // 横坐标设置
          type: 'category',
          data: [],
          axisLabel: {
            interval: 0, // 设置横坐标文字全部显示
            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.wYuan'),
            scale: true,
            nameTextStyle: {
              color: chartThemeMap[this.theme]['axisColor']
            },
            axisLabel: {
              // label格式化
              formatter: function (value) {
                if (value === 0) {
                  return '0';
                }
                return Number(value / 10000).toFixed(2);
              },
              color: chartThemeMap[this.theme]['axisColor'],
              fontSize: 10,
              textStyle: {
                color: chartThemeMap[this.theme]['axisColor']
              }
            },
            splitLine: {
              lineStyle: {
                color: chartThemeMap[this.theme]['splitLine']
              }
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            }
          }
        ],
        series: [
          // 具体数据以及图表形状
          {
            data: [],
            type: 'bar',
            name: this.$t('field.ccyPl'),
            color: chartThemeMap[this.theme]['serie_1'],
            barWidth: 16 // 调整柱状图宽度
          }
        ]
      };
      option.series[0].data = this.chartData.value?.slice(0, 5)
      option.xAxis.data = this.chartData.title?.slice(0, 5)

      this.chart.setOption(option);
      // 监听窗口大小改变事件
      window.addEventListener('resize', () => {
        // 调用图表实例的resize方法，使图表自适应
        this.chart.resize();
      });
    },

    // 构建期限图表
    async buildTermCharts() {
      if (!this.chartData.datals?.length) return
      await this.$nextTick()
      if (!this.chart) {
        const chartEl = this.$refs['assetCharts']
        this.chart = this.$echarts.init(chartEl);
      }
      const option = {
        legend: {
          // 显示图例
          show: true,
          // 在右上角放置图例
          // 也可以设置 'left', 'right', 'center'
          // 以及 'top', 'bottom', 'middle'
          right: 10,
          top: 10,
          // 设置图例的数据
          data: [],
          textStyle: {
            color: chartThemeMap[this.theme]['legendText']
          }
        },
        tooltip: {
          // 提示tip
          show: true,
          trigger: 'axis',
          axisPointer: {
            show: true,
            type: 'line',
            snap: true
          }
        },
        color: [
          '#FF0000', '#FFFF00', '#800080', '#0000FF', '#FFA500',
          '#00FF00', '#FFC0CB', '#00FFFF', '#FFD700', '#8B0000',
          '#00008B', '#006400', '#FF8C00', '#4B0082', '#808000',
          '#C71585', '#008080', '#B8860B', '#ADD8E6', '#90EE90'
        ],
        grid: {
          left: 55, // 调整左侧边距，给纵坐标添加额外空间
          top: 40,
          right: 10,
          bottom: 20 // 调整底部边距，给横坐标添加额外空间
        },
        xAxis: {
          // 横坐标设置
          type: 'category',
          data: [],
          axisLabel: {
            interval: 0, // 设置横坐标文字全部显示
            color: chartThemeMap[this.theme]['axisColor'],
            textStyle: {
              color: chartThemeMap[this.theme]['axisColor']
            }
          },
          axisLine: {
            lineStyle: {
              color: chartThemeMap[this.theme]['axisColor']
            }
          }
        },
        yAxis: [
          {
            // 纵坐标设置
            type: 'value',
            name: this.$t('field.wYuan'),
            scale: true,
            nameTextStyle: {
              color: chartThemeMap[this.theme]['axisColor']
            },
            axisLabel: {
              // label格式化
              formatter: function (value) {
                if (value === 0) {
                  return '0';
                }
                return value / 10000;
              },
              color: chartThemeMap[this.theme]['axisColor'],
              textStyle: {
                color: chartThemeMap[this.theme]['axisColor']
              },
              fontSize: 10
            },
            splitLine: {
              lineStyle: {
                color: chartThemeMap[this.theme]['splitLine']
              }
            },
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            }
          }
        ],
        series: []
      };
      option.xAxis.data = this.chartData.termList
      this.chartData.datals?.slice(0, 5)?.forEach((item) => {
        const line = {
          data: [],
          type: 'line'
        }
        this.chartData.termList.forEach((term) => {
          line.data.push(item[term] || 0)
          line.name = item.currency
          option.legend.data.push(item.currency)
        })
        option.series.push(line)
      })
      this.chart.setOption(option);
      // 监听窗口大小改变事件
      window.addEventListener('resize', () => {
        // 调用图表实例的resize方法，使图表自适应
        this.chart.resize();
      });
    }
  }
}
</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;
}

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