import 'dart:math';

import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/app/Danger_paicha/checking_information_one_page.dart';

import 'package:qhd_prevention/pages/home/scan_page.dart';
import 'package:qhd_prevention/pages/app/Danger_paicha/danger_project_page.dart';
import 'package:qhd_prevention/pages/http/ApiService.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/h_colors.dart';
import 'package:qhd_prevention/tools/tools.dart';

class RiskListPage extends StatefulWidget {
  const RiskListPage(this.type, this.id, {super.key});

  final int type;
  final String id;


  @override
  State<RiskListPage> createState() => _riskListPageState();
}

class _riskListPageState extends State<RiskListPage> {

  // final List<Model> _dataList = [
  //   Model("青椒皮蛋鸡尾酒哦普佛椒皮鸡尾酒哦普佛椒皮鸡尾鸡尾酒哦普佛椒皮鸡尾鸡尾酒哦普佛椒皮鸡尾鸡尾酒哦普佛椒皮鸡尾鸡尾酒哦普佛"),
  //   Model("dqfiqfjpoqo阿迪王期待期待五千多强大f"),
  //   Model("dqfiqfjpoqof"),
  //   Model("dqfiqfjpoqof")
  // ];

  List<dynamic> listDates = [];
  Map<String, dynamic> checkMap = {};
  String checkrecordId="";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _getData();
  }

  void _getData(){
    listDates.clear();
    checkMap.clear();
    switch(widget.type  ){
      case 1://隐患排查
        _getRiskPointsList();
        break;
      case 2://标准排查
        _getInspectionItemList();
        break;

    }
  }


  Future<void> _getRiskPointsList() async {
    try {

      final result = await ApiService.getRiskPointsList(widget.id);
      if (result['result'] == 'success') {
        final List<dynamic> newList = result['varList'] ?? [];
        setState(() {
          listDates.addAll(newList);

          try{
            checkrecordId=result['CHECKRECORD_ID'];
            checkMap.addAll(result['checkmap'] ?? []);
            if(checkMap.isNotEmpty){
              for(int i=0;i<listDates.length;i++){
                try{
                  (listDates[i] as Map<String, dynamic>)["LISTMANAGER_ID"] =widget.id;
                  if(checkMap[listDates[i]["IDENTIFICATIONPARTS_ID"]]!=null) {
                    String num = checkMap[listDates[i]["IDENTIFICATIONPARTS_ID"]].toString();
                    (listDates[i] as Map<String, dynamic>)["checkmap"] = num;
                  }else{
                    (listDates[i] as Map<String, dynamic>)["checkmap"] ="";
                  }
                }catch(e){
                  (listDates[i] as Map<String, dynamic>)["LISTMANAGER_ID"] =widget.id;
                  print('加载数据失败：$e');
                  (listDates[i] as Map<String, dynamic>)["checkmap"] ="";
                }

              }
            }
          }catch(e){
            for(int i=0;i<listDates.length;i++) {
              (listDates[i] as Map<String, dynamic>)["LISTMANAGER_ID"] =widget.id;
              (listDates[i] as Map<String, dynamic>)["checkmap"] = "";
            }
            print('没有这些数据：$e');

          }

        });

      }else{
        ToastUtil.showNormal(context, "加载数据失败");
        // _showMessage('加载数据失败');
      }
    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载数据失败：$e');
    }
  }

  Future<void> _getInspectionItemList() async {
    try {

      final result = await ApiService.getInspectionItemList(widget.id);
      if (result['result'] == 'success') {
        final List<dynamic> newList = result['varList'] ?? [];
        setState(() {

          listDates.addAll(newList);

          try{
            checkrecordId=result['CHECKRECORD_ID'];
            checkMap.addAll(result['checkmap'] ?? []);
            if(checkMap.isNotEmpty){
              for(int i=0;i<listDates.length;i++){
                try{
                  // String num= checkMap[listDates[i]["CHECK_ITEM"]].toString();
                  // (listDates[i] as Map<String, dynamic>)["checkmap"] =num;
                  if(checkMap[listDates[i]["CHECK_ITEM"]]!=null) {
                    String num = checkMap[listDates[i]["CHECK_ITEM"]].toString();
                    (listDates[i] as Map<String, dynamic>)["checkmap"] = num;
                  }else{
                    (listDates[i] as Map<String, dynamic>)["checkmap"] ="";
                  }

                }catch(e){
                  print('加载数据失败：$e');
                  (listDates[i] as Map<String, dynamic>)["checkmap"] ="";
                }

              }
            }
          }catch(e){
            for(int i=0;i<listDates.length;i++) {
              (listDates[i] as Map<String, dynamic>)["checkmap"] = "";
            }
            print('没有这些数据：$e');

          }


        });

      }else{
        ToastUtil.showNormal(context, "加载数据失败");
        // _showMessage('加载数据失败');
      }
    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载数据失败：$e');
    }
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: h_backGroundColor(),
      appBar: MyAppbar(
        title: widget.type==1?"风险点（单元）列表":"检查项目列表",
        // actions: [
        //   TextButton(
        //     onPressed: () {
        //       pushPage(ScanPage(), context);
        //     },
        //     child: Text(
        //       "扫描",
        //       style: TextStyle(color: Colors.white, fontSize: 16),
        //     ),
        //   ),
        // ],
      ),
      body: SafeArea(
          child: Column(
            children: [
              Expanded(child:  listDates.isEmpty
                  ? NoDataWidget.show()
                  : ListView.separated(
                itemCount: listDates.length,
                separatorBuilder: (_, __) => const SizedBox(),
                itemBuilder: (context, index) {
                  final item = listDates[index];
                  return GestureDetector(
                    onTap: () => _selectItem(item),
                    child: _itemCell(item),
                  );
                },
              )),
              Container(
                decoration: BoxDecoration(
                  color: Colors.green,
                  borderRadius: BorderRadius.circular(5)
                ),
                width: screenWidth(context) - 30,
                height: 50,
                child: TextButton(
                    onPressed: () => _nextHandle(), child: Text("下一步", style: TextStyle(color: Colors.white),)),
              )

            ],
          )),
    );
  }

  Widget _itemCell(final item) {

    return Padding(padding: EdgeInsets.symmetric(vertical: 7, horizontal: 15),
      child: GestureDetector(
        onTap: () => _selectItem(item),
        child: Container(
          height: 100,
          padding: EdgeInsets.symmetric(horizontal: 10),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(5)
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Image.asset(item["checkmap"].toString().isEmpty?"assets/images/zt-ing.png":"assets/images/zt-over.png", width: 50, height: 50,),
              const SizedBox(width: 10), // 添加间距
              Column(
                children: [
                  Expanded(  // 修复3: 文本过长时自动换行
                    child:
                    Center(child:
                    Text(
                      _getTitle(item),
                      // item.title,
                      style: const TextStyle(fontSize: 13),
                      maxLines: 2, // 限制两行
                      overflow: TextOverflow.ellipsis,
                    ),
                    ),

                  ),
                ],
              )

            ],
          ),
        ),
      ),
    );
  }

  String _getTitle(final item) {
    if(widget.type==1  ){
      return "${item["DEPT_NAME"]}--${item["RISKUNITNAME"]}--${item["PARTSNAME"]}${_dianZiString(item)}";
    }else{
      return item["DICTIONARY_NAMES"];
    }
  }



  Future<void> _selectItem(final item) async {
    switch(widget.type  ){
      case 1://隐患排查
      if(item["ELECTRONIC_FENCE_ID"]!=null){
        _isInElectronicFence(item);
      }else{

        final result = await Navigator.push(
          context,
          MaterialPageRoute(builder: (_) => DangerProjectPage(item,widget.type,checkrecordId )),
        );
        _getData();
      }
        break;
      case 2://标准排查
        // pushPage(DangerProjectPage(item), context);
        final result = await Navigator.push(
          context,
          MaterialPageRoute(builder: (_) => DangerProjectPage(item,widget.type,checkrecordId )),
        );
        _getData();
        break;

    }

  }

  Future<void> _isInElectronicFence(final item ) async {
    try {

      final result = await ApiService.isInElectronicFence(item["ELECTRONIC_FENCE_ID"]);
      if (result['result'] == 'success') {

        setState(() {
          // listDates.addAll(newList);
        });

      }else{
        ToastUtil.showNormal(context, result['msg']);
        // _showMessage('加载数据失败');
      }
    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载数据失败：$e');

    }
  }

  String _dianZiString(item) {
    try{
      if(item["ELECTRONIC_FENCE_NAME"]==null){
        return "";
      }else{
        return "\n所属电子围栏：${item["ELECTRONIC_FENCE_NAME"]}";
      }
    }catch(e){
      return "";
    }
  }

  void _nextHandle() {
    bool canGo=true;
    for(int i=0;i<listDates.length;i++){
      try{
        String num= listDates[i]["checkmap"];
        if(num.isEmpty){
          canGo=false;
        }
      }catch(e){
        canGo=false;
      }
    }

    if(!canGo){
      ToastUtil.showNormal(context, "清单为全部检查，无法提交");
      return;
    }
    pushPage(CheckingInformationOnePage(widget.id,checkrecordId,widget.type), context);

  }



}


