import * as taskService from './modules/task-service.js';
import * as timerUtils from './modules/timer-utils.js';

Page({
      data: {
            imageUrl: '',
            textContent: '',
            taskId: null,
            courseId: null,
            loading: true,
            progressLoading: true, // 进度加载中
            timerText: '加载中...', // 初始为加载中文案
            remainingTime: 0, // 剩余时间（秒），从接口获取
            startTime: null,
            isCompleted: false, // 添加完成状态标记
      },

      onLoad(options) {
            const { task_id, task_title, camp_id, course_id, task_status } = options

            this.setData({
                  taskId: task_id,
                  campId: camp_id,
                  courseId: course_id,
                  task_status,
                  startTime: new Date().getTime(),
                  progressLoading: true,
                  timerText: '加载中...'
            });

            // 设置导航栏标题
            wx.setNavigationBarTitle({
                  title: task_title
            });

            if (task_status == 'Completed') {
                  this.setData({
                        isCompleted: true,
                        timerText: '已完成',
                        progressLoading: false
                  });
            }

            // 按正确顺序：先获取任务详情，再获取任务进度
            if (task_id) {
                  wx.showLoading({ title: '加载中...' });
                  // 1. 先获取任务详情（包含倒计时时长）
                  this.getTaskDetail().then(() => {
                        wx.hideLoading();
                        // 2. 任务详情获取成功后，再获取任务进度
                        this.getProgressDetail();
                  }).catch(err => {
                        wx.hideLoading();
                        console.error('获取任务详情失败:', err);
                        this.setData({ 
                              progressLoading: false,
                              timerText: '00:00'
                        });
                        wx.showToast({
                              title: '加载任务失败',
                              icon: 'none'
                        });
                  });
            } else {
                  this.setData({ 
                        progressLoading: false,
                        timerText: '00:00'
                  });
            }
      },

      // 获取用户任务进度
      getProgressDetail() {
            const userId = wx.getStorageSync('wxuserid');
            const { taskId } = this.data;
            
            if (!userId || !taskId) {
                  this.setData({ progressLoading: false });
                  if (!this.data.isCompleted && this.data.remainingTime > 0 && !this.timerInterval) {
                        this.startTimer();
                  }
                  return Promise.resolve();
            }

            return taskService.getProgressDetail(userId, taskId)
                  .then(progress => {
                        if (progress && (progress.is_completed === true || progress.is_completed === 1)) {
                              this.setData({
                                    isCompleted: true,
                                    timerText: '已完成',
                                    progressLoading: false
                              });
                              return;
                        }
                        
                        if (!this.data.isCompleted && this.data.remainingTime > 0 && !this.timerInterval) {
                              this.startTimer();
                        }
                        this.setData({ progressLoading: false });
                  })
                  .catch(err => {
                        console.error('获取任务进度失败:', err);
                        if (!this.data.isCompleted && this.data.remainingTime > 0 && !this.timerInterval) {
                              this.startTimer();
                        }
                        this.setData({ progressLoading: false });
                  });
      },

      getTaskDetail() {
            const { taskId } = this.data;
            
            if (!taskId) {
                  this.setData({ 
                        progressLoading: false,
                        timerText: '00:00'
                  });
                  return Promise.reject(new Error('任务ID为空'));
            }

            return taskService.getTaskDetail(taskId).then(taskData => {
                  this.setData({
                        imageUrl: taskData.imageUrl,
                        textContent: taskData.textContent,
                        taskType: taskData.taskType,
                        remainingTime: taskData.remainingTime,
                        timerText: taskData.remainingTime > 0 ? timerUtils.formatTimer(taskData.remainingTime) : '00:00'
                  });
            }).catch(err => {
                  console.error('获取任务详情失败:', err);
                  this.setData({ 
                        timerText: '00:00',
                        remainingTime: 0
                  });
                  throw err;
            });
      },

      // 图片加载成功
      onImageLoad() {
            this.setData({
                  loading: false
            });
      },

      // 图片加载失败
      onImageError() {
            this.setData({
                  loading: false
            });
            wx.showToast({
                  title: '图片加载失败',
                  icon: 'none'
            });
      },

      // 预览图片
      previewImage() {
            const { imageUrl } = this.data;
            if (imageUrl) {
                  wx.previewImage({
                        urls: [imageUrl],
                        current: imageUrl
                  });
            }
      },



      startTimer() {
            timerUtils.startTimer(this, () => {
                  // 倒计时结束回调
                  const taskId = String(this.data.taskId);
                  const userId = String(wx.getStorageSync('wxuserid') || '');

                  taskService.updateProgressToCompleted(userId, taskId)
                        .then(res => {
                              console.log('更新任务进度成功:', res);
                              if (res && res.success === true) {
                                    console.log('任务进度已更新为已完成');
                              } else {
                                    console.error('更新任务进度失败:', res);
                                    wx.showToast({
                                          title: res && res.message || '更新进度失败',
                                          icon: 'none'
                                    });
                              }
                        })
                        .catch(err => {
                              console.error('更新任务进度异常:', err);
                              wx.showToast({
                                    title: '更新进度失败',
                                    icon: 'none'
                              });
                        });

                  this.setData({
                        isCompleted: true,
                        timerText: '已完成'
                  });

                  wx.showToast({
                        title: '学习完成！',
                        icon: 'success'
                  });
            });
      },

      onUnload() {
            timerUtils.stopTimer(this);
      }

}); 