<template>
  <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
    <cwg-header :title="titleList[detailType]" />
    <uni-loading v-if="loading" />
    <view v-else class="account-content">
      <view class="search-content">
        <view class="search-bar">
          <cwg-complex-search :fields="filterFields" v-model="searchParams" @search="handleSearch"
                              @reset="handleReset" />
        </view>
      </view>

      <cwg-tabel ref="tableRef" :columns="columns" :mobilePrimaryFields="mobilePrimaryFields" :queryParams="search"
                 :api="listApi" :show-operation="false" :showPagination="true" :showSummary="true" :immediate="false"
                 :summaryMethod="getSummaries">
      </cwg-tabel>
    </view>
  </cwg-page-wrapper>
</template>

<script setup lang="ts">
  // 报告
  import { ref, computed, onMounted, watch, nextTick, reactive } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { onLoad } from '@dcloudio/uni-app'
  import Config from '@/config/index'
  import { ibApi } from '@/service/ib'
  import { useReportConst } from '@/pages/ib/const/report'
  import { useFilters } from '@/composables/useFilters'
  import { isAfterJuly28 } from '@/utils/dateUtils'
  import useUserStore from '@/stores/use-user-store'

  const { numberFormat } = useFilters()
  const { t, locale } = useI18n()
  const { columnList, mobileList, platformOptions, customTypeList, groupCurrency1, groupTypeName } = useReportConst()
  let { Code } = Config
  const { userInfo } = useUserStore()
  const tableRef = ref(null)
  const loading = ref(false)

  const typeList = computed(() => [
    { text: t('Ib.Report.Title1'), value: 1 },
    { text: t('Ib.Report.Title2'), value: 2 },
    { text: t('Ib.Report.Title3'), value: 3 },
    // { text: t('Ib.Report.Title6'), value: 4 },
    // 新增代理
    // { text: t('Ib.Report.Title5'), value: 5 },
    { text: t('news_add_field.IbReport.Title6'), value: 6 },
    // { text: t('Ib.Report.Title7'), value: 7 },
    //  加点报告
    // { text: t('Ib.Report.Title8'), value: 24 },
  ])
  const titleList = computed(() => {
    return {
      1: t('Ib.Report.Tit1'),
      4: t('Ib.Report.Tit4'),
    }
  })

  const isShortList = computed(() => [
    { text: t('State.All'), value: 0 },
    { text: t('Ib.Report.item1'), value: 1 },
    { text: t('Ib.Report.item2'), value: 2 },
  ])

  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const defaultDateRange = [`${year}-${month}-01`, `${year}-${month}-${day}`]

  const detailType = ref(1)

  const searchParams = ref<any>({
    detail_type: null,
    customType: 0,
    platform: 'MT4',
    agentId: '',
    login: '',
    cId: '',
    isShort: 0,
    date: defaultDateRange,
  })

  const search = reactive({
    detail_type: 1,
    customType: 0,
    platform: 'MT4',
    startDate: defaultDateRange[0],
    endDate: defaultDateRange[1],
    date: defaultDateRange,
    agentId: '',
    login: '',
    cId: '',
    isShort: 0,
  })

  const country = computed(() => {
    return userInfo.customInfo.country
  })

  const agentLevels = ref<Array<{ key: string, options: any[] }>>([
    {
      key: 'agentId_0',
      options: [
        { value: 0, text: t('news_add_field.IbReport.ALL') },
        { value: -1, text: t('news_add_field.IbReport.DirectlyUnder') },
      ],
    },
  ])

  const handleAgentChange = async (val: any, levelIndex: number) => {
    console.log(val, 'change1')

    // 截断当前层级之后的所有层级
    agentLevels.value.splice(levelIndex + 1)

    // 清理 searchParams 中被移除层级的值
    const params = { ...searchParams.value }
    for (let key in params) {
      if (key.startsWith('agentId_')) {
        const idx = parseInt(key.split('_')[1])
        if (idx > levelIndex) {
          delete params[key]
        }
      }
    }

    // 更新当前选中的代理ID
    params[`agentId_${levelIndex}`] = val

    // 同步更新 searchParams
    searchParams.value = { ...params }

    // 确保更新完成后再执行搜索
    await nextTick()
    handleSearch(searchParams.value)

    if (val === 0 || val === -1 || val === '') {
      return
    }

    try {
      const res = await ibApi.ibTree({ pid: val })
      if (res.code === Code.StatusOK && res.data && res.data.length > 0) {
        const nextOptions = []
        res.data.forEach((item: any) => {
          if (item.ibNo) {
            nextOptions.push({
              value: item.id,
              text: item.name ? `${item.ibNo} - ${item.name}` : item.ibNo,
            })
          }
        })
        if (nextOptions.length > 0) {
          agentLevels.value.push({
            key: `agentId_${levelIndex + 1}`,
            options: nextOptions,
          })
        }
      }
    } catch (error) {
      uni.showToast({ title: 'Error', icon: 'none' })
    }
  }

  const getSummaries = (param: any) => {
    const { columns, summaryData } = param
    const sums: string[] = []
    if (!summaryData || Object.keys(summaryData).length === 0) return sums

    columns.forEach((column: any, index: number) => {
      if (index === 0) {
        sums[index] = t('Label.Total')
        return
      }

      const type = reportType.value
      const detailType = search.detail_type

      // 根据不同的列 prop 进行合计数据显示和格式化
      const prop = column.prop
      if (!prop) {
        sums[index] = ''
        return
      }

      if (type == 1) {
        if (['deposit', 'withdrawal', 'credit'].includes(prop)) {
          sums[index] = summaryData[prop] ? numberFormat(summaryData[prop]) : '0'
        } else {
          sums[index] = ''
        }
      } else if (type == 2) {
        if (['volume', 'rebateAmount', 'commissionAmount'].includes(prop)) {
          sums[index] = summaryData[prop] ? numberFormat(summaryData[prop]) : '0'
        } else {
          sums[index] = ''
        }
      } else if (type == 3) {
        if (detailType == 4) {
          if (['volume', 'storage', 'taxes', 'profit'].includes(prop)) {
            sums[index] = summaryData[prop] ? numberFormat(summaryData[prop]) : '0'
          } else {
            sums[index] = ''
          }
        } else {
          if (['commission', 'volume', 'storage', 'taxes', 'profit', 'totalProfit'].includes(prop)) {
            sums[index] = summaryData[prop] ? numberFormat(summaryData[prop]) : '0'
          } else {
            sums[index] = ''
          }
        }
      } else if (type == 4) {
        if (['credit', 'balance', 'equity', 'floating'].includes(prop)) {
          sums[index] = summaryData[prop] ? numberFormat(summaryData[prop]) : '0'
        } else {
          sums[index] = ''
        }
      } else if (type == 6) {
        if (prop === 'amount') {
          sums[index] = summaryData[prop] ? numberFormat(summaryData[prop]) : '0'
        } else {
          sums[index] = ''
        }
      } else if (type == 7) {
        if (['fxVolume', 'cfdVolume', 'indexVolume', 'metalVolume'].includes(prop)) {
          sums[index] = summaryData[prop] ? numberFormat(summaryData[prop]) : '0'
        } else {
          sums[index] = ''
        }
      } else if (type == 24) {
        if (prop === 'volume') {
          sums[index] = summaryData[prop] ? numberFormat(summaryData[prop]) + ' /手' : '0'
        } else if (prop === 'rebate') {
          sums[index] = summaryData[prop] ? '$' + numberFormat(summaryData[prop]) : '0'
        } else {
          sums[index] = ''
        }
      } else {
        sums[index] = ''
      }
    })

    return sums
  }

  const handleSearch = (params: any) => {
    console.log(params, 'params')
    // 默认类型为页面参数
    const payload: any = { ...params, reportType: 3 }

    let finalAgentId = payload.agentId_0
    for (let i = agentLevels.value.length - 1; i >= 0; i--) {
      const val = payload[`agentId_${i}`]
      if (val !== undefined && val !== '') {
        finalAgentId = val
        break
      }
    }
    console.log(finalAgentId, 'finalAgentId')
    payload.agentId = finalAgentId
    if (payload.date?.length) {
      payload.startDate = payload.date[0]
      payload.endDate = payload.date[1]
    }

    const type = Number(payload.reportType)
    if (![1, 3, 4, 7, 24].includes(type)) payload.platform = ''
    if (![1, 2, 3, 4, 7].includes(type)) payload.login = ''
    if (type !== 7) payload.cId = ''
    if (![3, 7].includes(type)) payload.isShort = 0
    if (type !== 3) payload.detail_type = null
    if (type !== 24) payload.customType = 0

    Object.assign(search, payload)
    // search.reportType = payload.reportType
    // search.detail_type = payload.detail_type
    // search.customType = payload.customType
    // search.platform = payload.platform
    // search.startDate = payload.startDate
    // search.endDate = payload.endDate
    // search.date = payload.date
    // search.agentId = payload.agentId
    // search.login = payload.login
    // search.cId = payload.cId
    // search.isShort = payload.isShort
    nextTick(() => {
      tableRef.value?.refreshTable?.()
    })
  }

  const handleReset = (emptyParams: any) => {
    // 重置时清理级联菜单到只有第一层
    agentLevels.value.splice(1)
    handleSearch(emptyParams)
  }

  const initIbTree = async () => {
    const res = await ibApi.ibTree({ pid: 0 })

    if (res.code === Code.StatusOK) {
      if (res.data && res.data.length > 0) {
        res.data.forEach((item: any) => {
          if (item.ibNo) {
            let option = {
              value: item.id,
              text: item.name ? `${item.ibNo} - ${item.name}` : item.ibNo,
            }
            agentLevels.value[0].options.push(option)
          }
        })
      } else {
        uni.showToast({
          title: res.msg, icon: 'none',
        })
      }
    }
  }

  // 表格列配置 根据types 切换
  const columns = computed(() => {
    // console.log(detailType.value, '23')


    // console.log(columnList.value[`3_${detailType.value}`])
    return columnList.value[`3_${detailType.value}`] || []

  })


  const mobilePrimaryFields = computed(() => {
    let list: any[] = []


    list = mobileList.value[`3_${detailType.value}`] || []

    return [
      ...list,
      {
        prop: 'more',
        type: 'more',
        width: 20,
        align: 'center',
      },
    ]
  })

  // 接口 根据types 切换（动态代理不同类型报表API）
  const listApi = computed(() => {
    return async (params: any) => {
      let apiFn = ibApi.tradeDw

      const type = detailType.value


      if (type == 1) apiFn = ibApi.tradeHistory
      else if (type == 4) apiFn = ibApi.tradePosition

      if (apiFn) {
        return await apiFn(params)
      }
    }
  })


  onLoad((options) => {
    console.log(options?.type, 'type')
    // search.reportType = options?.type;
    // searchParams.value.reportType = options?.type;
    detailType.value = options?.detailType
  })
  onMounted(async () => {
    loading.value = true
    await initIbTree()
    loading.value = false
  })
  const filterFields = computed(() => {
    const fields = []
    fields.push({
      key: 'platform',
      type: 'select',
      label: t('Label.Platform'),
      placeholder: t('placeholder.choose'),
      options: platformOptions,
      defaultValue: 'MT4',
    })


    agentLevels.value.forEach((level, index) => {
      fields.push({
        key: level.key,
        type: 'select',
        label: t('State.All'),
        options: level.options,
        placeholder: t('State.All'),
        onChange: (val: any) => handleAgentChange(val, index),
        defaultValue: index === 0 ? 0 : '',
      })
    })


    fields.push({
      key: 'login',
      type: 'input',
      label: t('Label.TradingAccount'),
      placeholder: t('Label.TradingAccount'),
      defaultValue: '',
    })


    fields.push({
      key: 'isShort',
      type: 'select',
      label: t('placeholder.choose'),
      placeholder: t('placeholder.choose'),
      options: isShortList.value,
      defaultValue: 0,
      isSelect: true,
    })


    fields.push({ key: 'date', label: t('placeholder.Start') + ' - ' + t('placeholder.End'), type: 'daterange' })
    return fields
  })
  watch(locale, () => {
    agentLevels.value = [
      {
        key: 'agentId_0',
        options: [
          { value: 0, text: t('news_add_field.IbReport.ALL') },
          { value: -1, text: t('news_add_field.IbReport.DirectlyUnder') },
        ],
      },
    ]
    nextTick(() => {
      setFields()
    })
  })
</script>

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

  .search-content {
    display: flex;
    justify-content: space-between;
  }

  .report-platform {
    display: flex;
    align-items: center;

    .checklist-box {
      cursor: pointer;
      box-sizing: border-box;
      padding: 0 px2rpx(20);
      border: 1px solid #DCDFE6;
      background-color: #f5f5f5;
      height: px2rpx(35);
      line-height: px2rpx(35);
      border-radius: px2rpx(4) 0 0 px2rpx(4);

      &:last-child {
        border-radius: 0 px2rpx(4) px2rpx(4) 0;
      }

      &.active {
        color: var(--color-white);
        background-color: var(--color-error);
        border-color: var(--color-error);
      }
    }
  }

  .search-input-box {
    .uni-input {
      height: px2rpx(35);
      border: 1px solid #DCDFE6;
      padding: 0 px2rpx(20);
      border-radius: px2rpx(4);
      background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
    }
  }

  .agent-select {
    width: px2rpx(240);
  }

  .search-btn {
    height: px2rpx(36);
    line-height: px2rpx(36);
    margin: 0;
  }
</style>
