<template>
    <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
        <cwg-header :title="t('Documentary.TundManagement.item17')" />
        <view class="content-container">
            <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 #balanceEquity="{ row }">
                        <view class="sp-view-tab">
                            {{ numberDecimal(row.followBalance || 0) }}
                        </view>
                        <view class="sp-view-tab-b">
                            {{ numberDecimal(row.followEquity || 0) }}
                        </view>
                    </template>
                    <template #followType="{ row }">

                        <text v-t="followTypeMap[row.followType || row.loginType]" />
                    </template>
                    <template #followValue="{ row }">

                        <text v-if="row.followType == 1">{{ row.volume / 100 || "0" }}Lot</text>
                        <text v-if="row.followType == 2">{{ row.ratio || "0" }}%</text>
                        <text v-if="row.followType == 3">{{ "--" }}</text>
                    </template>
                    <template #timeRange="{ row }">
                        <view class="sp-view-tab">
                            {{ row.startTime || '--' }}
                        </view>
                        <view class="sp-view-tab-b">
                            {{ row.endTime || '--' }}
                        </view>
                    </template>
                </cwg-tabel>
            </view>
        </view>
    </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { computed, ref, nextTick, onMounted, reactive, watch } from 'vue';
import { useI18n } from 'vue-i18n';
const { t, locale } = useI18n();
import { documentaryApi } from '@/service/documentary';
import { useFilters } from '@/composables/useFilters'
const { numberDecimal, percentFormat } = useFilters()
const search = ref({
    type: 1
})
const typeMap = [
    { value: 'MT4', text: 'MT4' },
    { value: 'MT5', text: 'MT5' }]

// 动态传入筛选字段配置
const filterFields = computed(() => [
    { key: 'followPlatform', type: 'select', label: t('Label.Platform'), placeholder: t('placeholder.choose'), options: typeMap, defaultValue: 1 },
    !isSubscribeLoading.value && { key: 'followLogin', type: 'select', label: t('Documentary.console.item28'), placeholder: t('placeholder.choose'), options: accountDownData.value },
    { key: 'date', label: t('placeholder.Start') + ' - ' + t('placeholder.End'), type: 'daterange' }
])

const followTypeMap = {
    1: 'Documentary.tradingCenter.item116',
    2: 'Documentary.tradingCenter.item117',
    3: 'Documentary.tradingCenter.item118'
}
//获取客户跟单账户的下拉列表
const isSubscribeLoading = ref(false)
const accountDownData = ref([])
const getSubscribeLoginDown = async () => {
    isSubscribeLoading.value = true
    let res = await documentaryApi.followDealLoginList({
        platform: "",
        page: null,
    });
    if (res.code == 200) {
        accountDownData.value = res.data?.map(item => ({
            text: t('Documentary.console.item28') + '-' + item.dealLogin || '--',
            value: item.dealLogin
        })) || []
    } else {
        uni.showToast({
            title: res.msg,
            icon: 'none'
        })
    }
    isSubscribeLoading.value = false
}
const searchParams = ref({})
const tableRef = ref(null)
const handleSearch = (params) => {
    search.value = params
    nextTick(() => {
        tableRef.value.refreshTable()
    })
}

const handleReset = (params) => {
    search.value = params
    nextTick(() => {
        tableRef.value.refreshTable()
    })
}
// 当前列配置
const currentColumns = computed(() => [
    {
        prop: 'dealPlatform',
        label: t('Label.Platform'),
        align: 'center',
        formatter: ({ row }) => row.dealPlatform || '--'
    },
    {
        prop: 'followLogin',
        label: t('Documentary.TundManagement.item25'),
        align: 'center',
        formatter: ({ row }) => row.followLogin || '--'
    },
    {
        prop: 'followType',
        label: t('Documentary.TundManagement.item19'),
        align: 'center',
        slot: 'followType'        // 使用插槽显示跟单类型（正向/反向/混合）
    },
    {
        prop: 'followValue',
        label: t('Documentary.TundManagement.item20'),
        align: 'center',
        slot: 'followValue'       // 使用插槽显示跟单数值（手数/比例/--）
    },
    {
        prop: 'followLeverage',
        label: t('Label.Leverage'),
        align: 'center',
        formatter: ({ row }) => row.followLeverage ? `1:${row.followLeverage}` : '--'
    },
    {
        prop: 'balanceEquity',
        label: t('Label.Balance') + '/' + t('Label.Equity'),
        align: 'center',
        slot: 'balanceEquity',
    },
    {
        prop: 'timeRange',
        label: t('Documentary.TundManagement.item26'),
        align: 'center',
        slot: 'timeRange'     // 使用插槽显示开始时间和结束时间（上下两行）
    },
    // {
    //     prop: 'followProfit',
    //     label: t('Documentary.TundManagement.item21'),
    //     align: 'center',
    //     formatter: ({ row }) => percentFormat(row.followProfit || 0)
    // }
])

const selectLoginDeal = () => {
    loginOptionsLogin.value.forEach((item) => {
        if (item.login == dialogFllowDataApply.dealLogin) {
            dialogFllowDataApply.leverage = "1:" + item.leverage;
            dialogFllowDataApply.loginType = item.type;
            dialogFllowDataApply.platform = item.platform;
        }
    });
}

const applyRef = ref(null)
const dialogFllowDataApply = reactive({
    dealLogin: '',
    leverage: '',
    loginType: '',
    platform: '',
    currency: '',
    leverageStatus: '',
    withdrawStatus: '',
    depositStatus: '',
    accountStatus: '',
    status: '',
    note: '',
    followType: '',
    volume: '',
    ratio: '',
    traderStrategy: '',
    personalSignature: '',
    nickname: '',
    protectAmount: '',
    protectRatio: '',
    introduceShow: '',
    historyShow: '',
    historyTime: '',
    settlementCycle: '',
    distributionType: '',
    distributionRatio: '',
    withdrawCurrency: '',
    withdrawAmount: '',
    depositCurrency: '',
    depositAmount: '',
    withdrawLogin: '',
    depositLogin: '',
    addTime: '',
    title: '',
})
const loginOptionsLogin = ref([])
const dialogFllowApply = ref(false)
//获取申请信号源交易账户下拉
const getCustomLoginDownLogin = async () => {
    if (flag.value) {
        return;
    } else {
        flag.value = true;
    }
    let res = await documentaryApi.CustomDropdownData({
        platform: "",
    });
    if (res.code == 200) {
        loginOptionsLogin.value = res.data;
        dialogFllowApply.value = true;
    } else {
        uni.showToast({
            title: res.msg,
            icon: 'none'
        });
    }
    flag.value = false;
}
watch(() => dialogFllowDataApply.dealLogin, (newVal, oldVal) => {
    if (newVal !== oldVal) {
        selectLoginDeal();
    }
})

//申请信号源
const ApplyFllow = async () => {
    try {
        await applyRef.value.validate()
        if (flag.value) {
            return;
        } else {
            flag.value = true;
        }
        let res = await documentaryApi.followDealApply({
            ...dialogFllowDataApply,
        });
        if (res.code == 200) {
            uni.showToast({
                title: t("Msg.Success"),
                icon: 'none'
            });
            ApplyFllowCancel();
            tableRef.value.refreshTable();
            getDealLogin();
            flag.value = false;
        } else {
            uni.showToast({
                title: res.msg,
                icon: 'none'
            });
            flag.value = false;
        }
    } catch (error) {
        return false;
    } finally {
        flag.value = false;
    }
}
const ApplyFllowCancel = () => {
    applyRef.value &&
        applyRef.value.clearValidate();
    dialogFllowApply.value = false;
}

//获取客户信号源账户
const accountDataLoading = ref(false)
const accountData = ref([])
const accountPager = ref({
    current: 1,
    row: 10,
    rowTotal: 0,
    pageTotal: 0
})
const getDealLogin = async () => {
    accountDataLoading.value = true;
    let res = await documentaryApi.followDealList({
        platform: null,
        status: 2,
        page: {
            current: accountPager.value.current,
            row: accountPager.value.row,
        },
    });
    if (res.code == 200) {
        accountData.value = res.data || []
        accountPager.value.rowTotal = res.page.rowTotal;
        accountPager.value.pageTotal = res.page.pageTotal;
    } else {
        uni.showToast({
            title: res.msg,
            icon: 'none'
        });
    }
    accountDataLoading.value = false;

}
//修改信号源
const dialogFllowData = ref({})
const dialogFllow = ref(false)
const dialogFllowDataDelete = ref({})
const dialogFllowDelete = ref(false)
const flag = ref(false)

const listApi = ref(null)
onMounted(() => {
    getDealLogin()
    getSubscribeLoginDown()
    listApi.value = documentaryApi.followDealSubscribeDealList
})


</script>

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

.sp-view-tab {
    border-bottom: 1px dashed #98989880;
    line-height: 2;
}

.sp-view-tab-b {
    line-height: 2;
}

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


.content-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: px2rpx(22);
    font-weight: 500;
    color: var(--bs-emphasis-color);
    background-color: rgba(255, 255, 255, 0);

    .content-title-btns {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: px2rpx(12);


        .btn-primary {
            min-width: px2rpx(120);
            background-color: var(--color-error);
            color: #fff;
            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-primary1 {
            background-color: #cf1322;
            ;
        }

        .btn-primary2 {
            background-color: var(--color-secondary-focus);
        }
    }
}

.operation-btn {
    :deep(text) {
        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;
    }
}

.dia-content {
    padding: px2rpx(20);

    .uni-forms-item {
        width: 100%;
    }

    .grid-layout {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: px2rpx(20);
        margin: px2rpx(24) 0;
        padding: px2rpx(20);
        background-color: transparent;
        border-radius: px2rpx(8);
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }



    .fllow-title {
        display: flex;
        align-items: center;
        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;
        }
    }

    .delete-grid {
        margin: px2rpx(16) 0;
    }

    .delete-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: px2rpx(12);

        @media screen and (max-width: 768px) {
            grid-template-columns: 1fr;
        }
    }

    .delete-item {
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: px2rpx(12) 0;
        border-bottom: 1px dashed #e9ecef;

        &:first-child {
            padding-right: px2rpx(16);
        }

        &:last-child {
            padding-left: px2rpx(16);
        }
    }

    .delete-label {
        font-size: px2rpx(14);
        color: var(--bs-body-color);
    }

    .delete-value {
        font-size: px2rpx(14);
        color: var(--bs-emphasis-color);
        font-weight: 400;
    }

    .delete-tip {
        margin-top: px2rpx(16);
        font-size: px2rpx(14);
        color: var(--bs-emphasis-color);
        line-height: 1.5;
        padding-top: px2rpx(16);
    }

    .tip-star {
        color: #dc3545;
        margin-right: px2rpx(4);
    }

    .agree {
        margin-top: px2rpx(20);
    }

    .checkbox-agree {
        display: flex;
        align-items: flex-start;
        gap: px2rpx(8);

        .agree-text {
            font-size: px2rpx(14);
            color: var(--bs-body-color);
            line-height: 1.5;
            width: 100%;
            white-space: wrap;

            .a {
                color: #007bff;
                text-decoration: underline;
                margin: 0 px2rpx(4);

                &:hover {
                    color: #0056b3;
                }
            }
        }
    }

    .fllow-content {
        margin-bottom: px2rpx(16);

        .tit {
            font-size: px2rpx(14);
            font-weight: 500;
            color: var(--bs-body-color);
            margin-bottom: px2rpx(6);
            text-transform: uppercase;
            letter-spacing: px2rpx(0.5);
        }

        .con {
            font-size: px2rpx(16);
            font-weight: 400;
            color: var(--bs-emphasis-color);
            line-height: 1.4;
        }
    }

    .form-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: px2rpx(20);
        margin-top: px2rpx(16);
    }

    .form-item {
        display: flex;
        flex-direction: column;
        align-items: flex-start;

        text {
            font-size: px2rpx(14);
            font-weight: 500;
            color: var(--bs-body-color);
            margin-bottom: px2rpx(8);
            white-space: nowrap;
        }

        input,
        select,
        textarea {
            width: 100%;
            padding: px2rpx(10);
            border: 1px solid #ced4da;
            border-radius: px2rpx(4);
            font-size: px2rpx(14);
            transition: all 0.2s ease;

            &:focus {
                outline: none;
                border-color: #4dabf7;
                box-shadow: 0 0 0 2px rgba(77, 171, 247, 0.2);
            }
        }

        textarea {
            resize: vertical;
            min-height: px2rpx(100);
        }
    }

    .tip-red {
        color: #dc3545;
        font-size: px2rpx(14);
        margin: px2rpx(12) 0 px2rpx(24) 0;
    }

    .tip-text {
        margin-top: px2rpx(24);
        font-size: px2rpx(14);
        color: var(--bs-body-color);
        line-height: 1.5;
        padding: px2rpx(16);
        background-color: #e7f3ff;
        border-radius: px2rpx(4);
        border-left: 4px solid #4dabf7;
    }
}

/* 弹窗按钮样式 */
:deep(.cwg-popup__footer) {
    display: flex;
    gap: px2rpx(20);
    padding: px2rpx(20);
    border-top: 1px solid #e9ecef;

    button {
        flex: 1;
        padding: px2rpx(12) 0;
        border-radius: px2rpx(4);
        font-size: px2rpx(14);
        font-weight: 500;
        transition: all 0.2s ease;

        &:first-child {
            background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
            color: #495057;
            border: 1px solid #ced4da;

            &:hover {
                background-color: transparent;
                border-color: #adb5bd;
            }

            &:active {
                transform: scale(0.98);
            }
        }

        &:last-child {
            background-color: #dc3545;
            color: white;
            border: 1px solid #dc3545;

            &:hover {
                background-color: #c82333;
                border-color: #bd2130;
            }

            &:active {
                transform: scale(0.98);
            }
        }
    }
}
</style>
