import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/main.dart';
import 'package:qhd_prevention/pages/home/study/strengthen_video_study_page.dart';
import 'package:qhd_prevention/pages/home/study/study_class_list_page.dart';
import 'package:qhd_prevention/pages/home/study/study_detail_page.dart';
import 'package:qhd_prevention/pages/home/study/take_exam_page.dart';
import 'package:qhd_prevention/pages/home/study/video_study_detail_page.dart';
import 'package:qhd_prevention/tools/tools.dart';
import '../../../customWidget/toast_util.dart';
import '../../../http/ApiService.dart';
import '../../mine/mine_sign_page.dart';
import '../../my_appbar.dart';

class StudyMyTaskPage extends StatefulWidget {
  const StudyMyTaskPage({super.key});

  @override
  State<StudyMyTaskPage> createState() => _StudyMyTaskPageState();
}

class _StudyMyTaskPageState extends State<StudyMyTaskPage> with RouteAware  {
  int _page = 1;
  final int _showCount = 10;
  bool _isLoading = false;
  bool _hasMore = true;
  int _totalPage = 1;
  List<dynamic> _list = [];
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) => _getStudyList());
  }
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final modalRoute = ModalRoute.of(context);
    if (modalRoute is PageRoute) {
      routeObserver.subscribe(this, modalRoute);
    }
  }

  /// 当页面从覆盖中返回到前台
  @override
  void didPopNext() {
    if (!_isLoading) _getStudyList();
  }
  @override
  void didPush() {
    // 可选：首次 initState 已经调用过一次 _getStudyList，
    if (!_isLoading) _getStudyList();
  }
  @override
  void dispose() {
    _timer?.cancel();
    // 退订 routeObserver（防止内存泄漏）
    try {
      routeObserver.unsubscribe(this);
    } catch (_) {}
    super.dispose();
  }

  /// 每秒减少 remainingSeconds，用于倒计时显示
  void _startCountdownTimer() {
    if (_timer != null && _timer!.isActive) return; // 避免重复开启

    _timer = Timer.periodic(Duration(seconds: 1), (_) {
      setState(() {
        for (var i = 0; i < _list.length; i++) {
          final endTimeStr = _list[i]["END_TIME"] as String;

          try {
            // 直接用原始字符串解析
            final endTime = DateTime.parse(endTimeStr);
            final now = DateTime.now();
            final seconds = endTime.difference(now).inSeconds;

            _list[i]['remainingSeconds'] = seconds > 0 ? seconds : 0;
          } catch (e) {
            _list[i]['remainingSeconds'] = 0;
          }
        }
      });
    });
  }

  Future<void> _getStudyList({bool loadMore = false}) async {
    if (_isLoading) return;
    _isLoading = true;
    if (!loadMore) LoadingDialogHelper.show();

    try {
      final res = await ApiService.getStudyList(_page);
      if (res['result'] == 'success') {
        final List<dynamic> varList = res['varList'] ?? [];
        _totalPage = res['totalPage'] ?? 1;

        // 计算初始倒计时
        final now = DateTime.now();
        for (var item in varList) {
          final endStr =
              (item['END_TIME'] as String?)?.replaceAll('-', '/') ?? '';
          try {
            final end = DateTime.parse(endStr);
            final diff = end.difference(now).inSeconds;
            item['remainingSeconds'] = diff > 0 ? diff : 0;
          } catch (_) {
            item['remainingSeconds'] = 0;
          }
        }

        setState(() {
          if (loadMore) {
            _list.addAll(varList);
          } else {
            _list = varList;
          }
          _hasMore = _page < _totalPage;
          if (_hasMore) _page++;
          _startCountdownTimer();

        });
      }
    } catch (e) {
      debugPrint('加载出错: $e');
    } finally {
      if (!loadMore) LoadingDialogHelper.hide();
      _isLoading = false;
    }
  }

  String formatSeconds(int seconds) {
    if (seconds <= 0) return '00天 00:00:00';
    final d = Duration(seconds: seconds);
    return '${d.inDays.toString().padLeft(2, '0')}天 '
        '${(d.inHours % 24).toString().padLeft(2, '0')}:'
        '${(d.inMinutes % 60).toString().padLeft(2, '0')}:'
        '${(d.inSeconds % 60).toString().padLeft(2, '0')}';
  }

  Color _stateColor(String code) {
    switch (code) {
      case '1':
        return Colors.blue;
      case '2':
        return Colors.green;
      default:
        return Colors.grey;
    }
  }

  String _stateText(String code) {
    switch (code) {
      case '0':
        return '未学习';
      case '1':
        return '学习中';
      case '2':
        return '已学完';
      case '3':
        return '已完成';
      case '4':
        return '未完成';
      case '5':
        return '待评估';
      case '6':
        return '评估未合格';
      default:
        return '未知';
    }
  }

  void _onTapSign(Map item) async {
    await NativeOrientation.setLandscape();

    final String? imagePath = await Navigator.push<String>(
      context,
      MaterialPageRoute(builder: (_) => MineSignPage()),
    );
    await NativeOrientation.setPortrait();

    // 用户有签名并取到了 imagePath
    if (imagePath != null && imagePath.isNotEmpty) {
      // 上传
      await _uploadSignAndNavigate(item, imagePath);
    }
  }

  Future<void> _uploadSignAndNavigate(Map item, String imagePath) async {
    try {
      final File file = File(imagePath);
      final List<int> bytes = await file.readAsBytes();
      final String signBase64 = base64Encode(bytes);

      final result = await ApiService.signUpdate(
        signBase64,
        item['CLASS_ID'],
        item['STAGESTUDENTRELATION_ID'],
      );

      if (result['result'] == 'success') {
        pushPage(StudyClassListPage(item), context);
      }
    } catch (e) {
      // 捕获并提示错误
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('上传出错：$e')));
    }
  }

  Widget _buildItem(Map item) {
    final now = DateTime.now();
    final start = DateTime.tryParse(item['START_TIME'] ?? '');
    final end = DateTime.tryParse(item['END_TIME'] ?? '');
    final nowOk =
        start != null && end != null
            ? now.isAfter(start) && now.isBefore(end)
            : false;

    final int studyState = int.tryParse(item['STUDYSTATE'] ?? '') ?? 0;
    final int stageExamState = int.tryParse(item['STAGEEXAMSTATE'] ?? '') ?? 0;
    final int strengthenExamState =
        int.tryParse(item['STRENGTHENEXAMSTATE'] ?? '') ?? -1;
    final int numberOfExams = int.tryParse('${item['NUMBEROFEXAMS']}') ?? 0;
    final int ksCount = int.tryParse('${item['ksCount']}') ?? 0;
    final int examinationFlag =
        item['EXAMINATION'] is int
            ? item['EXAMINATION'] as int
            : int.tryParse('${item['EXAMINATION']}') ?? 0;
    final String isStrengthen = item['ISSTRENGTHEN'] ?? '0';

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        boxShadow: [BoxShadow(color: Colors.grey.shade200, blurRadius: 5)],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 顶部：名称 + 状态
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Text(
                  '培训任务名称: ${item['NAME']}',
                  style: const TextStyle(fontWeight: FontWeight.bold),
                ),
              ),
              const SizedBox(width: 10,),
              Text(
                _stateText(item['STUDYSTATE']),
                style: TextStyle(color: _stateColor(item['STUDYSTATE'])),
              ),
            ],
          ),

          const Divider(),

          // 中部：岗位类型 + 培训时间
          Text('岗位类型：${item['POSTTYPE_NAME']}'),
          Text('培训时间：${item['START_TIME']} 至 ${item['END_TIME']}'),

          const Divider(),

          // 底部：倒计时 + 按钮组
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  const Icon(Icons.access_time, size: 18, color: Colors.grey),
                  const SizedBox(width: 4),
                  Text(
                    formatSeconds(item['remainingSeconds'] ?? 0),
                    style: const TextStyle(fontSize: 12),
                  ),
                ],
              ),
              Wrap(
                spacing: 10,
                children: [
                  // 加强学习
                  if (studyState >= 2 &&
                      stageExamState >= 2 &&
                      (isStrengthen == '1' || isStrengthen == '2') &&
                      strengthenExamState == 0)
                    CustomButton(
                      height: 36,
                      text: "加强学习",
                      padding: EdgeInsets.symmetric(horizontal: 18),
                      borderRadius: 18,
                      backgroundColor: Colors.blue,
                      onPressed:
                          () => pushPage(
                            StrengthenStudyPage(
                              classId: item['CLASS_ID'] ?? '',
                              postId: item['POST_ID'] ?? '',
                              studentId: item['STUDENT_ID'] ?? '',
                            ),
                            context,
                          ),
                    ),

                  // 立即学习
                  if (studyState <= 1 && item['STATE'] == '5' && nowOk)
                    CustomButton(
                      height: 36,
                      text: "立即学习",
                      padding: EdgeInsets.symmetric(horizontal: 18),
                      borderRadius: 18,
                      backgroundColor: Colors.blue,
                      onPressed: () {
                        if (studyState == 0) {
                          _onTapSign(item);
                        } else {
                          pushPage(StudyClassListPage(item), context);
                        }
                      },
                    ),

                  // 立即考试
                  if (studyState == 2 &&
                      item['STATE'] != '6' &&
                      examinationFlag == 1 &&
                      stageExamState == 1 &&
                      ksCount < numberOfExams)
                    CustomButton(
                      height: 36,
                      text: "立即考试",
                      padding: EdgeInsets.symmetric(horizontal: 18),
                      borderRadius: 18,
                      backgroundColor: Colors.green,
                      onPressed:
                          () => _startExam(item, TakeExamType.video_study),
                    ),
                  // 考试详情
                  if (stageExamState == 3)
                    CustomButton(
                      height: 36,
                      text: "考试详情",
                      padding: EdgeInsets.symmetric(horizontal: 18),
                      borderRadius: 18,
                      backgroundColor: Colors.green,
                      onPressed: () {
                        pushPage(
                          VideoStudyDetailPage(
                            studentId: item['STUDENT_ID'] ?? '',
                            classId: item['CLASS_ID'] ?? '',
                          ),
                          context,
                        );
                      },
                    ),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }
  /// 开始考试
  Future<void> _startExam(Map resData, TakeExamType type) async {
    setState(() {
      _isLoading = true;
    });
    final arguments = {
      'STAGEEXAMPAPERINPUT_ID': resData['STAGEEXAMPAPERINPUT_ID'] ?? '',
      'STAGEEXAMPAPER_ID': resData['STAGEEXAMPAPER_ID'] ?? '',
      'CLASS_ID': resData['CLASS_ID'] ?? '',
      'POST_ID': resData['POST_ID'] ?? '',
      'STUDENT_ID': resData['STUDENT_ID'] ?? '',
      'NUMBEROFEXAMS': resData['NUMBEROFEXAMS'] ?? '',
    };
    print('--_startExam data---$arguments');

    final data = await ApiService.getStartExam(arguments);
    setState(() {
      _isLoading = false;
    });
    if (data['result'] == 'success') {
      pushPage(TakeExamPage(examInfo: {
        'CLASS_ID': resData['CLASS_ID'] ?? '',
        'POST_ID': resData['POST_ID'] ?? '',
        'STUDENT_ID': resData['STUDENT_ID'] ?? '',
        'STRENGTHEN_PAPER_QUESTION_ID': resData['STAGEEXAMPAPERINPUT_ID'] ?? '',
        ...data
      }, examType: TakeExamType.video_study), context);

    }else{
      ToastUtil.showError(context, '请求错误');
    }
  }


  bool _onScroll(ScrollNotification n) {
    if (n.metrics.pixels > n.metrics.maxScrollExtent - 100 &&
        _hasMore &&
        !_isLoading) {
      _getStudyList(loadMore: true);
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: '我的学习'),
      body: SafeArea(
        child: NotificationListener<ScrollNotification>(
          onNotification: _onScroll,
          child:
              _list.isEmpty
                  ? NoDataWidget.show()
                  : ListView.builder(
                    itemCount: _list.length,
                    itemBuilder: (_, i) => _buildItem(_list[i]),
                  ),
        ),
      ),
    );
  }
}
