<template>
    <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
        <cwg-header :title="t('Home.page_customer.item4')" />
        <view class="info-card">
            <cwg-complex-search :fields="filterFields" v-model="searchParams" @search="handleSearch"
                @reset="handleReset" />
            <cwg-tabel ref="tableRef" :columns="columns" :immediate="false" :mobilePrimaryFields="mobilePrimaryFields"
                :queryParams="search" :api="listApi" :show-operation="false">
                <template #avatar="{ row }">
                    <image :src="row.avatar" class="avatar" mode="widthFix" />
                    <cwg-file :path="row.path" />
                </template>
                <template #type="{ row }">
                    {{typeMap.find(item => item.value === row.type)?.text}}
                </template>
                <template #status="{ row }">
                    <view class="status-box">
                        <template v-if="row.type == 1">
                            <text v-if="
                                row.status == 1 &&
                                row.callbackStatus == 0 &&
                                (row.expireTime == null || time < row.expireTime)
                            " class="status-tag status-pending" v-t="'State.ToBeProcessed'"></text>
                            <text v-if="
                                row.status == 2 &&
                                row.executionStatus == 2 &&
                                row.callbackStatus == 1
                            " class="status-tag status-completed" v-t="'State.Completed'"></text>
                            <text v-if="
                                row.status == 2 &&
                                (row.executionStatus == 1 || row.executionStatus == 0) &&
                                row.callbackStatus != 2 &&
                                (row.expireTime == null || time < row.expireTime)
                            " class="status-tag status-processing" v-t="'State.InTheProcessing'"></text>
                            <text v-if="
                                row.callbackStatus == 2 ||
                                row.status == 3 ||
                                row.executionStatus == 3
                            " class="status-tag status-failed" v-t="'State.Refused'"></text>
                            <text v-if="
                                !(
                                    row.status == 2 &&
                                    row.executionStatus == 2 &&
                                    row.callbackStatus == 1
                                ) &&
                                !(
                                    row.callbackStatus == 2 ||
                                    row.status == 3 ||
                                    row.executionStatus == 3
                                ) &&
                                row.expireTime != null &&
                                time > row.expireTime
                            " class="status-tag status-expired" v-t="'State.expireTime'"></text>
                        </template>

                        <template v-if="row.type == 2">
                            <text v-if="
                                row.status == 1 &&
                                row.callbackStatus == 0 &&
                                (row.expireTime == null || time < row.expireTime)
                            " class="status-tag status-pending" v-t="'State.ToBeProcessed'"></text>
                            <text v-if="
                                row.status == 2 &&
                                row.executionStatus == 2 &&
                                row.submitStatus == 2
                            " class="status-tag status-completed" v-t="'State.Completed'"></text>
                            <text v-if="
                                (row.status == 2 &&
                                    (row.executionStatus == 1 || row.executionStatus == 0) &&
                                    row.callbackStatus != 2) ||
                                (row.status == 2 &&
                                    row.executionStatus == 2 &&
                                    row.callbackStatus == 0 &&
                                    row.type == 2 &&
                                    row.submitStatus != 2)
                            " class="status-tag status-processing" v-t="'State.InTheProcessing'"></text>
                            <text v-if="
                                row.callbackStatus == 2 ||
                                row.status == 3 ||
                                row.executionStatus == 3
                            " class="status-tag status-failed" v-t="'State.Refused'"></text>
                        </template>

                        <text v-if="row.status == 5" class="status-tag status-cancelled" v-t="'State.Cancelled'"></text>

                        <!-- 取消按钮（保留原有功能，不添加状态类名） -->
                        <view v-if="
                            row.status == 1 &&
                            row.callbackStatus == 0 &&
                            (row.expireTime == null || time < row.expireTime) &&
                            row.type == 2
                        ">
                            <text class="status-tag btn crm-cursor status-cancelled" v-t="'Btn.Cancel'"
                                @click.stop="cancleConfirm(row.id, 1)"></text>
                        </view>
                        <view v-if="
                            row.status == 2 &&
                            row.executionStatus == 2 &&
                            row.backstageStatus == 1 &&
                            row.type == 2
                        ">
                            <text class="status-tag btn crm-cursor status-cancelled" v-t="'Btn.Cancel'"
                                @click.stop="cancleConfirm(row.id, 2)"></text>
                        </view>
                    </view>
                </template>
                <template #btn="{ row }">
                    <text :class="['operation-btn', row.status !== 4 ? 'disabled' : '']" @click="openAddFile(row)">
                        <cwg-icon name="crm-image" :size="16" color="#1d293d" />
                        <text v-t="'State.Again'" />
                    </text>
                </template>
            </cwg-tabel>
        </view>
        <cwg-confirm-popup />
    </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { computed, ref, nextTick, reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import { onLoad } from '@dcloudio/uni-app'
const { t, locale } = useI18n();
import { financialApi } from '@/service/financial';
import { useConfirm } from '@/hooks/useConfirm'
import { useAccountOptions } from '@/composables/useAccountOptions'
const { loginOptions, isLoaded, isSuccess } = useAccountOptions()
const search = reactive({
    login: null,
    type: null,
    orderStatus: null,
    date: null
})
const typeMap = computed(() => ([
    { value: null, text: t('Custom.PaymentHistory.All') },
    { value: 1, text: t('Custom.PaymentHistory.Deposit') },
    { value: 2, text: t('Custom.PaymentHistory.Withdrawals') }
]));
const orderStatusMap = computed(() => ([
    { value: null, text: t('Custom.PaymentHistory.All') },
    { value: 1, text: t('State.ToBeProcessed') },
    { value: 2, text: t('State.Completed') },
    { value: 3, text: t('State.InTheProcessing') },
    { value: 4, text: t('State.Refused') },
    { value: 5, text: t('State.expireTime') },
    { value: 6, text: t('State.Cancelled') },
]));
const isZh = computed(() => ['cn', 'zh', 'zhHant'].includes(locale.value));

const time = computed(() => {
    let timezone = 2; //目标时区时间，东3区   东时区正数 西市区负数
    let offset_GMT = new Date().getTimezoneOffset(); // 本地时间和格林威治的时间差，单位为分钟
    let nowDate = new Date().getTime(); // 本地时间距 1970 年 1 月 1 日午夜（GMT 时间）之间的毫秒数
    let now = new Date(
        nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000
    );

    //当前时间
    let hh = now.getHours(); //时
    let mm = now.getMinutes(); //分
    let ss = now.getSeconds(); //分
    let clock;
    let year = now.getFullYear(); //年
    let month = now.getMonth() + 1; //月
    let day = now.getDate(); //日
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    if (hh < 10) {
        hh = "0" + hh;
    }
    if (mm < 10) {
        mm = "0" + mm;
    }
    if (ss < 10) {
        ss = "0" + ss;
    }
    clock = year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss;
    return clock;
})
// 表格列配置
const columns = computed(() => [
    {
        prop: 'serial',
        label: t('Custom.PaymentHistory.Serial'),
        align: 'left'
    },
    {
        prop: 'login',
        label: t('Custom.PaymentHistory.TradingAccount'),
        align: 'left'
    },
    {
        prop: 'type',
        label: t('Custom.PaymentHistory.payType'),
        align: 'left',
        slot: 'type'
    },
    {
        prop: 'channelName',
        label: t('Custom.PaymentHistory.PaymentMethod'),
        formatter: ({ row }) => isZh.value ? row.channelName : row.channelEnName,
        align: 'left'
    },
    {
        prop: 'amount',
        label: t('Custom.PaymentHistory.Amount'),
        formatter: ({ row }) => row.amount + ' ' + row.currency,
        align: 'left'
    },
    {
        prop: 'addTime',
        label: t('Custom.PaymentHistory.ApplicationDate'),
        type: 'date',
        dateFormat: 'YYYY-MM-DD HH:mm',
        align: 'left'
    },
    {
        prop: 'status',
        label: t('Custom.PaymentHistory.Status'),
        slot: 'status',
        align: 'left'
    },
    {
        prop: 'note',
        label: t('Custom.Recording.Note'),
        type: 'note',
        align: 'right'
    },
    {
        prop: 'more',
        type: 'more',
        width: 20,
        align: 'right'
    },
])
// 动态传入筛选字段配置
const filterFields = computed(() => [
    { key: 'type', type: 'select', label: t('Custom.PaymentHistory.payType'), placeholder: t('placeholder.choose'), options: typeMap.value, defaultValue: null },
    {
        key: 'orderStatus', type: 'select', label: t('Custom.PaymentHistory.Status'), placeholder: t('placeholder.choose'), options: orderStatusMap.value, defaultValue: null
    },
    isLoaded.value && isSuccess.value && { key: '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({})

const handleSearch = (params) => {
    Object.assign(search, params)
    search.platform = loginOptions.find(item => item.value === params.login)?.platform || ''
    nextTick(() => {
        tableRef.value.refreshTable()
    })
}

const handleReset = (params) => {
    Object.assign(search, params)
    search.platform = loginOptions.find(item => item.value === params.login)?.platform || ''
    nextTick(() => {
        tableRef.value.refreshTable()
    })
}
const mobilePrimaryFields = computed(() => [
    {
        prop: 'serial',
        label: t('Custom.PaymentHistory.Serial'),
        align: 'left'
    },
    {
        prop: 'status',
        label: t('Custom.PaymentHistory.Status'),
        slot: 'status',
        align: 'left'
    },
    {
        prop: 'amount',
        label: t('Custom.PaymentHistory.Amount'),
        formatter: ({ row }) => row.amount + ' ' + row.currency,
        align: 'right'
    },
    {
        prop: 'more',
        type: 'more',
        width: 20,
        align: 'right'
    },
])
const listApi = ref(null)
listApi.value = financialApi.BalanceList
const confirm = useConfirm()

const cancleConfirm = async (id, type) => {
    tableRef.value.setDetailVisible(false)
    try {
        await confirm({
            title: t('Msg.SystemPrompt'),
            content: t('Msg.Cancle'),
            confirmText: t('Btn.item6'),
            cancelText: t('Btn.item7')
        })
        cancle(id, type)
    } catch (error) {
    }
}
const tableRef = ref(null)
const cancle = async (id, type) => {
    try {
        let api
        if (type == 1) {
            api = financialApi.withdrawCancel
        } else {
            api = financialApi.withdrawCancelBackstage
        }
        let res = await api({ id: id });
        if (res.code == 200) {
            uni.showToast({
                title: t("Msg.Success"),
                icon: 'success'
            });
            tableRef.value.refreshTable()
        } else {
            uni.showToast({
                title: res.msg,
                icon: 'error'
            });
        }
    } catch (error) {
        console.log('取消删除')
    }
}
onLoad((e) => {
    if (e.login) {
        search.login = Number(e.login)
    }
})
</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(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;
}
</style>
