<template>
    <div class="task-center">
        <!-- 页面标题和剩余推荐票 -->
        <div class="header">
            <h1 class="title">
                <el-icon class="title-icon"><List /></el-icon>
                任务中心
            </h1>
            <div class="remaining-tickets">
                剩余刷新：
                <span class="count">{{ remainingTickets }}</span> 
                张 推荐票
            </div>
        </div>

        <!-- 每日签到 -->
        <div class="section">
            <h2 class="section-title">每日签到</h2>
            <div class="sign-in-cards">
                <div 
                    v-for="day in signInDays" 
                    :key="day.id"
                    class="sign-card"
                    :class="{ 'completed': day.commonSignLog }"
                >
                    <div class="card-header">
                        <span class="day">{{ day.title }}</span>
                        <el-icon v-if="day.commonSignLog" class="check-icon"><Check /></el-icon>
                    </div>
                    <div class="reward">
                        <img :src="day.image || '@/assets/images/Recommendationvote.png'" alt="推荐票" class="reward-icon">
                        <span>推荐票 +{{ day.num }}</span>
                    </div>
                </div>
            </div>
            <div class="sign-button-container">
                <el-button 
                    type="primary"
                    size="large"
                    :disabled="!canSignToday"
                    :class="{ 'checked-btn': !canSignToday }"
                    @click="signIn"
                    class="sign-button"
                >
                    {{ !canSignToday ? '已签到' : '签到得奖励' }}
                </el-button>
            </div>
        </div>

        <!-- 更多任务 -->
        <div class="section">
            <h2 class="section-title">更多任务</h2>
            <div class="task-cards">
                <div 
                    v-for="task in moreTasks" 
                    :key="task.id"
                    class="task-card"
                >
                    <div class="task-info">
                        <h3 class="task-name">{{ task.title }}</h3>
                        <div class="task-reward">
                            <img 
                                src="@/assets/images/Recommendationvote.png" 
                                alt="推荐票" 
                                class="reward-icon"
                            >
                            <span>推荐票 +{{ task.num }}</span>
                        </div>
                    </div>
                    <el-button 
                        type="warning" 
                        size="small"
                        :disabled="task.commonTaskLog || !task.isTask"
                        @click="completeTask(task)"
                    >
                        {{ task.commonTaskLog ? '已领取' : (task.isTask ? '去领取' : '未达成') }}
                    </el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { List, Check } from '@element-plus/icons-vue';
import { taskApi } from '@/api/user.js';

export default {
    name: 'TaskCenter',
    components: {
        List,
        Check
    },
    setup() {
        const remainingTickets = ref(0);
        const signInDays = ref([]);
        const moreTasks = ref([]);
        const canSignToday = ref(false);

        // 获取我的推荐票数量
        const getMyRecommendTicketNum = async () => {
            try {
                const res = await taskApi.getMyRecommendTicketNum();
                remainingTickets.value = res.result || 0;
            } catch (error) {
                console.error('获取推荐票数量失败:', error);
                ElMessage.error('获取推荐票数量失败');
            }
        };

        // 获取签到任务列表
        const getSignTaskList = async () => {
            try {
                const token = localStorage.getItem('token');
                const res = await taskApi.getSignTaskList(token);
                if (res.result && Array.isArray(res.result)) {
                    signInDays.value = res.result;
                }
            } catch (error) {
                console.error('获取签到任务列表失败:', error);
                ElMessage.error('获取签到任务列表失败');
            }
        };

        // 获取更多任务列表
        const getMoreTaskList = async () => {
            try {
                const token = localStorage.getItem('token');
                const res = await taskApi.getMoreTaskList(token);
                if (res.result && Array.isArray(res.result)) {
                    moreTasks.value = res.result;
                }
            } catch (error) {
                console.error('获取更多任务列表失败:', error);
                ElMessage.error('获取更多任务列表失败');
            }
        };

        // 检查今日签到状态
        const checkTodaySignStatus = async () => {
            try {
                const res = await taskApi.getSignTaskToday();
                // res.result == 0 表示可以签到，否则表示已签到
                canSignToday.value = res.result;
            } catch (error) {
                console.error('获取今日签到状态失败:', error);
                // 默认设置为不可签到（已签到状态）
                canSignToday.value = false;
            }
        };



        // 签到方法
        const signIn = async () => {
            if (!canSignToday.value) {
                ElMessage.warning('今日已签到');
                return;
            }

            // 找到第一个未签到的任务
            let taskId = 0;
            for (let index = 0; index < signInDays.value.length; index++) {
                const element = signInDays.value[index];
                if (!element.commonSignLog) {
                    taskId = element.id;
                    break;
                }
            }

            if (!taskId) {
                ElMessage.warning('已全部签到');
                return;
            }

            try {
                await taskApi.clickSignTask(taskId);
                ElMessage.success('签到成功');
                
                // 签到成功后更新状态
                canSignToday.value = false;
                await Promise.all([
                    getSignTaskList(),
                    getMyRecommendTicketNum()
                ]);
            } catch (error) {
                console.error('签到失败:', error);
                ElMessage.error('签到失败，请稍后重试');
            }
        };

        // 处理任务点击逻辑
        const playTask = (task) => {
            if (task.keyName === 'key_comment') {
                // 每日首条评论
                ElMessage.info('发布一条评论即可领取');
            } else if (task.keyName === 'key_chapter') {
                // 每日首阅三个章节
                ElMessage.info('阅读3个新的章节小说即可领取');
            } else if (task.keyName === 'key_advertisement') {
                // 观看视频广告
                ElMessage.info('暂未开放');
            }
        };

        // 完成任务方法
        const completeTask = async (task) => {
            if (!task.isTask) {
                playTask(task);
                return;
            }

            if (task.commonTaskLog) {
                ElMessage.warning('任务已完成');
                return;
            }

            try {
                await taskApi.clickMoreTask(task.id);
                ElMessage.success('领取成功');
                
                // 任务完成后更新状态
                await Promise.all([
                    getMoreTaskList(),
                    getMyRecommendTicketNum()
                ]);
            } catch (error) {
                console.error('完成任务失败:', error);
                ElMessage.error('完成任务失败，请稍后重试');
            }
        };

        // 初始化数据
        const initData = async () => {
            try {
                await checkTodaySignStatus();
                await Promise.all([
                    getMyRecommendTicketNum(),
                    getSignTaskList(),
                    getMoreTaskList()
                ]);
            } catch (error) {
                console.error('初始化数据失败:', error);
            }
        };

        onMounted(() => {
            initData();
        });

        return {
            remainingTickets,
            signInDays,
            moreTasks,
            signIn,
            completeTask
        };
    }
};
</script>

<style lang="scss" scoped>
.task-center {
    padding: 24px;
    max-width: 1200px;
    margin: 0 auto;

    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 32px;
        padding-bottom: 16px;
        border-bottom: 1px solid #ebeef5;

        .title {
            display: flex;
            align-items: center;
            font-size: 24px;
            font-weight: 600;
            color: #0A2463;
            margin: 0;

            .title-icon {
                margin-right: 8px;
                font-size: 28px;
            }
        }

        .remaining-tickets {
            font-size: 14px;
            color: #666;

            .count {
                color: #0A2463;
                font-weight: 600;
                font-size: 16px;
            }
        }
    }

    .section {
        margin-bottom: 40px;

        .section-title {
            font-size: 18px;
            font-weight: 600;
            color: #303133;
            margin-bottom: 16px;
        }
    }

    .sign-in-cards {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: 16px;
        max-width: 900px;

        .sign-card {
            background: #f8f9fa;
            border: 1px solid #e4e7ed;
            border-radius: 8px;
            padding: 16px;
            text-align: center;
            transition: all 0.3s ease;
            position: relative;

            &.completed {
                background: #e8f5e8;
                border-color: #67c23a;
                
                .check-icon {
                    position: absolute;
                    top: 0;
                    right: 0;
                    width: 20px;
                    height: 20px;
                    background: #67c23a;
                    border-radius: 50%;
                    color: white;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 12px;
                }
            }

            &.current {
                background: #fff7e6;
                border-color: #ffa726;
                box-shadow: 0 2px 8px rgba(255, 167, 38, 0.2);
            }

            .card-header {
                display: flex;
                justify-content: center;
                align-items: center;
                margin-bottom: 12px;
                position: relative;

                .day {
                    font-size: 14px;
                    font-weight: 600;
                    color: #303133;
                }
            }

            .reward {
                display: flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 12px;
                font-size: 12px;
                color: #666;

                .reward-icon {
                    width: 16px;
                    height: 16px;
                    margin-right: 4px;
                }
            }

            .el-button {
                width: 100%;
                
                &.el-button--success {
                    background-color: #67c23a;
                    border-color: #67c23a;
                }
                
                &.el-button--primary {
                    background-color: #0A2463;
                    border-color: #0A2463;
                }
            }
        }

    }
    
    .sign-button-container {
        margin-top: 16px;
        display: flex;
        justify-content: center;
        .sign-button {
            width: 280px;
            height: 44px;
            border-radius: 22px;
            font-weight: 600;
            background-color: #0A2463;
            border-color: #0A2463;

            &.checked-btn {
                background: linear-gradient(90deg, #e0e0e0, #bdbdbd) !important;
                border-color: #bdbdbd !important;
                color: #666 !important;
                cursor: not-allowed;
            }
        }
    }

    .task-cards {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 16px;

        .task-card {
            background: #faf8f0;
            border: 1px solid #f0e6cc;
            border-radius: 8px;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;

            &:hover {
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }

            .task-info {
                flex: 1;

                .task-name {
                    font-size: 16px;
                    font-weight: 600;
                    color: #303133;
                    margin: 0 0 8px 0;
                }

                .task-reward {
                    display: flex;
                    align-items: center;
                    font-size: 14px;
                    color: #666;

                    .reward-icon {
                        width: 16px;
                        height: 16px;
                        margin-right: 4px;
                    }
                }
            }

            .el-button {
                margin-left: 16px;
                min-width: 80px;
            }
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .task-center {
        padding: 16px;

        .header {
            flex-direction: column;
            align-items: flex-start;
            gap: 12px;

            .title {
                font-size: 20px;
            }
        }

        .sign-in-cards {
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 12px;

            .sign-card {
                padding: 12px;
            }
        }

        .task-cards {
            grid-template-columns: 1fr;

            .task-card {
                flex-direction: column;
                align-items: flex-start;
                text-align: left;

                .el-button {
                    margin-left: 0;
                    margin-top: 12px;
                    width: 100%;
                }
            }
        }
    }
}
</style> 