<template>
  <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
    <cwg-header :title="t('Custom.Settings.Title')">
      <template #right>
        <view class="time-header">
          <text>{{ t('Documentary.console.item2') }}:</text>
          <text class="time-value" @click="toReload">{{ time }}</text>
          <cwg-icon name="crm-refresh" @click="toReload" style="margin-left: 6px; cursor: pointer;" />
        </view>
      </template>
    </cwg-header>

    <view class="info-card">
      <cwg-asset-tabs :tabs="tabs" v-model="activeTab" />

      <!-- Tab 1: 个人指标 -->
      <view v-if="activeTab === '1'" class="tab-content">
        <!-- 个人名片和品种摘要 -->
        <view class="section-row">
          <view class="section-col">
            <view class="fllow-title">
              <view class="title">
                <text>{{ t('TradingCenter.item12') }}</text>
              </view>
            </view>
            <view class="fllow-info-list">
              <cwg-label-line-value :label="t('TradingCenter.item13')" :value="DailyIndex1.nickname || '--'" />
              <cwg-label-line-value :label="t('TradingCenter.item14')" :value="DailyIndex1.personalSignature || '--'" />
              <cwg-label-line-value :label="t('TradingCenter.item11')"
                                    :value="getAccountTypeText(DailyIndex.groupType)" />
              <cwg-label-line-value :label="t('TradingCenter.item15')" :value="DailyIndex1.addTime || '--'" />
            </view>
          </view>
          <view class="section-col">
            <view class="fllow-title">
              <view class="title">
                <text>{{ t('TradingCenter.item16') }}</text>
              </view>
            </view>
            <view class="chart-container">
              <cwg-match-media :max-width="991">
                <cwg-charts type="pie" :chartData="symbolSummaryData" :opts="pieOpts" ontouch />
              </cwg-match-media>
              <cwg-match-media :min-width="991">
                <cwg-charts type="pie" :chartData="symbolSummaryData" :opts="pieOpts" />
              </cwg-match-media>
            </view>
          </view>
        </view>

        <!-- 数据指标部分 -->
        <view class="section-row">
          <!-- 历史表现 -->
          <view class="section-col">
            <view class="fllow-title">
              <view class="title">
                <text>{{ t('TradingCenter.item17') }}</text>
              </view>
            </view>
            <view class="fllow-info-grid">
              <cwg-label-line-value :label="t('TradingCenter.item18')"
                                    :value="formatCurrency(DailyIndex.pl, DailyIndex.currency, DailyIndex.groupType)" />
              <cwg-label-line-value :label="t('TradingCenter.item21')"
                                    :value="formatCurrency(DailyIndex.loss, DailyIndex.currency, DailyIndex.groupType)" />
              <cwg-label-line-value :label="t('TradingCenter.item19')" :value="DailyIndex.plRate || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item7')" :value="DailyIndex.maxDdRate || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item20')"
                                    :value="formatCurrency(DailyIndex.profit, DailyIndex.currency, DailyIndex.groupType)" />
            </view>
          </view>
          <!-- 交易规模与效率 -->
          <view class="section-col">
            <view class="fllow-title">
              <view class="title">
                <text>{{ t('TradingCenter.item22') }}</text>
              </view>
            </view>
            <view class="fllow-info-grid">
              <cwg-label-line-value :label="t('TradingCenter.item23')" :value="DailyIndex.trades || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item29')" :value="DailyIndex.avgHoldVolume || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item24')" :value="DailyIndex.volume || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item39')" :value="DailyIndex.maxHoldVolume || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item25')" :value="DailyIndex.tradesWin || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item30')" :value="DailyIndex.avgDailyTrades || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item26')" :value="DailyIndex.tradesLoss || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item31')" :value="DailyIndex.tradesSl || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item27')" :value="DailyIndex.avgHoldVolume || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item32')" :value="DailyIndex.slRate || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item28')" :value="DailyIndex.avgHoldTime || '--'" />
              <cwg-label-line-value :label="t('TradingCenter.item6')" :value="DailyIndex.winRate || '0'" />
            </view>
          </view>
        </view>

        <view class="section-row">
          <!-- 资金流向 -->
          <view class="section-col">
            <view class="fllow-title">
              <view class="title">
                <text>{{ t('TradingCenter.item33') }}</text>
              </view>
            </view>
            <view class="fllow-info-grid">
              <cwg-label-line-value :label="t('TradingCenter.item34')"
                                    :value="formatCurrency(DailyIndex.deposit, DailyIndex.currency, DailyIndex.groupType)" />
              <cwg-label-line-value :label="t('TradingCenter.item36')"
                                    :value="formatCurrency(DailyIndex.credit, DailyIndex.currency, DailyIndex.groupType)" />
              <cwg-label-line-value :label="t('TradingCenter.item35')"
                                    :value="formatCurrency(DailyIndex.withdraw, DailyIndex.currency, DailyIndex.groupType)" />
            </view>
          </view>
          <!-- 订阅与跟单 -->
          <view class="section-col">
            <view class="fllow-title">
              <view class="title">
                <text>{{ t('TradingCenter.item40') }}</text>
              </view>
            </view>
            <view class="fllow-info-grid">
              <cwg-label-line-value :label="t('TradingCenter.item37')" :value="DailyIndex.follows || '0'" />
              <cwg-label-line-value :label="t('TradingCenter.item38')"
                                    :value="formatCurrency(DailyIndex.followsPl, DailyIndex.currency, DailyIndex.groupType)" />
            </view>
          </view>
        </view>

        <!-- 排名曲线和净值曲线 -->
        <view class="section-row">
          <!-- 排名曲线 -->
          <view class="section-col">
            <view class="fllow-title">
              <view class="title">
                <text>{{ t('TradingCenter.item41') }}</text>
              </view>
            </view>
            <view class="chart-container">
              <cwg-match-media :max-width="991">
                <cwg-charts type="line" :chartData="rankingChartData" :opts="rankingChartOpts" ontouch />
              </cwg-match-media>
              <cwg-match-media :min-width="991">
                <cwg-charts type="line" :chartData="rankingChartData" :opts="rankingChartOpts" />
              </cwg-match-media>
            </view>
          </view>
          <!-- 净值曲线 -->
          <view class="section-col">
            <view class="fllow-title">
              <view class="title">
                <text>{{ t('Documentary.tradingCenter.item140') }}</text>
              </view>
            </view>
            <view class="chart-container">
              <cwg-match-media :max-width="991">
                <cwg-charts type="line" :chartData="equityChartData" :opts="equityChartOpts" ontouch />
              </cwg-match-media>
              <cwg-match-media :min-width="991">
                <cwg-charts type="line" :chartData="equityChartData" :opts="equityChartOpts" />
              </cwg-match-media>
            </view>
          </view>
        </view>
      </view>

      <!-- Tab 2: 交易订单 -->
      <view v-if="activeTab === '2'" class="tab-content">
        <cwg-complex-search :fields="tab2FilterFields" v-model="tab2SearchParams" @search="handleTab2Search"
                            @reset="handleTab2Reset" />
        <cwg-tabel ref="table2Ref" :columns="tab2Columns" :immediate="true" :queryParams="tab2QueryParams"
                   :api="tab2Api" :show-operation="false" :showSummary="true" :summaryMethod="getSummaries1">
          <template #openClosePrice="{ row }">
            <view class="sp-div-tab">{{ formatNumber(row.openPrice) }}</view>
            <view class="sp-div-tab-b">{{ formatNumber(row.closePrice) }}</view>
          </template>
          <template #openCloseTime="{ row }">
            <view class="sp-div-tab">{{ row.openTime || '--' }}</view>
            <view class="sp-div-tab-b">{{ row.closeTime || '--' }}</view>
          </template>
          <template #tpSl="{ row }">
            <view class="sp-div-tab">{{ formatNumber(row.tp) }}</view>
            <view class="sp-div-tab-b">{{ formatNumber(row.sl) }}</view>
          </template>
        </cwg-tabel>
      </view>

      <!-- Tab 3: 订阅总览 -->
      <view v-if="activeTab === '3'" class="tab-content">
        <view class="summary-top">
          <view class="search-operation-l">
            <text>{{ t('Documentary.tradingCenter.item123') }}</text>
            : {{ tableSumData.profit || '0' }}
          </view>
          <view class="search-operation-r">
            <text>{{ t('Documentary.tradingCenter.item124') }}</text>
            : {{ tableSumData.volume || '0' }}
          </view>
        </view>
        <cwg-complex-search :fields="tab3FilterFields" v-model="tab3SearchParams" @search="handleTab3Search"
                            @reset="handleTab3Reset" />
        <cwg-tabel ref="table3Ref" :columns="tab3Columns" :immediate="true" :queryParams="tab3QueryParams"
                   :api="tab3Api" :show-operation="false" />
      </view>

    </view>
  </cwg-page-wrapper>
</template>

<script setup lang="ts">
  import { computed, ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { documentaryApi } from '@/service/documentary'
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import { useWindowWidth } from '@/composables/useWindowWidth'
  const windowWidth = useWindowWidth(300)
  const isMobile = computed(() => windowWidth.value <= 991)
  const { t } = useI18n()

  // --- Params ---
  const myLogin = ref('')
  const myRanking = ref('')
  const myId = ref('')

  onLoad((options: any) => {
    myLogin.value = options.dealLogin || options.login || ''
    myRanking.value = options.ranking || ''
    myId.value = options.id || ''

    activeTab.value = '1'
    getDate()
    getPersonalIndicators()
  })

  // --- Time fetching ---
  const time = ref('')

  const getLocalTime = () => {
    let timezone = 2
    let offset_GMT = new Date().getTimezoneOffset()
    let nowDate = new Date().getTime()
    let now = new Date(nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000)
    let year = now.getFullYear()
    let month = String(now.getMonth() + 1).padStart(2, '0')
    let day = String(now.getDate()).padStart(2, '0')
    let hh = String(now.getHours()).padStart(2, '0')
    let mm = String(now.getMinutes()).padStart(2, '0')
    time.value = `${year}/${month}/${day}  ${hh}:${mm}`
  }

  const getDate = async () => {
    try {
      let res = await documentaryApi.followDealSignalRefreshDate()
      if (res.code === 200 && res.data) {
        time.value = res.data
      } else {
        getLocalTime()
      }
    } catch (error) {
      getLocalTime()
    }
  }

  const toReload = () => {
    getDate()
    if (activeTab.value === '1') {
      getPersonalIndicators()
    } else if (activeTab.value === '2') {
      table2Ref.value?.refreshTable()
    } else if (activeTab.value === '3') {
      table3Ref.value?.refreshTable()
    }
  }

  onMounted(() => {
  })

  onUnmounted(() => {
  })

  // --- Tabs ---
  const activeTab = ref('1')
  const tabs = computed(() => [
    { text: t('Documentary.tradingCenter.item60'), value: '1' },
    { text: t('Documentary.tradingCenter.item58'), value: '2' },
    { text: t('Documentary.tradingCenter.item59'), value: '3' },
  ])

  // --- Tab 1 Data ---
  const DailyIndex = ref<any>({})
  const DailyIndex1 = ref<any>({})

  const symbolSummaryData = ref<any>({ series: [] })

  const pieOpts = computed(() => ({
    color: ['#5470C6', '#91CC75', '#EE6666', '#FAC858', '#73C0DE', '#3BA272'],
    padding: [5, 5, 5, 5],
    enableScroll: true,
    legend: {
      show: true,
      position: isMobile.value ? 'top' : 'left',
      float: isMobile.value ? 'left' : 'center'
    },
    extra: {
      pie: {
        radius: isMobile.value ? 75 : 95
      }
    }
  }))

  const rankingChartData = ref<any>({ categories: [], series: [] })
  const rankingChartOpts = computed(()=>({
    enableScroll: true,
    yAxis: {
      data: [{
        axisLine: false,
        inverse: false,
      }],
    },
    xAxis: {
      // disableGrid: true,
      scrollShow: true,
      itemCount: isMobile.value?3:4,
    },
  }))


  const equityChartData = ref<any>({ categories: [], series: [] })
  const equityChartOpts = computed(()=>({
    enableScroll: true,
    xAxis: {
      // disableGrid: true,
      scrollShow: true,
      itemCount: isMobile.value?3:4,
    },
  }))
  const getAccountTypeText = (type: number) => {
    const map: Record<number, string> = {
      1: 'AccountType.ClassicAccount',
      2: 'AccountType.SeniorAccount',
      5: 'AccountType.SpeedAccount',
      6: 'AccountType.SpeedAccount',
      7: 'AccountType.StandardAccount',
      8: 'AccountType.CentAccount',
    }
    return type && map[type] ? t(map[type]) : '--'
  }

  const formatCurrency = (val: any, currency?: string, groupType?: number) => {
    if (!val) return '0'
    let symbol = '$'
    if (currency === 'GBP') symbol = '£'
    else if (currency === 'EUR') symbol = '€'
    else if (currency === 'USC' || groupType == 8) symbol = '¢'
    return `${symbol}${val}`
  }

  const getPersonalIndicators = async () => {
    if (myId.value) {
      let res = await documentaryApi.followDealSignalSearchSingle({ id: myId.value })
      if (res.code === 200 && res.data) {
        DailyIndex.value = res.data
        DailyIndex1.value = res.data
        if (res.data.login) {
          myLogin.value = res.data.login
        }
        if (res.data.symbolSummary) {
          drawSymbolSummary(res.data.symbolSummary)
        }
        getChart4()
        getChart5()
      }
    } else {
      // Fallback
      documentaryApi.followDailyIndex({ login: myLogin.value }).then(res => {
        if (res.code === 200) DailyIndex.value = res.data || {}
      })
      documentaryApi.followDealCard({ login: myLogin.value }).then(res => {
        if (res.code === 200) DailyIndex1.value = res.data || {}
      })
      documentaryApi.followDailyChartSymbol({ login: myLogin.value }).then(res => {
        if (res.code === 200 && res.data && res.data[0] && res.data[0].volumes) {
          drawSymbolSummary(res.data[0].volumes)
        }
      })
      getChart4()
      getChart5()
    }
  }

  const drawSymbolSummary = (data: any[]) => {
    let pieData = data.map(item => {
      let name = item.symbol || item.name || ''
      if (!name && item.symbolType) {
        const types = ['', t('Documentary.Report.item11'), t('Documentary.Report.item12'), t('Documentary.Report.item13'), t('Documentary.Report.item14'), t('Documentary.Report.item15'), t('Documentary.Report.item16')]
        name = types[item.symbolType] || ''
      }
      let value = item.volume !== undefined ? item.volume : (item.value !== undefined ? item.value : (item.amount || 0))
      return { name, value }
    })
    symbolSummaryData.value = {
      series: [{ data: pieData }],
    }
  }

  const getChart4 = async () => {
    let res = await documentaryApi.getEquityChart({ login: myLogin.value })
    if (res.code === 200 && res.data) {
      let categories = []
      let seriesData = []
      res.data.forEach((item: any) => {
        categories.push(item.date.split(' ')[0])
        seriesData.push(item.amount !== null ? item.amount : item.doubleAmount)
      })
      equityChartData.value = {
        categories,
        series: [{ name: t('Documentary.tradingCenter.item140'), data: seriesData }],
      }
    }
  }

  const getChart5 = async () => {
    let res = await documentaryApi.getRankingChart({ login: myLogin.value })
    if (res.code === 200 && res.data) {
      let categories = []
      let seriesData = []
      res.data.forEach((item: any) => {
        categories.push(item.date.split(' ')[0])
        seriesData.push(item.amount !== null ? item.amount : item.doubleAmount)
      })
      rankingChartData.value = {
        categories,
        series: [{ name: t('TradingCenter.item41'), data: seriesData }],
      }
    }
  }

  // --- Formatters ---
  const formatNumber = (value: any) => {
    if (value == '***') return '***'
    if (isNaN(value)) return '0'
    let valStr = String(value)
    const parts = valStr.split('.')
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    return parts.join('.')
  }

  // --- Tab 2 ---
  const table2Ref = ref(null)
  const combined = ref<any>({})
  const tab2SearchParams = ref({
    tab4Type: 1,
    date: [],
  })
  const tab2FilterFields = computed(() => [
    {
      key: 'tab4Type', type: 'select', label: t('Documentary.tradingCenter.item114'), options: [
        { value: 1, text: t('Documentary.tradingCenter.item114') },
        // { value: 2, text: t('Documentary.tradingCenter.item115') }
      ],
    },
    { key: 'date', type: 'daterange', label: t('placeholder.choose') },
  ])
  const tab2QueryParams = computed(() => {
    return { ...tab2SearchParams.value, login: myLogin.value }
  })
  const tab2Columns = computed(() => [
    { prop: 'order', label: t('Label.OrderNumber'), align: 'center' },
    { prop: 'platform', label: t('Label.Platform'), align: 'center' },
    { prop: 'cmd', label: t('Label.Type'), align: 'center' },
    { prop: 'symbol', label: t('Label.Varieties'), align: 'center' },
    {
      prop: 'openClosePrice',
      label: t('Label.OpenPrice') + '/' + t('Label.ClosePrice'),
      align: 'center',
      slot: 'openClosePrice',
    },
    {
      prop: 'openCloseTime',
      label: t('Label.OpenTime') + '/' + t('Label.CloseTime'),
      align: 'center',
      slot: 'openCloseTime',
    },
    { prop: 'tpSl', label: t('Label.EP') + '/' + t('Label.EL'), align: 'center', slot: 'tpSl' },
    {
      prop: 'volume',
      label: t('Documentary.tradingCenter.item99'),
      align: 'center',
      formatter: ({ row }: any) => formatNumber(row.volume || '0'),
    },
    {
      prop: 'storage',
      label: t('Label.StorageFee'),
      align: 'center',
      formatter: ({ row }: any) => formatNumber(row.storage || '0'),
    },
    {
      prop: 'profit',
      label: t('Label.ProfitLoss'),
      align: 'center',
      formatter: ({ row }: any) => formatNumber(row.profit || '0'),
    },
    {
      prop: 'totalProfit',
      label: t('Label.TotalProfitLoss'),
      align: 'center',
      formatter: ({ row }: any) => formatNumber(row.totalProfit || '0'),
    },
  ])

  const tab2Api = async (params: any) => {
    let res = await documentaryApi.followOrderRecordList(params)
    if (res.code === 200 || res.code === 0 || res.code === 10000) {
      combined.value = res.sum || {}
    }
    return res
  }

  const getSummaries1 = ({ columns }: any) => {
    let sums = Array(columns.length).fill('')
    if (Object.keys(combined.value).length > 0) {
      sums[0] = t('Label.Total')
      const volIdx = columns.findIndex((c: any) => c.prop === 'volume')
      const proIdx = columns.findIndex((c: any) => c.prop === 'profit')
      const totIdx = columns.findIndex((c: any) => c.prop === 'totalProfit')
      if (volIdx > -1) sums[volIdx] = combined.value.volume ? formatNumber(combined.value.volume) : 0
      if (proIdx > -1) sums[proIdx] = combined.value.profit ? formatNumber(combined.value.profit) : 0
      if (totIdx > -1) sums[totIdx] = combined.value.totalProfit ? formatNumber(combined.value.totalProfit) : 0
    }
    return sums
  }

  const handleTab2Search = (params: any) => {
    tab2SearchParams.value = params
    nextTick(() => {
      table2Ref.value?.refreshTable()
    })
  }
  const handleTab2Reset = (params: any) => {
    tab2SearchParams.value = params
    nextTick(() => {
      table2Ref.value?.refreshTable()
    })
  }

  // --- Tab 3 ---
  const table3Ref = ref(null)
  const tableSumData = ref<any>({})
  const tab3SearchParams = ref({
    platform: 'MT4',
    date: [],
  })
  const tab3FilterFields = computed(() => [
    {
      key: 'platform', type: 'select', label: t('Label.Platform'), options: [
        { value: 'MT4', text: 'MT4' },
        { value: 'MT5', text: 'MT5' },
      ],
    },
    { key: 'date', type: 'daterange', label: t('placeholder.choose') },
  ])
  const tab3QueryParams = computed(() => {
    return { ...tab3SearchParams.value, login: myLogin.value }
  })
  const tab3Columns = computed(() => [
    { prop: 'followLogin', label: t('Documentary.tradingCenter.item102'), align: 'center' },
    { prop: 'platform', label: t('Label.Platform'), align: 'center' },
    { prop: 'startTime', label: t('Documentary.tradingCenter.item103'), align: 'center' },
    { prop: 'endTime', label: t('Documentary.tradingCenter.item104'), align: 'center' },
    {
      prop: 'profit',
      label: t('Documentary.tradingCenter.item105'),
      align: 'center',
      formatter: ({ row }: any) => formatNumber(row.profit || '0'),
    },
    {
      prop: 'volume',
      label: t('Documentary.tradingCenter.item99'),
      align: 'center',
      formatter: ({ row }: any) => formatNumber(row.volume || '0'),
    },
  ])

  const tab3Api = async (params: any) => {
    let res = await documentaryApi.followDealSubscribeSummary(params)
    if (res.code === 200 || res.code === 0 || res.code === 10000) {
      tableSumData.value = res.sum || {}
    }
    return res
  }

  const handleTab3Search = (params: any) => {
    tab3SearchParams.value = params
    nextTick(() => {
      table3Ref.value?.refreshTable()
    })
  }
  const handleTab3Reset = (params: any) => {
    tab3SearchParams.value = params
    nextTick(() => {
      table3Ref.value?.refreshTable()
    })
  }

</script>

<style scoped lang="scss">
  @import "@/uni.scss";

  .time-header {
    display: flex;
    align-items: center;
    font-size: 14px;
    font-weight: 500;
    color: var(--bs-heading-color);

    .time-value {
      margin-left: 6px;
      color: var(--bs-heading-color);
    }
  }

  .info-card {
    padding: 16px;
    background: var(--bs-body-bg);
    border-radius: 8px;
  }

  .tab-content {
    margin-top: 16px;
  }

  .section-row {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-bottom: 20px;
  }

  .section-col {
    flex: 1;
    min-width: 300px;
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    padding: 16px;
    box-sizing: border-box;
  }

  .fllow-title {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
    margin-bottom: 10px;

    .title {
      font-weight: bold;
      color: var(--bs-heading-color);
      padding-left: 8px;
      border-left: 4px solid #eb3f57;
      font-size: 16px;
    }
  }

  .fllow-info-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .fllow-info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px 20px;
    @media screen and (max-width: 750px) {
      grid-template-columns: none;
    }
  }

  .chart-container {
    width: 100%;
    height: 250px;
  }

  .sp-div-tab {
    border-bottom: 1px dashed #eee;
    padding-bottom: 4px;
    margin-bottom: 4px;
  }

  .sp-div-tab-b {
    padding-top: 4px;
  }

  .summary-top {
    display: flex;
    gap: 20px;
    margin-bottom: 16px;
    font-size: 14px;
    font-weight: bold;
    color: var(--bs-heading-color);
  }
</style>
