import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/home/SafetyCommitment/company_safety_commitment_apply.dart';
import 'package:qhd_prevention/pages/home/SafetyCommitment/team_safety_commitment_apply.dart';
import 'package:qhd_prevention/pages/home/SafetyCommitment/team_safety_commitment_detail.dart';
import 'package:qhd_prevention/pages/home/SafetyCommitment/work_shop_safety_commitment_apply.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/dh_work_detai/hotwork_apply_detail.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/aqcs_work_detail/hotwork_safe_func_sure.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/aqgl_work_detail/hotwork_aqgl_detail.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/aqjd_work_detail/hotwork_aqjd_detail.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/dbbz_work_detail/hotwork_dbbz_detail.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/dhsp_work_detail/hotwork_dhsp_detail.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/jhr_work_detail/hotwork_jhr_detail.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/jszy_work_detail/hotwork_jszy_detail.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/kszy_work_detail/hotwork_kszy_detail.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/szaq_work_detail/hotwork_set_safe_detail.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/szdw_work_detail/hotwork_szdw_detail.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/ysgd_work_detail/hotwork_ysgd_detail.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/zyfz_work_detail/hotwork_zyfz_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/custom_button.dart';
import 'package:qhd_prevention/customWidget/search_bar_widget.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_Wrok/dh_work/qtfx_work_detail/hotwork_gas_list.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_Wrok/dh_work/jsjd_work_detail/hotwork_jsjd_detail.dart';

import 'commitment_workshop_detail_page.dart';
import 'company_safety_commitment_detail.dart';

class SafetyCommitmentDhList extends StatefulWidget {
  const SafetyCommitmentDhList({Key? key, required this.type, }) : super(key: key);

  final int type;
  @override
  _SafetyCommitmentDhListState createState() => _SafetyCommitmentDhListState();
}

class _SafetyCommitmentDhListState extends State<SafetyCommitmentDhList> {
  // 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 = '';
  String id="";
  String title ="";
  String itemTitle ="";
  String itemTitleName="";

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

  final ScrollController _scrollController = ScrollController();

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

    id=SessionService.instance.loginUser?["DEPARTMENT_ID"]??"";

    switch(widget.type){
      case 1:
        title="公司安全承诺";
        itemTitle="公开安全承诺报告";
        itemTitleName="CORP_NAME";
        break;
      case 2:
        title="风险研判报告及安全承诺公告";
        itemTitle="风险研判报告及安全承诺公告";
        itemTitleName="DEPARTMENT_NAME";
        break;
      case 3:
        title="班组风险研判及安全承诺";
        itemTitle="风险研判报告及安全承诺公告";
        itemTitleName="DEPARTMENTNAME";
        break;
    }

    _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> _fetchData() async {
    if (isLoading) return;
    setState(() => isLoading = true);
    try {
      final Map<String, dynamic> response;
      if(widget.type==1) {
        response = await ApiService.getCompanySafetyCommitmentList(currentPage, searchKeywords, id);
      }else if(widget.type==2){
        response = await ApiService.getWorkshopSafetyCommitmentList(currentPage, searchKeywords,id);
      }else {
        response = await ApiService.getTeamSafetyCommitmentList(currentPage, searchKeywords,id);
      }

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

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


  /// 申请
  Future<void> _handleApply() async {
    // 处理申请按钮点击逻辑

    // setState(() async {
    //   if(widget.type==1) {
    //     await pushPage(CompanySafetyCommitmentApply(), context);
    //   }else if(widget.type==2){
    //     await pushPage(WorkShopSafetyCommitmentApply(), context);
    //   }else {
    //     await pushPage(TeamSafetyCommitmentApply(), context);
    //   }
    //
    //   searchKeywords = "";
    //   currentPage = 1;
    //   list.clear();
    //   _fetchData();
    // });

    try {
      final Map<String, dynamic> response;
      if(widget.type==1) {
        response = await ApiService.getCompanySafetyCommitmentPermission( id);
      }else if(widget.type==2){
        response = await ApiService.getWorkshopSafetyCommitmentPermission(id);
      }else {
        response = await ApiService.getTeamSafetyCommitmentPermission(id);
      }

      if (response['result'] == 'success') {

            if(widget.type==1) {
              await pushPage(CompanySafetyCommitmentApply(), context);
            }else if(widget.type==2){
              await pushPage(WorkShopSafetyCommitmentApply(), context);
            }else {
              await pushPage(TeamSafetyCommitmentApply(), context);
            }

      setState(()  {
          searchKeywords = "";
          currentPage = 1;
          list.clear();
          _fetchData();
        });
      }else{
        ToastUtil.showNormal(context, response['msg']);
      }
    } catch (e) {
      ToastUtil.showNormal(context,'$e');
      print('Error fetching data: $e');
    }


  }



  void _goToDetail(Map<String, dynamic> item)  {
    if(widget.type==1) {
      pushPage(CompanySafetyCommitmentDetail( commitmentId:item['COMMITMENTCOMPANY_ID'],), context);
    }else if(widget.type==2){
      pushPage(CommitmentWorkshopDetailPage( commitmentWorkshopId:item['COMMITMENTWORKSHOP_ID'],), context);
    }else {
      pushPage(TeamSafetyCommitmentDetail( commitmentWorkshopId:item['COMMITMENTTEAM_ID'],), context);
    }

  }



  Widget _buildListItem(Map<String, dynamic> item) {
    return InkWell(
        onTap: () => _goToDetail(item),
        child: Container(
          padding: const EdgeInsets.all(20),
          margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10),
            boxShadow: [
              BoxShadow(
                color: Colors.black12,
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '$itemTitle-${item[itemTitleName]}',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('承诺时间: ${item['SIGN_TIME']??""}'),
                  Text('承诺人: ${item['SIGN_USER_NAME']??""}'),
                ],
              ),
            ],
          ),
        ),

    );
  }





  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: title,
        actions: [
            TextButton(
              onPressed: _handleApply,
              child: const Text(
                '承诺',
                style: TextStyle(color: Colors.white, fontSize: 17),
              ),
            ),
        ],
      ),

      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()),
        ],
      ),
    );
  }
}
