import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/danner_repain_item.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/KeyProjects/Danger/danger_manager_detail_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';

class DangerManagerPage extends StatefulWidget {
  const DangerManagerPage({super.key, required this.OUTSOURCED_ID});

  final String OUTSOURCED_ID;

  @override
  State<DangerManagerPage> createState() => _DangerManagerPageState();
}

class _DangerManagerPageState extends State<DangerManagerPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  late int _selectedTab = 0;
  late List listDates = [];
  late int totalPage = 0;
  int currentPage = 1;
  final ScrollController _scrollController = ScrollController();

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController.addListener(_onScroll);

    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        setState(() {
          _selectedTab = _tabController.index;
          currentPage = 1;
        });
        print('切换到标签：${_tabController.index}');

        _getDataWithIndex(_tabController.index);
      }
    });
    _getDataWithIndex(_selectedTab);

  }
  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent) {
      if (currentPage < totalPage) {
        currentPage++;
        _getDataWithIndex(_selectedTab);
      }
    }
  }
  Future<void> _getDataWithIndex(int index) async {
    LoadingDialogHelper.show();
    try {
      final data = {
        'KEYWORDS': '',
        'OUTSOURCED_ID': widget.OUTSOURCED_ID,
        'CREATOR': SessionService.instance.loginUserId,
        'ISCHECK': index + 1,
      };
      final url =
          '/app/keyprojectcheck/listHidden?showCount=10&currentPage=$currentPage';
      final response = await ApiService.getKeyprojectDangerList(url, data);

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

  String _getState(String state) {
    final info = {'1': "未整改",
      '2': "已整改",
      '4': "已验收",};
    return info[state] as String;
  }

  void _goToDetail(Map<String, dynamic> item, String tabCur) async {
    item['TabCur'] = tabCur;
    await pushPage(DangerManagerDetailPage(info: item), context);
    _getDataWithIndex(_selectedTab);
  }

  Widget _itemCell(Map<String, dynamic> item) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 12),
      child: GestureDetector(
        onTap: () {
          _goToDetail(item, '2');
        },
        child: Container(
          padding: EdgeInsets.only(top: 12, left: 12, right: 12),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(5),
            color: Colors.white,
          ),
          child: Column(
            children: [
              ListItemFactory.headerTitle(item['OUTSOURCED_NAME'] ?? ''),
              const SizedBox(height: 5,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("隐患来源: ${item['SOURCE'] ?? ''}"),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("隐患描述: ${item['HIDDENDESCR'] ?? ''}"),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("隐患发现人: ${item['CREATOR_NAME'] ?? item['CREATOR_NAMES']}"),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("隐患发现时间: ${item['CREATTIME'] ?? ''}"),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("隐患整改人: ${item['RECTIFICATIONOR_NAME'] ?? ''}"),
                  Text("整改时间: ${item['RECTIFICATIONTIME'] ?? ''}"),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("隐患验收人: ${item['CREATOR_NAME'] ?? ''}"),
                  Text("验收时间: ${item['CHECKTIME'] ?? ''}"),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("隐患状态: ${_getState(item['STATE'].toString())}"),
                  Text("是否处罚: ${FormUtils.hasValue(item, 'ISPUNISH') ? (item['ISPUNISH'] == '1' ? '是' : '否'):''}"),
                ],
              ),
              SizedBox(height: 5,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(),
                  Row(
                    children: [
                      if (item['CREATOR'] == SessionService.instance.loginUserId && _selectedTab == 0)
                        CustomButton(
                          onPressed: () { _goToDetail(item, '1');},
                          text: '验收',
                          height: 30,
                          padding: EdgeInsets.symmetric(vertical: 5, horizontal: 15),
                          textStyle: TextStyle(fontSize: 13, color: Colors.white),
                          backgroundColor: Colors.blue,
                        ),
                      CustomButton(
                        onPressed: () { _goToDetail(item, '2');},
                        text: '查看',
                        height: 30,
                        padding: EdgeInsets.symmetric(vertical: 5, horizontal: 15),
                        textStyle: TextStyle(fontSize: 13, color: Colors.white),
                        backgroundColor: Colors.blue,
                      ),
                    ],
                  )
                ],
              ),
              SizedBox(height: 10,),
              const Divider(height: 1,)
            ],
          ),
        ),
      )
    );
  }

  void _handleItemTap(Map item, int index) {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: '隐患管理'),
      body: SafeArea(
        child: Column(
          children: [
            Container(
              color: Colors.white,
              child: TabBar(
                controller: _tabController,
                labelStyle: TextStyle(fontSize: 16),
                indicator: UnderlineTabIndicator(
                  borderSide: BorderSide(width: 3.0, color: Colors.blue),
                  insets: EdgeInsets.symmetric(horizontal: 100.0),
                ),
                labelColor: Colors.blue,
                unselectedLabelColor: Colors.grey,
                tabs: const [Tab(text: '待验收隐患'), Tab(text: '已验收隐患')],
              ),
            ),
            Expanded(
              child:
                  listDates.isEmpty
                      ? NoDataWidget.show()
                      : ListView.separated(
                        padding: EdgeInsets.only(top: 15),
                        itemCount: listDates.length,
                        controller: _scrollController,
                        separatorBuilder: (_, __) => const SizedBox(),
                        itemBuilder: (context, index) {
                          final item = listDates[index];
                          return GestureDetector(
                            onTap: () => _handleItemTap(item, index),
                            child: _itemCell(item),
                          );
                        },
                      ),
            ),
          ],
        ),
      ),
    );
  }
}
