<template>
    <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
        <cwg-header :title="t('Documentary.TundManagement.item10')" />
        <view class="info-card">
            <cwg-complex-search :fields="filterFields" v-model="searchParams" @search="handleSearch"
                @reset="handleReset" />
            <cwg-tabel ref="tableRef" :columns="currentColumns" :immediate="false" :queryParams="search" :api="listApi"
                :show-operation="false">
                <template #status="{ row }">
                    <view v-if="getStatusText(row)" class="status-tag" :class="getStatusClass(row)">
                        {{ getStatusText(row) }}
                    </view>
                    <view v-else></view>
                </template>
                <template #accountType="{ row }">
                    {{ getAccountTypeText(row.dealLoginType || row.followAccountType) }}
                </template>
            </cwg-tabel>
        </view>
    </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { computed, ref, reactive, nextTick, watch } from 'vue';
import { useI18n } from 'vue-i18n';
const { t, locale } = useI18n();
import { documentaryApi } from '@/service/documentary';
import useUserStore from "@/stores/use-user-store";
const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);
import { useAccountOptions } from '@/composables/useAccountOptions'
const { loginOptions, isLoaded, isSuccess } = useAccountOptions()
import { useFilters } from '@/composables/useFilters'
import {useFollowEnum} from '@/pages/follow/const/enum'

const {optObj} = useFollowEnum()
const { numberFormat, numberDesensitization, numberDecimal } = useFilters()
const search = reactive({
    type: 1,
    followLogin: null,
    status: null
})
const typeMap = computed(() => ([
    { value: 1, text: t('Documentary.TundManagement.item58') },
    { value: 2, text: t('Documentary.TundManagement.item47') },
]));
const isZh = computed(() => ['cn', 'zh', 'zhHant'].includes(locale.value));

// 账户类型映射
const accountTypeMap = {
    1: 'AccountType.ClassicAccount',
    2: 'AccountType.SeniorAccount',
    5: 'AccountType.SpeedAccount',
    6: 'AccountType.SpeedAccount',
    7: 'AccountType.StandardAccount',
    8: 'AccountType.CentAccount'
}
// 拒绝原因映射（示例）
const reasons = ref({})
// 根据类型获取列配置
const getColumnsByType = (type: number) => {
    switch (type) {
        case 1: //信号源申请
            return [
                {
                    prop: 'dealLogin',
                    label: t('Documentary.TundManagement.item25'),
                    align: 'center',
                    headerAlign: 'center',
                    formatter: ({ row }) => numberDesensitization(row.dealLogin) || '--'
                },
                {
                    prop: 'dealPlatform',
                    label: t('Label.Platform'),
                    align: 'center',
                    headerAlign: 'center',
                    formatter: ({ row }) => row.dealPlatform || '--'
                },
                {
                    prop: 'dealLoginType',
                    label: t('Label.AccountType'),
                    align: 'center',
                    slot: 'accountType' // 多语言枚举
                },
                {
                    prop: 'dealLeverage',
                    label: t('Label.Leverage'),
                    align: 'center',
                    formatter: ({ row }) => row.dealLeverage ? `1:${row.dealLeverage}` : '--'
                },
                {
                    prop: 'distributionType',
                    label: t('Documentary.TundManagement.item38'),
                    align: 'center',
                    headerAlign: 'center',
                    formatter: ({ row }) => row.distributionType === 1 ? t('Documentary.TundManagement.item59') : '--'
                },
                {
                    prop: 'distributionRatio',
                    label: t('Documentary.TundManagement.item39'),
                    align: 'center',
                    headerAlign: 'center',
                    formatter: ({ row }) => (row.distributionRatio || '0') + '%'
                },
                {
                    prop: 'settlementCycle',
                    label: t('Documentary.TundManagement.item55'),
                    align: 'center',
                    headerAlign: 'center',
                    formatter: ({ row }) => {
                      return optObj.value[row.settlementCycle] || '--'
                    }
                },
                {
                    prop: 'approveTime',
                    label: t('Documentary.TundManagement.item56'),
                    align: 'center',
                    formatter: ({ row }) => row.approveTime || '--'
                },
                {
                    prop: 'status',
                    label: t('Documentary.TundManagement.item57'),
                    align: 'center',
                    slot: 'status' // 状态
                },
                {
                    prop: 'approveDesc',
                    label: t('Label.Note'),
                    align: 'center',
                    type: 'note' // 备注多语言
                }
            ]
        case 2: // 取消记录
            return [
                {
                    prop: 'dealNickname',
                    label: t('Documentary.tradingCenter.item1'),
                    align: 'center',
                    headerAlign: 'center',
                    formatter: ({ row }) => row.dealNickname || '--'
                },
                {
                    prop: 'dealLogin',
                    label: t('Documentary.tradingCenter.item18'),
                    align: 'center',
                    headerAlign: 'center',
                    formatter: ({ row }) => numberDesensitization(row.dealLogin) || '--'
                },
                {
                    prop: 'followLogin',
                    label: t('Documentary.console.item28'),
                    align: 'center',
                    headerAlign: 'center',
                    formatter: ({ row }) => row.followLogin || '--'
                },
                {
                    prop: 'followPlatform',
                    label: t('Label.Platform'),
                    align: 'center',
                    formatter: ({ row }) => row.followPlatform || '--'
                },
                {
                    prop: 'followLoginType',
                    label: t('Label.AccountType'),
                    align: 'center',
                    slot: 'followAccountType'
                },
                {
                    prop: 'followLeverage',
                    label: t('Label.Leverage'),
                    align: 'center',
                    formatter: ({ row }) => row.followLeverage ? `1:${row.followLeverage}` : '--'
                },
                {
                    prop: 'distributionType',
                    label: t('Documentary.TundManagement.item38'),
                    align: 'center',
                    headerAlign: 'center',
                    formatter: () => t('Documentary.TundManagement.item59')
                },
                {
                    prop: 'distributionRatio',
                    label: t('Documentary.TundManagement.item39'),
                    align: 'center',
                    headerAlign: 'center',
                    formatter: ({ row }) => (row.distributionRatio || '0') + '%'
                },
                {
                    prop: 'settlementCycle',
                    label: t('Documentary.TundManagement.item55'),
                    align: 'center',
                    headerAlign: 'center',
                    formatter: ({ row }) => {
                      return optObj.value[row.settlementCycle] || '--'
                    }
                },
                {
                    prop: 'timeRange',
                    label: t('Documentary.TundManagement.item51') + ' / ' + t('Documentary.TundManagement.item52'),
                    align: 'center',
                    slot: 'timeRange' // 开始-结束时间
                },
                {
                    prop: 'endTime',
                    label: t('Documentary.TundManagement.item56'),
                    align: 'center',
                    formatter: ({ row }) => row.endTime || '--'
                }
            ]
    }
}
const setSearchValue = (key, value) => {
  search[key] = value
}

const filterFields = computed(() => {
  return [
    { key: 'type', type: 'select', label: t('Custom.PaymentHistory.payType'), placeholder: t('placeholder.choose'), options: typeMap.value },
    isLoaded.value && isSuccess.value && { key: search.type == 2 ? 'followLogin':'login', type: 'select', label: t('Custom.PaymentHistory.TradingAccount'), placeholder: t('placeholder.login'), options: loginOptions || [], defaultValue: search.login || undefined, clearable: true },
    { key: 'date', label: t('placeholder.Start') + ' - ' + t('placeholder.End'), type: 'daterange' }
  ]
})
const searchParams = ref({
  type: 1,
})
const tableRef = ref(null)
const handleSearch = (params) => {
  searchParams.value = {...params}
  Object.assign(search, params)
  nextTick(() => {
    tableRef.value?.refreshTable()
  })
}

const handleReset = (params) => {
  Object.assign(search, params)
  searchParams.value = {
    ...params,
    type: 1
  }
  nextTick(() => {
    tableRef.value?.refreshTable()
  })
}
const currentColumns = computed(() => getColumnsByType(search.type))
const getStatusText = (row: any) => {
    const status = row.status
    if (search.type === 1) {
        if (status === 0) return t('State.ToBeProcessed')
        if (status === 2) return t('State.Completed')
        if (status === 1) return t('State.InTheProcessing')
        if (status === 3) return t('State.Refused')
    } else if (search.type === 2) {
        if (status === 1) return t('State.ToBeProcessed')
        if (status === 2 && row.leverageStatus === 2) return t('State.Completed')
        if (status === 2 && row.leverageStatus === 1) return t('State.InTheProcessing')
        if (status === 3) return t('State.Refused')
    } else if (search.type === 3 || search.type === 5) {
        if (status === 1) return t('State.ToBeProcessed')
        if (status === 2 && row.withdrawStatus === 2 && row.depositStatus === 2) return t('State.Completed')
        if (status === 2 && (row.withdrawStatus === 1 || row.depositStatus === 1)) return t('State.InTheProcessing')
        if (status === 3 || row.withdrawStatus === 3 || row.depositStatus === 3) return t('State.Refused')
    } else {
        // 活动申请等
        if (status === 1) return t('State.ToBeProcessed')
        if (status === 2) return t('State.Completed')
        if (status === 3) return t('State.Refused')
    }
    return ''
}
// 获取状态样式类
const getStatusClass = (row: any) => {
    const text = getStatusText(row)
    if (text === t('State.Refused')) return 'status-failed'
    if (text === t('State.ToBeProcessed')) return 'status-pending'
    if (text === t('State.Completed')) return 'status-success'
    if (text === t('State.InTheProcessing')) return 'status-processing'
    return ''
}
// 获取账户类型文本
const getAccountTypeText = (type: number) => {
    const key = accountTypeMap[type as keyof typeof accountTypeMap]
    return key ? t(key) : '--'
}
// 格式化数字
const formatNumber = (value: string | number) => {
    if (!value) return '--'
    const num = Number(value)
    return isNaN(num) ? '--' : num.toFixed(2)
}
// 格式化备注
const formatNote = (approveDesc: string) => {
    if (!approveDesc) return '--'
    const reason = reasons.value[approveDesc as keyof typeof reasons.value]
    if (reason) {
        return isZh.value ? reason.content : reason.enContent
    }
    return approveDesc
}
const listApi = ref(null)
watch(() => search.type, (newVal) => {
    switch (newVal) {
        case 1:
            setSearchValue('status', null)
            setSearchValue('followLogin', null)
            listApi.value = documentaryApi.followDealList
            break
        case 2:
            setSearchValue('status', null)
            setSearchValue('followLogin', null)
            listApi.value = documentaryApi.followDealSubscribeList
            setSearchValue('status', 2)
            break
    }
}, { immediate: true })

</script>

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

.avatar {
    width: px2rpx(60);
    height: px2rpx(60);
    border-radius: 4px;
}

.content-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: px2rpx(20);
    font-weight: 500;

    .content-title-btns {
        margin: px2rpx(8) 0;

        display: flex;
        align-items: center;
        justify-content: center;
        gap: px2rpx(12);

        .btn-primary {
            min-width: px2rpx(120);
            background-color: var(--color-error);
            color: white;
            padding: 0 px2rpx(12);
            border: none;
            font-size: px2rpx(14);
            text-align: center;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: px2rpx(8);
        }

        .btn-primary:active {
            background-color: #cf1322;
            ;
        }
    }
}

.operation-btn {
    :deep(span) {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: px2rpx(4);
        cursor: pointer;
        background-color: var(--color-slate-150);
        padding: px2rpx(8) 0;
    }
}

.operation-btn.disabled {
    cursor: not-allowed;
    opacity: 0.5;
}

.search-bar {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;
    gap: px2rpx(16);
    margin: px2rpx(16) 0;

    .cwg-combox,
    .uni-easyinput,
    .uni-date {
        width: px2rpx(240) !important;
        flex: none;
    }
}
</style>
