<template>
  <div class="page-div">
    <back-button />
    <div class="header">
      <div class="header-content">
        <h1 class="title">{{ indexData?.indexCode }}</h1>
        <p class="subtitle">{{ indexData?.indexName || '指数详情' }}</p>
      </div>
    </div>
    <div class="info-card">
      <div class="d-flex justify-content-between align-items-center">
        <div class="f-b">相关文件</div>
        <div v-if="fileList.length > 0" @click="handleViewDetails" class="blue-color">
          查看详情
        </div>
        <div v-else class="red-color">暂无数据</div>
      </div>
    </div>
    <div class="info-card">
      <h3 class="card-title">指数走势图</h3>
      <div class="chart-container">
        <van-loading v-show="chartList[0].loading" type="spinner" color="#1989fa" class="loading" />
        <div :id="`${chartList[0].id}`" class="chartDiv"></div>
      </div>
    </div>
    <div class="info-card">
      <h3 class="card-title">追踪汇总图</h3>
      <div class="chart-container">
        <van-loading v-show="chartList[1].loading" type="spinner" color="#1989fa" class="loading" />
        <div :id="`${chartList[1].id}`" class="chartDiv"></div>
      </div>
    </div>
    <div class="info-card">
      <div class="tab-container">
        <button @click="activeTab = 0" :class="{ 'active': activeTab === 0 }" class="tab-button">行业</button>
        <button @click="activeTab = 1" :class="{ 'active': activeTab === 1 }" class="tab-button">指数持仓</button>
        <button @click="activeTab = 2" :class="{ 'active': activeTab === 2 }" class="tab-button">跟踪基金</button>
      </div>
    </div>
    <div v-if="activeTab === 0">
      <div class="info-card">
        <h3 class="card-title">一级行业</h3>
        <div class="chart-container">
          <van-loading v-show="chartList[2].loading" type="spinner" color="#1989fa" class="loading" />
          <div :id="`${chartList[2].id}`" class="chartDiv"></div>
        </div>
      </div>
      <div class="info-card">
        <h3 class="card-title">二级行业</h3>
        <div class="chart-container">
          <van-loading v-show="chartList[3].loading" type="spinner" color="#1989fa" class="loading" />
          <div :id="`${chartList[3].id}`" class="chartDiv"></div>
        </div>
      </div>
    </div>
    <div v-if="activeTab === 1">
      <div class="info-card">
        <div class="tableDiv">
          <table border="1">
            <thead>
              <tr>
                <th class="td--column--1">名称</th>
                <th>上期权重</th>
                <th>本期权重</th>
                <th>权重变化</th>
                <th>排名</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="index in indexDetailList" :key="index.id">
                <td class="td--column--1">
                  {{ index.ticker }}
                  <div class="van-ellipsis firstTd">{{ index.tickerName }}</div>
                </td>
                <td>{{ index.lastQuarterWeight ? index.lastQuarterWeight + '%' : '' }}</td>
                <td>{{ index.weight ? index.weight + '%' : '' }}</td>
                <td :class="index.weightChange > 0 ? 'red-color' : index.weightChange < 0 ? 'green-color' : ''">
                  {{ index.weightChange ? index.weightChange + '%' : '' }}</td>
                <td>{{ index.rankNum }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <div v-if="activeTab === 2">
      <div class="info-card">
        <div class="tableDiv">
          <table border="1">
            <thead>
              <tr>
                <th class="td--column--1">名称</th>
                <th>净资产(亿)</th>
                <th>净值</th>
                <th>股本(亿)</th>
                <th>调整日</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="fund in fundList" :key="fund.id" @click="$router.push({ name: 'etf-detail', params: { id: fund.etfCode } })">
                <td class="td--column--1">
                  {{ fund.etfCode }}
                  <div class="van-ellipsis firstTd">{{ fund.etfName }}</div>
                </td>
                <td>{{ fund.netAssets }}</td>
                <td>{{ fund.nav }}</td>
                <td>{{ fund.sharesOutstanding }}</td>
                <td><div v-html="fund.day"></div></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
  <van-popup v-model:show="showFileListPopup" position="bottom" :style="{ height: '70%' }">
    <div class="p-16">
      <div class="d-flex justify-content-between items-center mb-16">
        <div class="sub-title f-b">文件列表</div>
        <van-icon name="close" @click="showFileListPopup = false" />
      </div>
      <div class="file-list">
        <div v-for="(file, index) in fileList" :key="index" class="file-item">
          <a :href="file.link" target="_blank" class="file-link">
            <i class="iconfont" :class="`icon-${file.type}`"></i>
            <span class="file-title van-ellipsis">{{ file.title }}</span>
          </a>
        </div>
      </div>
    </div>
  </van-popup>
</template>
<script setup lang='ts'>
import BackButton from '@/components/back-button.vue'

import { ref, onMounted, watch, nextTick } from 'vue'

import { useRoute } from 'vue-router'
const route = useRoute()

const loadFlag = ref(false)
watch(
  () => route.fullPath,
  (newPath, oldPath) => {
    if (oldPath?.includes('index-list') && newPath?.includes('index-detail') && loadFlag.value) {
      activeTab.value = 0
      charts.value = [null, null, null, null]
      nextTick(() => {
        init()
      })
    }
    if (newPath?.includes('index-list')) {
      disposeAll()
    }
  },
  { immediate: true }
)

import { indexInfo, indexInfoIndexHistChart, indexFundHisQueryFundHis, indexInfoIndustry1Chart, indexInfoIndustry2Chart, indexFundList } from '@/utils/api'
const indexData: any = ref(null)
const fileList = ref<any[]>([])
const indexDetailList = ref<any[]>([])
const fundList = ref<any[]>([])
import { addOrSubtractTime, formatNumberByUnit } from '@/utils'

const firstIndustry = ref<any[]>([])
const secondIndustry = ref<any[]>([])
import * as echarts from 'echarts'
import { getLineSeries, getBaseOption, getXAxis, getYAxis } from '@/utils/chart'
const init = async () => {
  try {
    const { data } = await indexInfo(route.params.id + '')
    indexData.value = data
    if (data.indexDescription) {
      const list = JSON.parse(data.indexDescription).data
      const reg1 = /(\.xls|\.xlsx)$/
      const reg2 = /(\.pdf)$/
      const reg3 = /(\.doc|\.docx)$/
      const reg4 = /(\.ppt|\.pptx)$/
      list.map((ele: any) => {
        if (reg1.test(ele.link)) {
          ele.type = 'excel'
        }
        if (reg2.test(ele.link)) {
          ele.type = 'pdf'
        }
        if (reg3.test(ele.link)) {
          ele.type = 'word'
        }
        if (reg4.test(ele.link)) {
          ele.type = 'ppt'
        }
      })
      fileList.value = list
    }
    indexDetailList.value = data.indexDetailList
    const { data: indexHist } = await indexInfoIndexHistChart(route.params.id + '')
    setLineChart(indexHist, 0)
    const { data: fundsHis } = await indexFundHisQueryFundHis({
      indexId: route.params.id + '',
      timeB: addOrSubtractTime(new Date(), -3, 'year'),
      timeE: new Date().toISOString().split('T')[0]
    })
    setLineChart(fundsHis, 1)
    const { data: firstIndustryData } = await indexInfoIndustry1Chart(route.params.id + '')
    firstIndustryData.map((ele: any) => {
      ele.name = ele.industry1_name
      ele.value = ele.weight
    })
    firstIndustry.value = firstIndustryData
    const { data: secondIndustryData } = await indexInfoIndustry2Chart(route.params.id + '')
    secondIndustryData.map((ele: any) => {
      ele.name = ele.industry2_name
      ele.value = ele.weight
    })
    secondIndustry.value = secondIndustryData
    handleTabChange(activeTab.value)
    const { data: fundData } = await indexFundList({ indexId: route.params.id + '' })
    fundData.map((ele: any) =>{
      ele.netAssets = ele.netAssets ? Math.round(ele.netAssets / 100000000) / 100 : ''
      ele.sharesOutstanding = ele.sharesOutstanding ? Math.round(ele.sharesOutstanding / 100000000) / 100 : ''
      ele.day = `${ele.lastQuarterDate ? ele.lastQuarterDate.slice(5,10) : ''}<br/>${ele.quarterDate ? ele.quarterDate.slice(5,10) : ''}`
    })
    fundList.value = fundData
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

const setLineChart = (data: any, index: number) => {
  const sysDate = [] as string[]
  let seriesList = [] as any[]
  let color = []
  const legend = {
    data: [] as string[],
    top: '0px',
    show: false
  }
  let yAxis = [] as any[]
  if (index === 0) {
    color = ['blue']
    legend.data = ['指数']
    seriesList = [getLineSeries({ name: '指数' })]
    yAxis = [getYAxis({ })]
    data.forEach((ele: any) => {
      sysDate.push(ele.sysDate)
      seriesList[0].data.push({ value: ele.navPerShare })
    })
  } else{
    color = ['blue', 'red']
    legend.show = true
    legend.data = ['净资产', '股本']
    seriesList = [getLineSeries({ name: '净资产' }), getLineSeries({ name: '股本', yAxisIndex: 1 })]
    yAxis = [getYAxis({ axisLabel: function (data: any) { return formatNumberByUnit(data) }}), getYAxis({ axisLabel: function (data: any) { return formatNumberByUnit(data) }, position: 'right' })]
    data.forEach((ele: any) => {
      sysDate.push(ele.sysDate)
      seriesList[0].data.push({ value: ele.totalNetAssets })
      seriesList[1].data.push({ value: ele.sharesOutstanding })
    })
  }
  
  if (!destroyedFlag.value) {
    let chart = echarts.init(document.getElementById(`${chartList.value[index].id}`))
    const option = getBaseOption({
      series: seriesList,
      yAxis: yAxis,
      xAxis: [getXAxis({ data: sysDate })],
      tooltipFormatter: function (params: any) {
        const data = Array.isArray(params) ? params : [params]
        let backText = `日期：${data[0].name}<br/>`
        data.forEach((ele) => {
          backText += `<span style="color: ${ele.color}">${ele.seriesName}</span>:<span class="font-bold">${formatNumberByUnit(ele.value)}</span><br/>`
        })
        return backText
      },
      grid: [{ top: '20px', left: '50px', right: '50px', bottom: '20px' }],
      legend: legend,
      color: color
    })
    chart.setOption(option)
    charts.value[index] = chart
    chartList.value[index].loading = false
  }
}

const showFileListPopup = ref(false)
const handleViewDetails = () => {
  showFileListPopup.value = true
}

const activeTab = ref(0)
watch(activeTab, (newValue) => {
  handleTabChange(newValue)
})

const handleTabChange = (tabIndex: number) => {
  if (charts.value[2]) {
    charts.value[2].dispose()
    charts.value[2] = null
  }
  if (charts.value[3]) {
    charts.value[3].dispose()
    charts.value[3] = null
  }
  switch (tabIndex) {
    case 0:
      nextTick(() =>{
        setTreemapChart(firstIndustry.value, 2)
        setTreemapChart(secondIndustry.value, 3)
      })
      break
    case 1:
      break
    case 2:
      break
    default:
      break
  }
}

const setTreemapChart = (list: any, index: number) => {
  if (!destroyedFlag.value) {
    let chart = echarts.init(document.getElementById(`${chartList.value[index].id}`))
    const option = getBaseOption({
      series: [{
        type: 'treemap',
        visibleMin: 300,
        nodeClick: 'false',
        label: {
          show: true,
          formatter: function (data: any) {
            return `${data.data.name}(${data.data.value}%)`
          }
        },
        scaleLimit: {
          min: 1,
          max: 1
        },
        itemStyle: {
          borderColor: '#fff'
        },
        levels: [{
          itemStyle: {
            borderWidth: 0,
            gapWidth: 3
          }
        }],
        breadcrumb: { show: false },
        data: list,
        left: 0,
        right: 0,
        top: 0,
        bottom: 0
      }]
    })
    chart.setOption(option)
    charts.value[index] = chart
    chartList.value[index].loading = false
  }
}

import { chartMixins } from '@/mixins/chart-mixins'
const { charts, destroyedFlag, disposeAll } = chartMixins()
let chartList = ref([{
  id: 'index_hist_chart',
  loading: true,
  name: '指数走势'
}, {
  id: 'funds_his_chart',
  loading: true,
  name: '追踪汇总'
}, {
  id: 'first_industry_chart',
  loading: true,
  name: '一级行业'
}, {
  id: 'second_industry_chart',
  loading: true,
  name: '二级行业'
}])

onMounted (() =>{
  charts.value = [null, null, null, null]
  init()
  loadFlag.value = true
})
</script>

<style lang='scss' scoped>
.page-div {
  overflow-y: auto;
  padding-top: 105px;

  .header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;

    @media screen and (min-width: 992px) {
      left: calc(50vw - 496px);
      right: calc(50vw - 496px);
    }
  }

  .chart-container {
    height: calc(50vh - 206px);

    @media screen and (min-width: 768px) {
      height: calc(50vh - 226px);
    }
  }

  .firstTd {
    min-width: 80px;
    max-width: 120px;
    width: auto; 

    @media screen and (min-width: 768px) {
      min-width: 150px;
      max-width: 400px;
    }
  }
}
  
.file-list {
  max-height: calc(100% - 60px);
  overflow-y: auto;
  padding-bottom: 20px;

  .file-item {
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;
  }

  .file-link {
    display: flex;
    align-items: center;
    color: #333;
    text-decoration: none;

    i {
      font-size: 20px;
      margin-right: 10px;
    }

    .file-title {
      flex: 1;
      font-size: 14px;
    }
  }

  @media screen and (min-width: 768px) {
    padding: 0 16px 20px;

    .file-item {
      padding: 16px 0;
    }

    .file-link {
      i {
        font-size: 24px;
        margin-right: 16px;
      }

      .file-title {
        font-size: 16px;
      }
    }
  }
}
</style>
