import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/sxkj_work/tzgl_zytz_work_detail/sxkj_tzgl_detail.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:qhd_prevention/customWidget/bottom_picker.dart';
import 'package:qhd_prevention/customWidget/search_bar_widget.dart';
import 'package:qhd_prevention/http/ApiService.dart';

class SxkjTzglListPage extends StatefulWidget {

  const SxkjTzglListPage({
    Key? key,
  }) : super(key: key);

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

class _SxkjTzglListPageState extends State<SxkjTzglListPage> {
  // Data and state variables
  List<dynamic> list = [];
  int currentPage = 1;
  int rows = 10;
  int totalPage = 1;
  bool isLoading = false;
  final TextEditingController _searchController = TextEditingController();

  List<Map<String, dynamic>> stepList = [];
  int sindex = 0;
  String searchKeywords = '';

  List<Map<String, dynamic>> flowList = [];
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _fetchSteps();
    _fetchData();
    _scrollController.addListener(_onScroll);
  }

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

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent &&
        !isLoading) {
      if (currentPage < totalPage) {
        currentPage++;
        _fetchData();
      }
    }
  }

  Future<void> _fetchSteps() async {
    try {
      final response = await ApiService.searchGetTaskSetps(1);
      setState(() {
        stepList = [
          {'STEP_NAME': '全部', 'STEP_ID': ''},
          ...response['list'] ?? [],
        ];
      });
    } catch (e) {
      print('Error fetching steps: $e');
    }
  }

  Future<void> _fetchData() async {
    if (isLoading) return;
    setState(() => isLoading = true);

    try {
      final data = {
        'tm':DateTime.now().millisecondsSinceEpoch.toString(),
        'KEYWORDS': searchKeywords,
      };
      final url = '/app/limitspace/list?showCount=-1&currentPage=$currentPage';
      final response = await ApiService.specialCheckListWorkCount(data, url);

      setState(() {
        if (currentPage == 1) {
          list = response['varList'];
        } else {
          list.addAll(response['varList']);
        }
        Map<String, dynamic> page = response['page'];
        totalPage = page['totalPage'] ?? 1;
        isLoading = false;
      });
    } catch (e) {
      print('Error fetching data: $e');
      setState(() => isLoading = false);
    }
  }

  void _search() {
    searchKeywords = _searchController.text.trim();
    currentPage = 1;
    list.clear();
    _fetchData();
  }

  void _goToDetail(Map<String, dynamic> item) async {
    pushPage(SxkjTzglDetail(LIMITSPACE_ID : item['LIMITSPACE_ID'] ?? ''), context);
  }

 

  Widget _buildListItem(Map<String, dynamic> item) {
    return Card(
      color: Colors.white,
      margin: const EdgeInsets.all(8.0),
      child: InkWell(
        onTap: () => _goToDetail(item),
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Column(
            spacing: 8,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '${item['NUMBER']} ${item['NAME']}',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox()
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("受限空间类型: ${item['LIMITSPACETYPENAME'] ?? ''}"),
                  Text("风险等级: ${item['RISKGRADENAME'] ?? ''}"),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("责任人 : ${item['PRINCIPALNAME'] ?? ''}"),
                  Text("填报日期: ${item['COMPILETIME'] ?? ''}"),
                ],
              ),

            ],
          ),
        ),
      ),
    );
  }

  // 显示底部选择器
  Future<void> _showStepPicker() async {
    if (stepList.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('正在加载步骤数据，请稍后...')));
      await _fetchSteps();
      if (stepList.isEmpty) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('无法加载步骤数据')));
        return;
      }
    }

    // 创建选项列表
    final options = stepList.map((e) => e['STEP_NAME'] as String).toList();

    // 显示底部选择器
    final choice = await BottomPicker.show<String>(
      context,
      items: options,
      itemBuilder: (item) => Text(item, textAlign: TextAlign.center),
      initialIndex: sindex,
    );

    if (choice != null) {
      // 找到选择的索引
      final newIndex = options.indexOf(choice);
      if (newIndex != -1) {
        setState(() {
          sindex = newIndex;
        });
        _search();
      }
    }
  }

  Widget _buildListContent() {
    if (isLoading && list.isEmpty) {
      // 初始加载时显示居中的加载指示器
      return Center(child: CircularProgressIndicator());
    } else if (list.isEmpty) {
      // 没有数据
      return NoDataWidget.show();
    } else {
      // 有数据或加载更多
      return ListView.builder(
        padding: EdgeInsets.zero,

        controller: _scrollController,
        itemCount: list.length + (isLoading ? 1 : 0),
        itemBuilder: (context, index) {
          if (index >= list.length) {
            // 加载更多时在列表底部显示加载指示器
            return Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: Center(child: CircularProgressIndicator()),
            );
          }
          return _buildListItem(list[index]);
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      key: _scaffoldKey,
      appBar: MyAppbar(
        title: '受限空间台账',

      ),

      body: Column(
        children: [
          // Filter bar
          Container(
            color: Colors.white,
            padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 8),
            child: Row(
              children: [

                Expanded(
                  flex: 2,
                  child: SearchBarWidget(
                    showResetButton: false,
                    hintText: "请输入关键字",
                    // isClickableOnly: true,
                    onSearch: (text) {
                      _search();
                    },
                    controller: _searchController,
                  ),
                ),
              ],
            ),
          ),
          const Divider(height: 1),
          // List
          Expanded(child: _buildListContent()),
        ],
      ),
    );
  }
}
