import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:qhd_prevention/pages/home/SafeCheck/DangeCheck/safeCheck_assignment_detail_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/http/ApiService.dart';

class SafecheckAssignmentList extends StatefulWidget {
  final String INSPECTION_ID;

  const SafecheckAssignmentList({Key? key, required this.INSPECTION_ID})
      : super(key: key);

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

class _SafecheckAssignmentListState extends State<SafecheckAssignmentList> {
  // Data and state variables
  List<dynamic> list = [];
  int currentPage = 1;
  int rows = 10;
  int totalPage = 1;
  bool isLoading = false;
  final List<Map<String, String>> hiddenStatusList = [
    {'ID': '',   'NAME': '请选择'},
    {'ID': '1',  'NAME': '待整改'},
    {'ID': '2',  'NAME': '待验收'},
    {'ID': '3',  'NAME': '已整改'},
    {'ID': '4',  'NAME': '已验收'},
    {'ID': '5',  'NAME': '忽略隐患'},
    {'ID': '6',  'NAME': '重大隐患'},
    {'ID': '7',  'NAME': '待处理的特殊申请隐患'},
    {'ID': '8',  'NAME': '已处理的特殊隐患'},
    {'ID': '10', 'NAME': '验收打回'},
    {'ID': '11', 'NAME': '分公司安委会办公室副主任核定'},
    {'ID': '12', 'NAME': '分公司安委会办公室副主任核定'},
    {'ID': '13', 'NAME': '港股分公司安委会办公室副主任核定、重大隐患待整改'},
    {'ID': '13', 'NAME': '重大隐患待验收'},
    {'ID': '15', 'NAME': '重大隐患已归档'},
    {'ID': '16', 'NAME': '确认打回'},
    {'ID': '100','NAME': '安全检查暂存的隐患'},
    {'ID': '100','NAME': '检查已归档，待指派'},
    {'ID': '101','NAME': '待指派整改人'},
    {'ID': '-1', 'NAME': '已过期'},
    {'ID': '-2', 'NAME': '待确认'},
  ];

  List<Map<String, dynamic>> flowList = [];
  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();
      }
    }
  }
  String? translateHidden(String id) {
    final match = hiddenStatusList.firstWhere(
          (item) => item['ID'] == id,
      orElse: () => {},
    );
    return match['NAME']; // 如果 orElse 返回 {}，这里会是 null（安全）
  }
  Future<void> _fetchData() async {
    if (isLoading) return;
    setState(() => isLoading = true);

    try {

      final response = await ApiService.getSafeCheckDangerList(widget.INSPECTION_ID);

      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 _goToDetail(Map<String, dynamic> item) async {
    await pushPage(SafecheckAssignmentDetailPage(HIDDEN_STATUS: '0', INSPECTION_ID: item['INSPECTION_ID'], HIDDEN_ID:item['HIDDEN_ID']), context);
   _fetchData();

  }
  // 指派
  void _goToAssign(Map<String, dynamic> item) async {

    await pushPage(SafecheckAssignmentDetailPage(HIDDEN_STATUS: '-2', INSPECTION_ID: item['INSPECTION_ID'], HIDDEN_ID:item['HIDDEN_ID']), context);
    _fetchData();


  }
  // 验收
  void _goAccept(Map<String, dynamic> item) async {

    // await pushPage(SafecheckSignDetail(INSPECTION_ID: item['INSPECTION_ID'] ?? '', INSPECTION_INSPECTOR_ID: item['INSPECTION_INSPECTOR_ID'] ?? '',isEdit: false), context);
    _fetchData();


  }

  Widget _buildFlowStepItem({
    required Map<String, dynamic> item,
    required bool isFirst,
    required bool isLast,
  }) {
    bool status = item['active'] == item['order'];
    // 依据状态设色
    final Color dotColor = status ? Colors.blue :Colors.grey;
    final Color textColor = status ? Colors.blue :Colors.black54;

    return ListTile(
      visualDensity: VisualDensity(vertical: -4),

      contentPadding: const EdgeInsets.symmetric(horizontal: 16),
      leading: Container(
        width: 24,
        alignment: Alignment.center,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            // 上方线段或占位
            isFirst
                ? SizedBox(height: 6 + 5)
                : Expanded(child: Container(width: 1, color: Colors.grey[300])),
            // 圆点
            CircleAvatar(radius: 6, backgroundColor: dotColor),
            // 下方线段或占位
            isLast
                ? SizedBox(height: 6 + 5)
                : Expanded(child: Container(width: 1, color: Colors.grey[300])),
          ],
        ),
      ),
      title: Text(
        item['title'] ?? '',
        style: TextStyle(color: textColor, fontSize: 15),
      ),
      subtitle: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (item['desc'] != null)
            Text(
              item['desc'],
              style: TextStyle(color: textColor, fontSize: 13),
            ),
        ],
      ),
    );
  }


  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(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    item['HIDDENDESCR'] ?? '',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("隐患状态: ${translateHidden(item['HIDDEN_STATUS'] ?? '')}"),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("隐患描述: ${item['HIDDENDESCR'] ?? ''}", maxLines: 5, overflow: TextOverflow.ellipsis),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(),
                  Row(
                    spacing: 5,
                    children: [
                      CustomButton(
                        text: '查看',
                        height: 32,
                        padding: EdgeInsets.symmetric(horizontal: 12),
                        margin: EdgeInsets.only(left: 0),
                        backgroundColor: Colors.green,
                        onPressed: () => _goToDetail(item),
                      ),
                      if (item['INSPECTED_SITEUSER_ID'] == SessionService.instance.loginUserId && item['HIDDEN_STATUS'] == '101')
                        CustomButton(
                          text: '指派',
                          height: 32,
                          padding: EdgeInsets.symmetric(horizontal: 12),
                          margin: EdgeInsets.only(left: 0),
                          backgroundColor: Colors.blue,
                          onPressed: () => _goToAssign(item),
                        ),
                      if (item['CREATOR'] == SessionService.instance.loginUserId &&
                          (item['HIDDEN_STATUS'] == '4' || item['HIDDEN_STATUS'] == '8') &&
                          (item['HIDDEN_STATUS'] == '4' || item['HIDDEN_STATUS'] == '8') &&
                      FormUtils.hasValue(item, 'FINAL_CHECK'))
                        CustomButton(
                          text: '验收',
                          height: 32,
                          padding: EdgeInsets.symmetric(horizontal: 12),
                          margin: EdgeInsets.only(left: 0),
                          backgroundColor: Colors.blue,
                          onPressed: () => _goAccept(item),
                        ),
                    ],
                  )

                ],
              ),

            ],
          ),
        ),
      ),
    );
  }

  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) {
    final int lastDoneIndex = flowList.lastIndexWhere((e) => e['STATUS'] == 1);

    return Scaffold(
      key: _scaffoldKey,
      appBar: MyAppbar(
        title: '发现问题',
        actions: [],
      ),
      endDrawer: Drawer(
        child: SafeArea(
          child:
          flowList.isEmpty
              ? Center(child: Text('暂无流程图数据'))
              : ListView.builder(
            padding: const EdgeInsets.symmetric(vertical: 16),
            itemCount: flowList.length + 1, // +1 用来放标题
            itemBuilder: (context, i) {
              if (i == 0) {
                return Padding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 8,
                  ),
                  child: Text(
                    '查看流程图',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                );
              }
              final idx = i - 1;
              final item = flowList[idx];
              final bool isFirst = idx == 0;
              final bool isLast = idx == flowList.length - 1;

              return _buildFlowStepItem(
                item: item,
                isFirst: isFirst,
                isLast: isLast,
              );
            },
          ),
        ),
      ),

      body: SafeArea(child: Expanded(child: _buildListContent()),),
    );
  }
}
