<template>
  <div class="page-div">
    <back-button />
    <div class="header">
      <h1 class="title">组合列表</h1>
    </div>
    <div class="grid">
      <van-grid :column-num="1" :gutter="16" :border="false">
        <van-grid-item v-for="item in list" :key="item.id">
          <div @touchstart="onTouchStart(item.stockGroupName)" @touchend="onTouchEnd(item.stockGroupName, 'group-detail', item.id)" class="item"
            @touchcancel="onTouchCancel(item.stockGroupName)" :class="{ 'tapped': tappedItem === item.stockGroupName }">
            <div class="card-content" :style="{ backgroundColor: item.bgColor, borderLeftColor: item.color }">
              <div class="card-code" :style="{ color: item.color }">{{ item.stockGroupName }}</div>
              <div class="d-flex">
                <div class="leftValue d-flex justify-center align-center pe-16">
                  <div>
                    <div class="card-name">累计收益率：
                      <span :class="item.totalIncomeRate > 0 ? 'red-color' : item.totalIncomeRate < 0 ? 'green-color' : ''">{{ item.totalIncomeRate }}%</span></div>
                    <div class="card-note">建仓日期：{{ item.createDate }}</div>
                  </div>
                </div>
                <div class="rightChart flex-1 d-flex justify-center align-center">
                  <van-loading v-show="item.loading" type="spinner" color="#1989fa" class="loading" />
                  <div style="width: 100%;">
                    <div class="chart-div" :id="item.id + ''"></div>
                    <div class="d-flex justify-between">
                      <div class="tip">{{ item.beginDay }}</div>
                      <div class="tip">{{ item.endDay }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script setup lang="ts">
import BackButton from '@/components/back-button.vue'

import { tapMixins } from '@/mixins/tap-mixins'
const { tappedItem, onTouchStart, onTouchEnd, onTouchCancel } = tapMixins()

import { ref, onMounted, nextTick, watch } from 'vue'
let list = ref<any[]>([])
import { groupList, groupHisChartIncomeRate } from '@/utils/api'
import { colorList } from '@/utils/colorList'

const init = async () => {
  const { data } = await groupList('curPage=1&limit=999&isPublic=1,2')
  data.list.map((ele: any, index: number) => {
    const colorIndex = index % colorList.length
    ele.color = colorList[colorIndex].color
    ele.bgColor = colorList[colorIndex].bgColor
    ele.totalIncomeRate = ele.holdInfo && ele.holdInfo.totalIncomeRate ? ele.holdInfo.totalIncomeRate : ''
    ele.loading = true
    ele.beginDay = ''
    ele.endDay = ''
  })
  charts.value = new Array(data.list.length).fill(null)
  list.value = data.list
  nextTick(() =>{
    setData()
  })
}

import { chartMixins } from '@/mixins/chart-mixins'
const { charts, destroyedFlag, disposeAll } = chartMixins()
import * as echarts from 'echarts'
import { getLineSeries, getBaseOption, getXAxis, getYAxis } from '@/utils/chart'
const setData = async() => {
  for (let i = 0 ; i < list.value.length ; i++) {
    if (list.value && list.value.length > i && list.value[i].loading) {
      const { data: chartData } = await groupHisChartIncomeRate({ groupId: list.value[i].id })
      const sysDate: any = []
      const seriesData: any = []
      chartData.forEach((ele: any) => {
        sysDate.push(ele.sysDate)
        seriesData.push({ value: ele.nav })
      })
      const markPoint = []
      if (seriesData.length > 0) {
        if (list.value && list.value.length > i) {
          list.value[i].beginDay = sysDate[0]
          list.value[i].endDay = sysDate[sysDate.length - 1]
        }
        markPoint.push({
          symbolSize: 30,
          coord: [0, seriesData[0].value],
          label: {
            formatter: function () {
              return seriesData[0].value
            },
            color: '#ff0000',
          },
          itemStyle: {
            color: 'rgba(0,0,0,0)'
          }
        })
        markPoint.push({
          symbolSize: 30,
          coord: [sysDate.length - 1, seriesData[seriesData.length - 1].value],
          label: {
            formatter: function () {
              return seriesData[seriesData.length - 1].value
            },
            color: '#ff0000',
          },
          itemStyle: {
            color: 'rgba(0,0,0,0)'
          }
        })
      }
      const series = [
        getLineSeries({ data: seriesData, name: '累计收益率', markPoint: { data : markPoint } }),
      ]
      const option = getBaseOption({
        yAxis: [getYAxis({ showFlag: false })],
        xAxis: [getXAxis({ data: sysDate, showFlag: false })],
        series: series,
        grid: [{ top: '20px', bottom: '1px', left: '20px', right: '20px' }]
      })
      if (!destroyedFlag.value && list.value && list.value.length > i && document.getElementById(list.value[i].id)) {
        if (charts.value[i]) {
          charts.value[i]?.dispose()
          charts.value[i] = null
        }
        const chart = echarts.init(document.getElementById(list.value[i].id))
        chart.setOption(option)
        charts.value[i] = chart
        list.value[i].loading = false
      }
    }
  }
}

import { useRoute } from 'vue-router'
const route = useRoute()
watch(
  () => route.fullPath,
  (newPath, oldPath) => {
    if (oldPath?.includes('target-table')) {
      nextTick(() => {
        init()
      })
    } else if (oldPath?.includes('group-detail')) {
      nextTick(() => {
        setData()
      })
    }
    if (newPath?.includes('target-table')) {
      disposeAll()
      charts.value = []
      list.value = []
    }
  },
  { immediate: true }
)

onMounted (() =>{
  init()
})
</script>

<style lang='scss' scoped>
.leftValue {
  width: 160px;
  height: 100px;
}

.rightChart {
  width: 100%;
  height: 100px;
  position: relative;

  .loading {
    position: absolute;
    z-index: 2;
  }

  .chart-div {
    height: 80px;
    width: 100%;
  }
}


@media screen and (min-width: 768px) {
  .grid {
    padding: 0 24px;
  }
  
  .card-content {
    padding: 24px;
  }
  
  .card-code {
    margin-bottom: 24px !important;
    font-size: 18px;
  }
  
  .leftValue {
    width: 280px;
  }
  
  .chart-div {
    height: 80px;
  }
}
</style>
