<template>
  <div class="page-div">
    <back-button />
    <div class="header">
      <div class="header-content">
        <h1 class="title">{{ groupData?.stockGroupName }}</h1>
      </div>
    </div>
    <div class="info-card financial-data">
      <div class="data-item">
        <div class="data-label">总资产</div>
        <div class="data-value">{{ groupData?.totalAmount }}</div>
      </div>
      <div class="data-item">
        <div class="data-label">总盈亏</div>
        <div class="data-value">
          <span :class="groupData?.totalIncome >= 0 ? 'red-color' : 'green-color'">{{ groupData?.totalIncome }}</span>
          <span :class="groupData?.totalIncomeRate >= 0 ? 'red-color' : 'green-color'">({{ groupData?.totalIncomeRate }}%)</span>
        </div>
      </div>
      <div class="data-item">
        <div class="data-label">当日盈亏</div>
        <div class="data-value">
          <span :class="groupData?.todayIncome >= 0 ? 'red-color' : 'green-color'">{{ groupData?.todayIncome }}</span>
          <span :class="groupData?.todayIncomeRate >= 0 ? 'red-color' : 'green-color'">({{ groupData?.todayIncomeRate }}%)</span>
        </div>
      </div>
      <div class="data-item">
        <div class="data-label">总市值</div>
        <div class="data-value">{{ groupData?.hkTotalMarket }}</div>
      </div>
      <div class="data-item">
        <div class="data-label">可用</div>
        <div class="data-value">{{ groupData?.totalCash }}</div>
      </div>
    </div>
    <div class="info-card" v-if="chartList.length > 0">
      <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">
      <div class="tableDiv">
        <table border="1">
          <thead>
            <tr>
              <th class="td--column--1">股票/市值</th>
              <th>盈亏</th>
              <th>持仓</th>
              <th>成本/现价</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(hold, index) in holdList" :key="index" @click="showTradingRecord(hold)">
              <td class="td--column--1">
                <div>{{ hold.stockName }}</div>
                <div>{{ hold.hkStockMarket }}</div>
              </td>
              <td>
                <div>{{ hold.income }}</div>
                <div>{{ hold.incomeRate }}%</div>
              </td>
              <td>
                {{ hold.shares }}<br/>
              </td>
              <td>
                <div>{{ hold.costPrice }}</div>
                <div>{{ hold.hkStockPrice }}</div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <van-popup v-model:show="showTradingRecordPopup" 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">{{ stockCode }}【{{ stockName }}】交易记录</div>
          <van-icon name="close" @click="showTradingRecordPopup = false" />
        </div>
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad"
            :immediate-check="false">
            <van-cell v-for="(item, index) in tradeList" :key="index" :class="['trade-item', `trade-type-${item.tradeType}`]">
              <div class="trade-header d-flex justify-content-between items-center f-b">
                <div class="trade-date">{{ item.tradeDate }}</div>
                <div class="trade-type-label f-b">{{ item.tradeType === 'dividend' ? '分红' : item.tradeType === 'cash' ? '派息' : item.tradeType === 'buy' ? '买入' : '卖出' }}</div>
              </div>
              <div class="trade-content">
                <div v-if="item.tradeType === 'dividend'" class="dividend-content">
                  <div class="trade-amount">送股数量: {{ item.sharesChange }}</div>
                </div>
                <div v-else-if="item.tradeType === 'cash'" class="cash-content">
                  <div class="trade-amount">每股派息: {{ item.dps }}{{ item.dividendUnit }}</div>
                </div>
                <div v-else-if="item.tradeType === 'buy' || item.tradeType === 'sell'" class="trade-content-main">
                  <div class="trade-stock-info">
                    <span class="stock-price">价格: {{ item.stockPrice }}</span>
                  </div>
                  <div class="trade-shares">数量: {{ item.sharesChange }}股</div>
                  <div class="trade-market">金额: {{ item.tradeMarket }}</div>
                </div>
              </div>
            </van-cell>
          </van-list>
        </van-pull-refresh>
      </div>
    </van-popup>
  </div>
</template>
<script setup lang='ts'>
import BackButton from '@/components/back-button.vue'

import { ref, onMounted } from 'vue'

import { useRoute } from 'vue-router'
const route = useRoute()
import { groupInfo, groupHisChartIncomeRate, groupHoldList, groupTradeList } from '@/utils/api'
const groupData: any = ref(null)
import { formatNumber } from '@/utils'

import * as echarts from 'echarts'
import { getLineSeries, getBaseOption, getXAxis, getYAxis } from '@/utils/chart'
const init = async () => {
  try {
    const {data } = await groupInfo(route.params.id + '')
    groupData.value = {
      stockGroupName: data.stockGroup && data.stockGroup.stockGroupName ? data.stockGroup.stockGroupName : '',
      totalAmount: data.holdInfo && data.holdInfo.totalAmount ? formatNumber(data.holdInfo.totalAmount) : '',
      totalIncome: data.holdInfo && data.holdInfo.totalIncome ? formatNumber(data.holdInfo.totalIncome) : '',
      totalIncomeRate: data.holdInfo && data.holdInfo.totalIncomeRate ? data.holdInfo.totalIncomeRate : '',
      todayIncome: data.holdInfo && data.holdInfo.todayIncome ? formatNumber(data.holdInfo.todayIncome) : '',
      todayIncomeRate: data.holdInfo && data.holdInfo.todayIncomeRate ? data.holdInfo.todayIncomeRate : '',
      hkTotalMarket: data.holdInfo && data.holdInfo.hkTotalMarket ? formatNumber(data.holdInfo.hkTotalMarket) : '',
      totalCash: data.holdInfo && data.holdInfo.totalCash ? formatNumber(data.holdInfo.totalCash) : ''
    }
    getChartData()
    getTableData()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

const getChartData = async () => {
  const { data } = await groupHisChartIncomeRate({ groupId: route.params.id + '' })
  const sysDate: any = []
  const seriesData: any = []
  data.forEach((ele: any) => {
    sysDate.push(ele.sysDate)
    seriesData.push({ value: ele.nav })
  })
  const option = getBaseOption({
    yAxis: [getYAxis({ })],
    xAxis: [getXAxis({ data: sysDate })],
    series: [getLineSeries({ data: seriesData, name: '累计收益率' })],
    grid: [{ top: '20px', bottom: '20px', left: '40px', right: '40px' }]
  })
  if (!destroyedFlag.value && document.getElementById(chartList.value[0].id)) {
    let chart = echarts.init(document.getElementById(`${chartList.value[0].id}`))
    chart.setOption(option)
    charts.value[0] = chart
    chartList.value[0].loading = false
  }
}

const holdList = ref<any[]>([])
const getTableData = async () => {
  const { data } = await groupHoldList({ curPage: 1, limit: 999, groupId: route.params.id + '' })
  let hkStockMarket = 0
  let shares = 0
  let incomeAll = 0
  let holdCostALL = 0
  data.list.map((ele: any) => {
    ele.stockPrice = formatNumber(ele.stockPrice)
    if (ele.stockCode !== 'CASH-HKD') {
      const income = Math.round((ele.hkStockMarket - ele.holdCost) * 100) / 100
      incomeAll += income
      holdCostALL += ele.holdCost
      ele.incomeRate = ele.holdCost ? Math.round(income / ele.holdCost * 10000) / 100 : 0
      ele.income = formatNumber(income)
      hkStockMarket += ele.hkStockMarket
      shares += ele.shares
    }
    ele.hkStockMarket = formatNumber(ele.hkStockMarket)
    ele.shares = formatNumber(ele.shares)
  })
  incomeAll = Math.round(incomeAll * 100) / 100
  data.list.push({
    stockName: '总计',
    hkStockMarket: formatNumber(Math.round(hkStockMarket * 100) / 100),
    shares: formatNumber(Math.round(shares * 100) / 100),
    income: formatNumber(incomeAll),
    incomeRate: holdCostALL ? Math.round(incomeAll / holdCostALL * 10000) / 100 : 0
  })
  holdList.value = data.list
}


const showTradingRecordPopup = ref(false)
const stockCode = ref('')
const stockName = ref('')
const showTradingRecord = (item: any) => {
  showTradingRecordPopup.value = true
  stockCode.value = item.stockCode
  stockName.value = item.stockName
  onRefresh()
}

const curPage = ref(1)
const tradeList = ref<any[]>([])
const onRefresh = () => {
  curPage.value = 1
  tradeList.value = []
  onLoad()
}

const loading = ref(false)
const totalCount = ref(0)
const refreshing = ref(false)
const finished = ref(false)
const onLoad = async () => {
  loading.value = true
  try {
    const { data } = await groupTradeList({ groupId: route.params.id + '', stockCode: stockCode.value, curPage: curPage.value, limit: 20 })
    totalCount.value = data.totalCount
    if (refreshing.value) {
      tradeList.value = data.list
      refreshing.value = false
    } else {
      tradeList.value = tradeList.value.concat(data.list)
    }
    if (tradeList.value.length >= data.totalCount) {
      finished.value = true
    } else {
      curPage.value++
    }
  } catch (error) {
    console.log(error)
  }
}

import { chartMixins } from '@/mixins/chart-mixins'
const { charts, destroyedFlag } = chartMixins()

let chartList = ref([{ id: 'group_chart', loading: true }])
onMounted (() =>{
  charts.value = [null]
  init()
})
</script>

<style lang='scss' scoped>
.page-div {
  padding-top: 86px;
  height: auto;

  .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: 26vh;

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

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

      @media screen and (min-width: 768px) {
        min-width: 150px;
        max-width: 400px;
      }
    }
  }
}

.trade-item {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.trade-header {
  margin-bottom: 8px;

  .trade-date {
    color: #333;
    font-size: 14px;
  }

  .trade-type-label {
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: bold;
  }
}

.trade-type-buy .trade-type-label {
  background-color: #e1f3d8;
  color: #52c41a;
}

.trade-type-sell .trade-type-label {
  background-color: #fff1f0;
  color: #f5222d;
}

.trade-type-dividend .trade-type-label,
.trade-type-cash .trade-type-label {
  background-color: #e6f7ff;
  color: #1890ff;
}

.trade-content {
  display: flex;
  flex-direction: column;
  gap: 4px;

  .trade-stock-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .trade-shares,
  .trade-market,
  .trade-amount {
    font-size: 14px;
    color: #666;
  }

  .trade-price {
    font-size: 14px;
    color: #333;
  }
}
</style>
