import 'package:flutter/material.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/h_colors.dart';
import '../../../http/ApiService.dart';
import '../../../tools/tools.dart';

class StudyScorePage extends StatefulWidget {
  const StudyScorePage({Key? key}) : super(key: key);

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

class _StudyScorePageState extends State<StudyScorePage> {
  // 接口数据
  int joinNum = 0, passNum = 0, noPassNum = 0;
  List<dynamic> list = [];

  // 分页控制
  int showCount = 10;
  int currentPage = 1;
  int totalPage = 1;
  bool loading = false;

  final ScrollController _scrollController = ScrollController();

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

    // 滚动到底自动加载
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
              _scrollController.position.maxScrollExtent - 50 &&
          !loading &&
          currentPage < totalPage) {
        currentPage++;
        _fetchData();
      }
    });
  }

  Future<void> _fetchData() async {
    setState(() => loading = true);
    final res = await ApiService.pageTaskScoreByUser(showCount, currentPage);
    setState(() => loading = false);
    if (res != null && res['result'] == 'success') {
      final varList = res['varList'];
      if (varList is List) {
        list.addAll(varList);
      }

      // 强壮类型转换
      joinNum = _toInt(res['JOINNUM'], defaultValue: joinNum);
      passNum = _toInt(res['PASSNUM'], defaultValue: passNum);
      noPassNum = _toInt(res['NOPASSNUM'], defaultValue: noPassNum);
      totalPage = _toInt(res['totalPage'], defaultValue: totalPage);
    }
  }

  int _toInt(dynamic value, {required int defaultValue}) {
    if (value is int) return value;
    if (value is String) {
      return int.tryParse(value) ?? defaultValue;
    }
    return defaultValue;
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Widget _buildStatItem(String label, int value) {
    return Expanded(
      child: Column(
        children: [
          Text(
            '$value',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w900,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 4),
          Text(label, style: TextStyle(fontSize: 15, color: Colors.white)),
        ],
      ),
    );
  }

  Widget _buildListItem(dynamic item) {
    // 根据 STAGEEXAMSTATE 渲染不同颜色
    Color stateColor;
    String stateText;
    switch (item['STAGEEXAMSTATE']) {
      case '1':
        stateColor = Color(0xff3377ff);
        stateText = '待考试';
        break;
      case '2':
        stateColor = Color(0xff999999);
        stateText = '考试未通过';
        break;
      case '3':
        stateColor = Color(0xff33c76d);
        stateText = '考试通过';
        break;
      default:
        stateColor = Color(0xff999999);
        stateText = '未参加';
    }

    // 解析成绩
    int score = _toInt(item['STAGEEXAMSCORE'], defaultValue: -1);
    String scoreText = score >= 0 ? '$score' : '无';

    return Card(
      color: Colors.white,
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () {
          final state = item['STAGEEXAMSTATE'];
          if (state == '2' || state == '3') {
            Navigator.pushNamed(context, '/exam_details', arguments: item);
          }
        },
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '考试时长：${item['ANSWERSHEETTIME']} 分钟',
                    style: TextStyle(color: Colors.grey[700]),
                  ),
                  Text(stateText, style: TextStyle(color: stateColor)),
                ],
              ),
              const Divider(height: 20),
              _infoRow('培训任务名称', item['CLASS_NAME'] ?? ''),
              _infoRow('试卷名称', item['EXAMNAME'] ?? ''),
              _infoRow('岗位类型', item['POSTTYPE_NAME'] ?? ''),
              _infoRow('考试成绩', scoreText),
            ],
          ),
        ),
      ),
    );
  }

  Widget _infoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: TextStyle(color: Colors.grey[600])),
          Flexible(
            child: Text(
              value,
              style: TextStyle(
                color: Colors.black87,
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.right,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: '成绩查询'),
      backgroundColor: h_backGroundColor(),
      body: Column(
        children: [

          Padding(
            padding: EdgeInsets.symmetric(vertical: 15, horizontal: 12),
            child: Stack(
              children: [
                SizedBox(
                  width: 1000,
                  height: 130,
                  child: Image.asset(
                    'assets/study/bgimg1.png',
                    fit: BoxFit.fill,
                  ),
                ),
                Column(
                  children: [
                    const SizedBox(height: 10),
                    const Text(
                      '我的成绩',
                      style: TextStyle(
                        fontSize: 20,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 10),
                      child: const Divider(height: 20, color: Colors.white),
                    ),
                    Row(
                      children: [
                        _buildStatItem('参加考试次数', joinNum),
                        _buildStatItem('合格次数', passNum),
                        _buildStatItem('不合格次数', noPassNum),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),

          // 列表
          Expanded(
            child:
                list.isEmpty
                    ? NoDataWidget.show()
                    : ListView.builder(
                      controller: _scrollController,
                      itemCount: list.length + 1,
                      itemBuilder: (context, i) {
                        if (i < list.length) return _buildListItem(list[i]);
                        // 底部加载更多指示器
                        return Padding(
                          padding: EdgeInsets.symmetric(vertical: 16),
                          child: Center(
                            child:
                                loading
                                    ? CircularProgressIndicator()
                                    : Text(
                                      currentPage >= totalPage ? '没有更多了' : '',
                                    ),
                          ),
                        );
                      },
                    ),
          ),
        ],
      ),
    );
  }
}
