// pages/tasks/index.js
import { MOCK_TASKS_DATA } from '../../utils/mockData';

Page({
    data: {
        tasks: [],
        groupedTasks: [],
        progress: 0,
        completingTask: null,
        remark: ''
    },

    onLoad() {
        this.setData({ tasks: MOCK_TASKS_DATA });
        this.processTasks();
    },

    onShow() {
        if (typeof this.getTabBar === 'function' &&
            this.getTabBar()) {
            this.getTabBar().setData({ selected: 1 });
        }
    },

    processTasks() {
        const { tasks } = this.data;

        // Calculate Progress (Simulated)
        const completedCount = 3; // Mocked existing completed
        const initialTotal = MOCK_TASKS_DATA.length + completedCount;
        const currentCompleted = completedCount + (MOCK_TASKS_DATA.length - tasks.length);
        const progress = Math.min(100, Math.round((currentCompleted / initialTotal) * 100));

        // Grouping
        const groups = {};
        tasks.forEach(task => {
            if (!groups[task.plantName]) {
                groups[task.plantName] = {
                    plantName: task.plantName,
                    plantImage: task.plantImage,
                    tasks: [],
                    hasOverdue: false
                };
            }
            groups[task.plantName].tasks.push(task);
            if (task.isOverdue) groups[task.plantName].hasOverdue = true;
        });

        // Sorting
        const sortedGroups = Object.values(groups).sort((a, b) => {
            if (a.hasOverdue && !b.hasOverdue) return -1;
            if (!a.hasOverdue && b.hasOverdue) return 1;
            return 0;
        });

        this.setData({
            groupedTasks: sortedGroups,
            progress
        });
    },

    handleTaskClick(e) {
        // e.currentTarget.dataset.task might differ if TDesign changes event structure, 
        // but 'data-task' on t-button works similarly in Miniprogram.
        const task = e.currentTarget.dataset.task;
        this.setData({
            completingTask: task,
            remark: ''
        });
    },

    onPopupVisibleChange(e) {
        // Handle both TDesign event and manual close tap
        const visible = e.detail ? e.detail.visible : e.currentTarget.dataset.visible;
        if (!visible) {
            this.setData({ completingTask: null });
        }
    },

    onRemarkInput(e) {
        this.setData({ remark: e.detail.value });
    },

    handleConfirmComplete() {
        if (!this.data.completingTask) return;

        const taskId = this.data.completingTask.id;
        // Filter out the completed task
        const newTasks = this.data.tasks.filter(t => t.id !== taskId);

        this.setData({
            tasks: newTasks,
            completingTask: null
        }, () => {
            this.processTasks();
            wx.showToast({ title: '已完成', icon: 'success' });
        });
    }
})
