<template>
    <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
        <cwg-header :title="t('wallet.item52')" />
        <view id="custom_history" class="">

            <view class="main-content">
                <!-- 无任务列表提示 -->
                <view class="list-empty-state" v-if="!tableData || tableData.length === 0">
                    <cwg-empty-state title="UtaskList.item12" />
                </view>
                <!-- 数据卡片展示 -->
                <view class="outer-card" v-for="(item, index) in tableData" :key="index"
                    v-show="tableData && tableData.length > 0">
                    <view class="data-cards">
                        <!-- 第一行：总数据 -->
                        <view class="total-data-row">
                            <view class="data-card total-card">
                                <view class="card-content">
                                    <view class="card-title">{{ t("UtaskList.item13") }}</view>
                                    <view class="card-value" style="color: #ff4d4f">
                                        {{ item.depositAmount || 0 }}
                                    </view>
                                </view>
                            </view>
                            <view class="data-card total-card">
                                <view class="card-content">
                                    <view class="card-title">{{ t("UtaskList.item3") }}</view>
                                    <view class="card-value" style="color: #ff4d4f">
                                        {{ item.completeVolume || 0 }}
                                    </view>
                                </view>
                            </view>
                            <view class="data-card total-card">
                                <view class="card-content">
                                    <view class="card-title">{{ t("surplusList.item8") }}</view>
                                    <view class="card-value" style="color: #ff4d4f">
                                        {{ item.amount }}
                                    </view>
                                </view>
                            </view>
                            <view class="data-card total-card">
                                <view class="card-content">
                                    <view class="card-title">{{ t("Label.State") }}</view>
                                    <view class="card-value" :style="item.status == 1 ? 'color: #ffd591;' : 'color: #52c41a;'
                                        ">
                                        {{ item.status == 1 ? t("State.Ongoing") : t("State.Completed") }}
                                    </view>
                                </view>
                            </view>
                        </view>

                        <!-- 第二行：分数据 -->
                        <view class="sub-data-row">
                            <view class="data-card">
                                <view class="card-content">
                                    <view class="card-value">{{ item.revokeCredit == 1 ? t("surplusList.item5") :
                                        t("surplusList.item6") }}</view>
                                    <view class="card-desc">{{ t("surplusList.item4") }}</view>
                                </view>
                            </view>
                            <view class="data-card">
                                <view class="card-content">
                                    <view class="card-value">{{ item.needVolume || 0 }}</view>
                                    <view class="card-desc">{{ t("UtaskList.item5") }}</view>
                                </view>
                            </view>
                            <view class="data-card">
                                <view class="card-content">
                                    <view class="card-value">{{ item.amount }}</view>
                                    <view class="card-desc">{{ t("UtaskList.item14") }}</view>
                                </view>
                            </view>
                            <view class="data-card">
                                <view class="card-content">
                                    <view class="card-value">{{ item.endTime }}</view>
                                    <view class="card-desc">{{ t("wallet.item55") }}</view>
                                </view>
                            </view>
                            <view class="data-card">
                                <view class="card-content">
                                    <view class="card-value">{{ item.endDate }}</view>
                                    <view class="card-desc">{{ t("UtaskList.item10") }}</view>
                                </view>
                            </view>
                            <view class="data-card" v-show="shouldShowCard(item, item)">
                                <button class="btn btn-primary waves-effect waves-light"  v-if="item.status === 1 && item.revokeCredit === 2" type="primary" size="small"
                                    @click="completeTask(item.id)" :loading="loadingStates[item.id] === 'complete'">
                                    {{ t("surplusList.item7") }}
                                </button>
                                <button class="btn btn-dark waves-effect waves-light btn-outline-dark1"  v-if="item.status === 1" @click="cancelTask(item.id)"
                                    :loading="loadingStates[item.id] === 'cancel'">
                                    {{ t("Btn.Cancel") }}
                                </button>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <cwg-confirm-popup />
    </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import { activityApi } from "@/service/activity"
import Config from "@/config/index"
import { useConfirm } from '@/hooks/useConfirm'
const confirm = useConfirm()
const { t, locale } = useI18n()
let { Code } = Config

// ---------- 存储辅助函数（模拟原 Session） ----------
const Session = {
    Get(key: string, parse = false) {
        const value = uni.getStorageSync(key)
        if (parse && value) {
            try {
                return JSON.parse(value)
            } catch {
                return value
            }
        }
        return value
    }
}

// ---------- 响应式数据 ----------
const flag = ref(false)
const reasons = ref({})
const pictLoading = ref(false)
const tableData = ref<any[]>([])
const time = ref("")
const loadingStates = ref<Record<string, string | null>>({})

// 卡片数据
const totalTasks = ref(0)
const totalRewards = ref(0)
const completionRate = ref("0")
const inProgressTasks = ref(0)
const completedTasks = ref(0)
const expiredTasks = ref(0)
const rejectedTasks = ref(0)
const todayRewards = ref(0)
const weekRewards = ref(0)
const monthRewards = ref(0)
const activityLevel = ref("0")

// 原 watch 中依赖的 search（保留）
const search = ref({ type: "" })

// ---------- 计算属性 ----------
const expireTime = computed(() => {
    return JSON.parse(Session.Get("user", true))
})

// 注意：document.body.clientWidth 在 uni-app 中不可用，改为获取屏幕宽度
const getScreenWidth = () => {
    const systemInfo = uni.getSystemInfoSync()
    return systemInfo.windowWidth
}

const lang = computed(() => {
    return (Session.Get("lang") == "en" && getScreenWidth() < 1330)
})

// ---------- 方法 ----------
const getStatus = (status: number) => {
    if (status == 1) {
        return t("State.Ongoing")
    } else if (status == 2) {
        return t("State.Completed")
    } else if (status == 3) {
        return t("State.Cancelled")
    } else if (status == 4) {
        return t("State.expireTime")
    }
}

const canPerformAction = (task: any) => {
    return task.status === 1 || (task.status === 2 && task.withdrawStatus === 1)
}

const shouldShowCard = (el: any) => {
    const hasRecoverCreditButton = el.status === 1 && el.revokeCredit === 2
    const hasCancelButton = el.status === 1
    return hasRecoverCreditButton || hasCancelButton
}

// 恢复信用
const completeTask = async (id: number) => {
    try {
        await confirm({
            title: t("Msg.SystemPrompt"),
            content: t("surplusList.item9"),
            confirmText: t("Btn.Confirm"),
            cancelText: t("Btn.Cancel"),
        })
        const res = await activityApi.ActivitySurplusRecoverCredit({ id })
        if (res.code == Code.StatusOK) {
            uni.showToast({ title: t("UtaskList.item9"), icon: "success" })
            searchFunc()
        } else {
            uni.showToast({ title: res.msg, icon: "none" })
        }
    } catch (error) {
        if (error?.msg) uni.showToast({ title: error.msg, icon: "none" })
    }
}

// 提现
const withdrawTask = async (id: number) => {
    return new Promise(async (resolve) => {
        const resConfirm = await uni.showModal({
            title: t("Msg.SystemPrompt"),
            content: t("UtaskList.item15"),
            confirmText: t("Btn.Confirm"),
            cancelText: t("Btn.Cancel"),
        })
        if (!resConfirm.confirm) return resolve(null)

        loadingStates.value[id] = "withdraw"
        try {
            const res = await activityApi.UcoinWithdraw({ id })
            if (res.code == Code.StatusOK) {
                uni.showToast({ title: t("Msg.Success"), icon: "success" })
                searchFunc()
            } else {
                uni.showToast({ title: res.msg, icon: "none" })
            }
        } catch (error) {
            uni.showToast({ title: t("Msg.Fail"), icon: "none" })
        } finally {
            loadingStates.value[id] = null
            resolve(null)
        }
    })
}
// 取消任务
const cancelTask = async (id: number) => {
    try {
        await confirm({
            title: t("Msg.SystemPrompt"),
            content: t("UtaskList.item8"),
            confirmText: t("Btn.Confirm"),
            cancelText: t("Btn.Cancel"),
        })
        const res = await activityApi.ActivityMonthlyCancel({ id })
        if (res.code == Code.StatusOK) {
            uni.showToast({ title: t("UtaskList.item9"), icon: "success" })
            searchFunc()
        } else {
            uni.showToast({ title: res.msg, icon: "none" })
        }
    } catch (error) {
        if (error?.msg) uni.showToast({ title: error.msg, icon: "none" })
    }
}

// 查看任务进度
const viewTaskProgress = async (id: number) => {
    loadingStates.value[id] = "progress"
    try {
        const res = await activityApi.UcoinProgress()
        if (res.code == Code.StatusOK) {
            uni.showToast({ title: res.msg, icon: "none" })
        } else {
            uni.showToast({ title: res.msg, icon: "none" })
        }
    } catch (error) {
        uni.showToast({ title: t("Msg.Fail"), icon: "none" })
    } finally {
        loadingStates.value[id] = null
    }
}

// 计算卡片数据
const calculateCardData = () => {
    // 可根据需求实现
}

// 返回活动
const backActivity = () => {
    uni.navigateTo({ url: "/customer/activities" })
}

// 获取列表
const searchFunc = async () => {
    if (flag.value) return
    flag.value = true

    pictLoading.value = true
    let res = await activityApi.ActivitySurplusTaskList()
    if (res.code == Code.StatusOK) {
        tableData.value = res.data
        calculateCardData()
        pictLoading.value = false
        flag.value = false
    } else {
        uni.showToast({ title: res.msg, icon: "none" })
        pictLoading.value = false
        flag.value = false
    }
}

// ---------- 生命周期与监听 ----------
onMounted(() => {
    searchFunc()
})

onUnmounted(() => {
    searchFunc()
})

// 原 watch（保留）
watch(
    () => search.value.type,
    () => {
        searchFunc()
    }
)
</script>

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

#custom_history {
    width: 100%;
    height: 100%;

    .no-data-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: px2rpx(300);

        .no-data-content {
            text-align: center;
            color: var(--bs-heading-color);

            i {
                font-size: px2rpx(48);
                margin-bottom: px2rpx(16);
                display: block;
            }

            p {
                font-size: px2rpx(16);
                margin: 0;
            }
        }
    }

    .main-content {
        width: 100%;
        height: calc(100% - 50px);
        // @include bg_white();
        padding: px2rpx(20);
        box-sizing: border-box;
        overflow: hidden;
        overflow-y: auto;
    }

    .state.btn {
        background: #eb3f57;
        color: white;
        padding: px2rpx(3) px2rpx(15);
        border-radius: px2rpx(4);
    }

    .action-buttons {
        display: flex;
        flex-direction: column;
        gap: px2rpx(8);
        align-items: center;

        .el-button {
            min-width: px2rpx(80);
            font-size: px2rpx(12);
        }

        .status-text {
            font-size: px2rpx(14);
            color: var(--bs-heading-color);
            font-weight: 500;
        }
    }

    // 外层卡片样式
    .outer-card {
        background: #ffffff;
        border-radius: px2rpx(16);
        padding: px2rpx(24);
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        border: 1px solid #f0f0f0;
        margin-bottom: px2rpx(30);
    }

    // 数据卡片样式
    .data-cards {
        display: flex;
        flex-direction: column;
        gap: px2rpx(20);

        .total-data-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: px2rpx(15);
        }

        .sub-data-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: px2rpx(15);
        }

        .data-card {
            background: #ffffff;
            border-radius: px2rpx(12);
            padding: px2rpx(24);
            //   box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            border: 1px solid #f0f0f0;
            transition: all 0.3s ease;
            text-align: center;

            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
            }

            // 根据状态设置背景色
            &.status-1 {
                background: #fff7e6; // 任务中 - 黄色背景
                border-color: #ffd591;
            }

            &.status-2 {
                background: #f6ffed; // 已完成 - 绿色背景
                border-color: #b7eb8f;
            }

            &.status-3,
            &.status-4 {
                background: #f5f5f5; // 已取消/已结束 - 灰色背景
                border-color: #d9d9d9;
            }

            &.total-card {
                background: #ffffff;
                color: var(--bs-heading-color);

                // border: 1px solid gray;
                .card-value {
                    color: var(--bs-heading-color);
                }

                .card-desc {
                    color: var(--bs-heading-color);
                }

                // 状态卡片的特殊样式
                &.status-1 {
                    background: #fff7e6;
                    border-color: #ffd591;
                }

                &.status-2 {
                    background: #f6ffed;
                    border-color: #b7eb8f;
                }

                &.status-3,
                &.status-4 {
                    background: #f5f5f5;
                    border-color: #d9d9d9;
                }
            }

            &.sub-card {
                background: #ffffff;
                border-left: px2rpx(4) solid #667eea;

                &:nth-child(2) {
                    border-left-color: #52c41a;
                }

                &:nth-child(3) {
                    border-left-color: #faad14;
                }

                &:nth-child(4) {
                    border-left-color: #ff4d4f;
                }
            }

            .card-content {
                .card-title {
                    font-size: px2rpx(16);
                    color: var(--bs-heading-color);
                    margin-bottom: px2rpx(8);
                    font-weight: 500;
                }

                .card-value {
                    font-size: px2rpx(18);
                    font-weight: 700;
                    color: var(--bs-heading-color);
                    margin-bottom: px2rpx(4);
                    line-height: 1;
                }

                .card-desc {
                    font-size: px2rpx(12);
                    color: var(--bs-heading-color);
                    line-height: 1.4;
                }
            }
        }

        .btn-card {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            gap: px2rpx(10);

            button {
                width: 100%;
            }
        }
    }

    // 响应式设计
    @media (max-width: 768px) {
        .data-cards {

            .total-data-row,
            .sub-data-row {
                grid-template-columns: 1fr;
            }

            .data-card {
                padding: px2rpx(16);

                .card-content {
                    .card-value {
                        font-size: px2rpx(24);
                    }
                }
            }
        }
    }
}
</style>
