import 'package:flutter/material.dart';
import 'package:qhd_prevention/pages/KeyProjects/Danger/danger_manager_page.dart';
import 'package:qhd_prevention/pages/KeyProjects/KeyProject/keyProject_detail.dart';
import 'package:qhd_prevention/pages/KeyProjects/Punishment/punishment_manager_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.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';

class PunishmentListPage extends StatefulWidget {
  final String flow;

  const PunishmentListPage({Key? key, required this.flow}) : super(key: key);

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

class _PunishmentListPageState extends State<PunishmentListPage> {
  // 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 = '';

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _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 data = {'KEYWORDS': searchKeywords, 'PUNISHUser':SessionService.instance.loginUserId,};
      final url =
          '/app/keyProjects/getPUNISHlist?showCount=10&currentPage=$currentPage';
      final response = await ApiService.getKeyProjectList(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 {
    await pushPage(PunishmentManagerPage(OUTSOURCED_ID: item['OUTSOURCED_ID'] ?? ''),context);
    _fetchData();
  }

  Widget _buildListItem(Map<String, dynamic> item) {
    bool showBadge = item['cfcount'] > 0;
    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(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题 + 红点
              Row(
                children: [
                  Expanded(
                    child: Text(
                      "${item['OUTSOURCED_NAME'] ?? ''}",
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  if (showBadge)
                    Container(
                      margin: const EdgeInsets.only(left: 8.0),
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8.0,
                        vertical: 2.0,
                      ),
                      height: 18,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: const Color(0xFFdd514c),
                        borderRadius: BorderRadius.circular(96),
                      ),
                      child: const Text(
                        '1',
                        style: TextStyle(color: Colors.white, fontSize: 10),
                      ),
                    ),
                ],
              ),
              const SizedBox(height: 8),

              // 根据 IS_CORP_TYPE 显示不同的主管/监管信息（对应 vue 逻辑）
              if (item['IS_CORP_TYPE'] == '1') ...[
                Text("主管部门：${item['Q_COMPETENT_DEPT_NAME'] ?? ''}"),
                const SizedBox(height: 6),
                Text("监督部门：${item['DEPARTMENT_NAME'] ?? ''}"),
              ] else if (item['IS_CORP_TYPE'] == '0') ...[
                Text("主管部门：${item['MANAGER_DEPARTMENT_NAME'] ?? ''}"),
                const SizedBox(height: 6),
                Text("监管部门：${item['DEPARTMENT_NAME'] ?? ''}"),
              ],
              const SizedBox(height: 8),

              // 相关方单位负责人 + 电话（两列）
              Row(
                children: [
                  Expanded(
                    child: Text(
                      "相关方单位负责人：${item['UNITS_PIC_NAME'] ?? ''}",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),

              Text(
                "电话：${item['UNITS_PHONE'] ?? ''}",
              ),
              const SizedBox(height: 6),


              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(),
                  CustomButton(
                    onPressed: () { _goToDetail(item);},
                    text: '查看',
                    height: 30,
                    padding: EdgeInsets.symmetric(vertical: 5, horizontal: 15),
                    textStyle: TextStyle(fontSize: 13, color: Colors.white),
                    backgroundColor: Colors.blue,
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  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: widget.flow),

      body: SafeArea(child: 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()),
        ],
      )),
    );
  }
}
