<template>
  <div class="page-div">
    <back-button />
    <div class="header">
      <h1 class="title">基金列表</h1>
    </div>
    <div class="info-card">
      <div class="tab-container">
        <button v-for="tab in tabList" :key="tab.dicKey" @click="activeTab = tab.dicKey"
            :class="{ 'active': activeTab === tab.dicKey }" class="tab-button">
          {{ tab.dicValue }}
        </button>
      </div>
    </div>
    <div class="grid">
      <van-grid :column-num="1" :gutter="16" :border="false">
        <van-grid-item v-for="item in fundList" :key="item.indexId">
          <div @touchstart="onTouchStart(item.fundName)" @touchend="onTouchEnd(item.fundName, 'fund-detail', item.fundId)" class="item"
            @touchcancel="onTouchCancel(item.fundName)" :class="{ 'tapped': tappedItem === item.fundName }">
            <div class="card-content" :style="{ backgroundColor: item.bgColor, borderLeftColor: item.color }">
              <div class="card-code" :style="{ color: item.color }">{{ item.fundName }}</div>
              <div class="d-flex">
                <div class="leftValue d-flex justify-center align-center pe-16">
                  <div class="text-center">
                    <div class="blue-color cagr">{{ item.cagr ? item.cagr + '%' : '暂无' }}</div>
                    <div class="tip">复合年增长率</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.fundId + ''"></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, watch, nextTick } from 'vue'
let tabList = ref<any[]>([])
import { sysDicListByType, stockAFundList, stockAFundInfo, stockAFundHisFundHisChart } from '@/utils/api'

const activeTab = ref('')
const init = async () => {
  const { data } = await sysDicListByType({ dicType: 'fund_type' })
  tabList.value = data
  activeTab.value = data[0].dicKey
}

watch(activeTab, () => {
  disposeAll()
  charts.value = []
  fundList.value = []
  handleTabChange()
})

import { colorList } from '@/utils/colorList'
let fundList = ref<any[]>([])
const handleTabChange = async () => {
  const { data } = await stockAFundList({ curPage: 1, limit: 999, fundType: activeTab.value })
  data.list.map((ele: any, index: number) => {
    ele.loading = true
    const colorIndex = index % colorList.length
    ele.color = colorList[colorIndex].color
    ele.bgColor = colorList[colorIndex].bgColor
    ele.cagr = ''
    ele.beginDay = ''
    ele.endDay = ''
  })
  charts.value = new Array(data.list.length).fill(null)
  fundList.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 < fundList.value.length ; i++) {
    if (fundList.value && fundList.value.length > i && !fundList.value[i].cagr) {
      const { data: info } = await stockAFundInfo(fundList.value[i].fundId)
      if (info && fundList.value[i]) {
        fundList.value[i].cagr = info.cagr
      }
    }
    if (fundList.value && fundList.value.length > i && fundList.value[i].loading) {
      const { data: chartData } = await stockAFundHisFundHisChart({ fundId: fundList.value[i].fundId })
      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 (fundList.value && fundList.value.length > i) {
          fundList.value[i].beginDay = sysDate[0]
          fundList.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 && fundList.value && fundList.value.length > i && document.getElementById(fundList.value[i].fundId)) {
        if (charts.value[i]) {
          charts.value[i]?.dispose()
          charts.value[i] = null
        }
        const chart = echarts.init(document.getElementById(fundList.value[i].fundId))
        chart.setOption(option)
        charts.value[i] = chart
        fundList.value[i].loading = false
      }
    }
  }
}

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

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

<style lang='scss' scoped>
.card-code {
  margin-bottom: 16px !important;
}
.leftValue {
  width: 96px;
  height: 100px;

  .cagr {
    font-size: 18px;
  }

  .tip {
    color: #666;
    margin-top: 12px;
  }
}

.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: 240px;
    .cagr {
      font-size: 24px;
    }
    .tip {
      margin-top: 16px;
      font-size: 14px;
    }
  }
  
  .chart-div {
    height: 80px;
  }
}
</style>
