import 'dart:async';
import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/remote_file_page.dart';
import 'package:qhd_prevention/customWidget/toast_util.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/tools/tools.dart';
import 'package:video_player/video_player.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import '../../../customWidget/video_player_widget.dart';

/// 加强学习
class StrengthenStudyPage extends StatefulWidget {
  final String classId;
  final String postId;
  final String studentId;

  const StrengthenStudyPage({
    super.key,
    required this.classId,
    required this.postId,
    required this.studentId,
  });

  @override
  _StrengthenStudyPageState createState() => _StrengthenStudyPageState();
}

class _StrengthenStudyPageState extends State<StrengthenStudyPage> {
  VideoPlayerController? _videoController;
  String _videoCoverUrl = '';
  List<dynamic> _videoList = [];
  Map<String, dynamic> _info = {};

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  void dispose() {
    _videoController?.removeListener(_controllerListener);
    _videoController?.dispose();
    super.dispose();
  }

  Future<void> _fetchData() async {
    final res = await ApiService.getListStrengthenVideo({
      'CLASS_ID': widget.classId,
      'STUDENT_ID': widget.studentId,
      'TYPE': 'APP',
    });
    if (res['result'] == 'success') {
      setState(() {
        _info = res['relation'];
        _videoList = res['videoList'];
      });
      final first = _processData(_videoList);
      _loadPlayInfo(first, loadPdf: false);
    }
  }

  Map<String, dynamic> _processData(List<dynamic> data) {
    for (var item in data) {
      if (item['nodes'] != null) {
        final node = (item['nodes'] as List)
            .cast<Map<String, dynamic>>()
            .firstWhere((n) => n['IS_VIDEO'] == 0, orElse: () => {});
        if (node.isNotEmpty) return node;
      } else if (item['IS_VIDEO'] == 0) {
        return item;
      }
    }
    return {};
  }

  Future<void> _loadPlayInfo(
    Map<String, dynamic> row, {
    required bool loadPdf,
  }) async {
    final id = row['VIDEOCOURSEWARE_ID'];
    final isVideo = row['IS_VIDEO'];
    if (isVideo == 0) {
      final res = await ApiService.fnGetVideoPlayInfo(id);
      if (res['result'] == 'success') {
        setState(() => _videoCoverUrl = res['videoBase']?['coverURL'] ?? '');

        _initVideo(
          res['videoList']?[0]['playURL'] ?? '',
          _videoCoverUrl,
        );
      } else {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text(res['msg'] ?? '播放信息获取失败')));
      }
    } else if (loadPdf && row['VIDEOFILES'] != null) {
      _videoController?.pause();
      pushPage(
        RemoteFilePage(
          fileUrl: ApiService.baseImgPath + row['VIDEOFILES'],
          countdownSeconds: 10,
        ),
        context,
      );
    }
  }

  void _initVideo(String url, String cover) {
    _videoController?.removeListener(_controllerListener);
    _videoController?.dispose();
    _videoController = VideoPlayerController.networkUrl(Uri.parse(url))
      ..initialize().then((_) {
        _videoController!
          ..play()
          ..addListener(_controllerListener);
      });
  }

  void _controllerListener() {
    if (mounted) setState(() {});
  }

  String _formatDuration(dynamic secs) {
    final total = (double.tryParse(secs.toString())?.toInt() ?? 0);
    final h = total ~/ 3600;
    final m = (total % 3600) ~/ 60;
    final s = total % 60;
    String two(int n) => n.toString().padLeft(2, '0');
    return "${two(h)}:${two(m)}:${two(s)}";
  }

  /// 开始考试
  Future<void> _startExam(TakeExamType type) async {
    final arguments = {
      'STRENGTHEN_STAGEEXAMPAPER_INPUT_ID': _info['STRENGTHEN_STAGEEXAMPAPER_INPUT_ID'],
      'CLASS_ID': widget.classId,
      'POST_ID': widget.postId,
      'STUDENT_ID': widget.studentId,
    };
    print('--_startExam data---$arguments');

    final data = await ApiService.getStartStrengthenExam(arguments);
    if (data['result'] == 'success') {
      pushPage(TakeExamPage(examInfo: {
        'CLASS_ID':widget.classId,
        'POST_ID': widget.postId,
        'STUDENT_ID': widget.studentId,
        'STRENGTHEN_PAPER_QUESTION_ID': _info['STRENGTHEN_STAGEEXAMPAPER_INPUT_ID'],
        ...data
      }, examType: type), context);

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: '加强学习课件'),
      body: Column(
        children: [
          ListItemFactory.createBuildSimpleSection('加强学习课件'),
          SizedBox(
            width: double.infinity,
            height: 250,
            child: VideoPlayerWidget(
              allowSeek: false,
              controller: _videoController,
              coverUrl:'',
              aspectRatio: _videoController?.value.aspectRatio ?? 16 / 9,
            ),
          ),
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(12),
              itemCount: _videoList.length,
              itemBuilder: (_, i) {
                final item = _videoList[i];
                return GestureDetector(
                  onTap: () => _loadPlayInfo(item, loadPdf: true),
                  child: Container(
                    margin: const EdgeInsets.only(bottom: 10),
                    padding: const EdgeInsets.all(20),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Image.asset(
                              item['IS_VIDEO'] == 0
                                  ? 'assets/study/play.png'
                                  : 'assets/study/copy-one.png',
                              width: 20,
                              height: 20,
                            ),
                            const SizedBox(width: 10),
                            Text(item['COURSEWARENAME'] ?? ''),
                          ],
                        ),
                        if (item['IS_VIDEO'] == 0)
                          Text(_formatDuration(item['VIDEOTIME'])),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(20),
            child: CustomButton(
              text: '效果评估考试',
              backgroundColor: Colors.blue,
              onPressed: () {
                _videoController?.pause();
                _startExam(TakeExamType.strengththen);
              },
            ),

          ),
        ],
      ),
    );
  }
  
}
