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/customWidget/toast_util.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/KeyProjects/Punishment/PunishmentModalAlert.dart';
import 'package:qhd_prevention/pages/KeyProjects/Punishment/punishment_manager_detail_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';

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

  final String OUTSOURCED_ID;

  @override
  State<PunishmentManagerPage> createState() => _PunishmentManagerPageState();
}

class _PunishmentManagerPageState extends State<PunishmentManagerPage>
    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,
        'HANDLED': index + 1,
      };
      final url =
          '/app/keyprojectcheck/punishlist?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();
    }
  }

  void _punishment(Map item) {
    showPunishDialog(
      context,
      initial: {
        'ISPUNISH': '2',
        'RECTIFICATIONDEPT_NAME': item['UNITS_NAME'],
        'RECTIFICATIONOR_NAME': item['RECTIFICATIONOR_NAME'],
      },
      onSubmit: (form) {
        // 这里接收用户确认后的表单数据
        form['HIDDEN_ID'] = item['HIDDEN_ID'];
        _keyprojectPunishAdd(form);
      },
    );
  }

  Future<void> _keyprojectPunishAdd(Map<String, dynamic> form) async {
    try {
      if (form['ISPUNISH'] == 1) {
        final result = await ApiService.keyprojectpunishAdd(form);
        if (result['result'] == 'success') {
          await ApiService.keyprojectPunishEdit(form, '1');
          _getDataWithIndex(_selectedTab);
        }
      }else{
        await ApiService.keyprojectPunishEdit(form, '2');
        _getDataWithIndex(_selectedTab);
      }

    } catch (e) {
      ToastUtil.showNormal(context, '$e');
    }
  }

  void _goToDetail(Map<String, dynamic> item, String tabCur) async {
    item['TabCur'] = tabCur;
    await pushPage(PunishmentManagerDetailPage(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: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [Text('${item['HIDDENDESCR'] ?? ''}')],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("被处罚单位: ${item['UNITS_NAME'] ?? ''}"),
                  if (item['ISPUNISH'].toString() == '1' &&
                      item['HANDLED'].toString() == '0')
                    Text("被处罚人: ${item['PERSON_NAME'] ?? ''}"),
                ],
              ),
              if (item['ISPUNISH'].toString() == '1')
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [Text("处罚原因: ${item['REASON'] ?? ''}")],
                ),
              if (FormUtils.hasValue(item, 'ISPUNISH'))
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text("下发人: ${item['CREATOR_NAME'] ?? ''}"),
                    Text("是否处罚: ${item['ISPUNISH'] == '2' ? "否" : "是"}"),
                  ],
                ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "处罚处理状态: ${item['ISPUNISH'] == '2'
                        ? "不处罚"
                        : item['HANDLED'] == '1'
                        ? '已完成'
                        : item['ISPUNISH'] == "1"
                        ? "待反馈"
                        : "待处罚"}",
                  ),
                  // Text("整改时间: ${item['RECTIFICATIONTIME'] ?? ''}"),
                ],
              ),

              SizedBox(height: 5),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(),
                  Row(
                    children: [
                      if (!FormUtils.hasValue(item, 'ISPUNISH'))
                        CustomButton(
                          onPressed: () {
                            _punishment(item);
                          },
                          text: '处罚',
                          height: 30,
                          padding: EdgeInsets.symmetric(
                            vertical: 5,
                            horizontal: 15,
                          ),
                          textStyle: TextStyle(
                            fontSize: 13,
                            color: Colors.white,
                          ),
                          backgroundColor: Colors.red,
                        ),
                      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),
                          );
                        },
                      ),
            ),
          ],
        ),
      ),
    );
  }
}
