import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/department_person_picker.dart';
import 'package:qhd_prevention/customWidget/department_picker.dart';
import 'package:qhd_prevention/customWidget/picker/CupertinoDatePicker.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';

import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/pages/http/ApiService.dart';
import 'package:qhd_prevention/pages/mine/mine_sign_page.dart';

import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/h_colors.dart';
import 'package:qhd_prevention/tools/tools.dart';

import 'check_information_one_item.dart';
import 'danner_repair.dart';




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

  final int type;
  final String id;
  final String checkrecordId;

  @override
  State<CheckingInformationOnePage> createState() => _CheckingInformationOnePageState();
}

class _CheckingInformationOnePageState extends State<CheckingInformationOnePage> {

  final List<DepartmentEntry> departments = [
    DepartmentEntry(department: '请选择', responsible: '请选择',index:'',departmentId: '',responsibleId:''),
  ];

  final List<DepartmentEntry> otherHidden = [];

  final TextEditingController contentController = TextEditingController();

  // 存储各单位的人员列表
  List<Map<String, dynamic>> _personCache = [];
  List<dynamic> listDates = [];
  String dataTime="";
  String stringTime="";
  String imagePath="";
  String CHECKRECORD_ID="";

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

    CHECKRECORD_ID= widget.checkrecordId??"";
    final now =DateTime.now();
    dataTime=DateFormat('yyyy-MM-dd').format(now);
    stringTime=DateFormat('HH:mm').format(now);

    _getData();

  }


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

    }
  }


  Future<void> _getCheckInformationListYinHuan() async {
    try {

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

          // CHECKRECORD_ID= result['CHECKRECORD_ID'];
          listDates.addAll(newList);//"HIDDENDESCR" -> "3111111"
          for(int i=0;i<listDates.length;i++){
            try{
              otherHidden.add(DepartmentEntry(department: listDates[i]["HIDDENDESCR"], responsible: '请选择',index:'',departmentId:listDates[i]['HIDDEN_ID'] ,responsibleId:''));
            }catch(e){
              otherHidden.add(DepartmentEntry(department: "", responsible: '请选择',index:'',departmentId:listDates[i]['HIDDEN_ID'],responsibleId:''));
            }

          }
        });

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


  Future<void> _getCheckInformationList() async {
    try {

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

          // CHECKRECORD_ID= result['CHECKRECORD_ID'];
          listDates.addAll(newList);//"HIDDENDESCR" -> "3111111"
          for(int i=0;i<listDates.length;i++){
            try{
              otherHidden.add(DepartmentEntry(department: listDates[i]["HIDDENDESCR"], responsible: '请选择',index:'',departmentId:listDates[i]['HIDDEN_ID'] ,responsibleId:''));
            }catch(e){
              otherHidden.add(DepartmentEntry(department: "", responsible: '请选择',index:'',departmentId:listDates[i]['HIDDEN_ID'],responsibleId:''));
            }

            }
        });

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


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: "检查信息"),
      body: ListView(
        children: [
          Container(
            color: Colors.white,
            padding: EdgeInsets.symmetric(horizontal: 15),
            child: ListItemFactory.createRowSpaceBetweenItem(
              leftText: "日期选择",
              rightText: dataTime.isEmpty?"请选择":dataTime,
              isRight: true,
            ),
          ),

          Divider(height: 1,),

          Container(
            color: Colors.white,
          padding: EdgeInsets.symmetric(horizontal: 15),
            child: GestureDetector(
            child: ListItemFactory.createRowSpaceBetweenItem(leftText: '时间选择', rightText: stringTime.isEmpty?'请选择':stringTime, isRight: true),
            onTap: () async {
              DateTime? picked = await BottomDateTimePicker.showDate(context);
              if (picked != null) {
                setState(() {
                  stringTime = DateFormat('HH:mm').format(picked);
                });
              }
            },
          ),
          ),
          SizedBox(height: 10,),
      Container(
        padding: EdgeInsets.only(top: 10,left: 15,right: 15),
        color: Colors.white,
         child:  Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("检查部门的人",style: TextStyle(color: Colors.black,fontSize: 16)),
              CustomButton(
                onPressed: () {
                  _addDepartment();
                },
                text: "添加",
                backgroundColor: Colors.blue,
                borderRadius: 17,
                height: 34,
                padding: EdgeInsets.symmetric(horizontal: 20),
              ),
            ],
          ),
      ),


          Container(
            padding: EdgeInsets.only(left: 10,right: 10),
            color: Colors.white,
            child:  Column(
              children: List.generate(
                departments.length,
                    (index) => _departmentItem(
                  departments[index],
                  index,
                  showLabel: index == 0,
                ),
              ),
            ),
          ),


          ///其他隐患
          SizedBox(height: 10,),
          Container(
            padding: EdgeInsets.only(top: 10,left: 15,right: 15),
            color: Colors.white,
            child:  Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text("其他隐患信息",style: TextStyle(color: Colors.black,fontSize: 16)),
                CustomButton(
                  onPressed: () {
                    _addOtherHidden();
                  },
                  text: "添加",
                  backgroundColor: Colors.blue,
                  borderRadius: 17,
                  height: 34,
                  padding: EdgeInsets.symmetric(horizontal: 20),
                ),
              ],
            ),
          ),

          Container(
            padding: EdgeInsets.only(left: 10,right: 10),
            color: Colors.white,
            child:  Column(
              children: List.generate(
                otherHidden.length,
                    (index) => _otherHiddenItem(otherHidden[index],
                  index,
                  showLabel: index == 0,
                ),
              ),
            ),
          ),



          SizedBox(height: 10,),

          Container(
            color: Colors.white,
            child:  ItemListWidget.multiLineTitleTextField(
              label: '备注：',
              isEditable: true,
              isRequired:false,
              controller: contentController,
              text: "",
            ),
          ),

          SizedBox(height: 10,),

     Container(
        color: Colors.white,
         padding: EdgeInsets.only(top: 10,bottom: 10,left: 15,right: 15),
         child:  Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              GestureDetector(
                onTap: () {
                  pushPage(MineSignPage(), context);
                },
                child:  Text("用户",style: TextStyle(color: Colors.black,fontSize: 16)),
              ),

              _buildConfirmButton(),
            ],
          ),
      ),

      Container(
        color: Colors.white,
        padding: EdgeInsets.only(left: 15,right: 15),
        child: Row(
            children: [
              if (imagePath.isNotEmpty)
                Text('签字照片：',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                    color: Colors.grey,
                  ),
                ),
              const SizedBox(width: 15),
              if (imagePath.isNotEmpty)
                Image.file(File(imagePath),width: 230,height: 150,fit: BoxFit.cover,),

            ],
          ),

      ),

          const SizedBox(height: 8),
          // 确认按钮
          // const Spacer(),
          _buildTrueButton(),


        ],
      ),
    );
  }

  /// 验收部门和负责人选择的item
  Widget _departmentItem(
      DepartmentEntry entry,
      int index, {
        required bool showLabel,
      }) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Colors.black12, width: 1),
            ),
            child: _noAccepet_repair(false,index),
          ),

          // 当 num > 1 时，左上角显示删除按钮
          if (index > 0)
            Positioned(
              top: -20,
              left: -20,
              child: IconButton(
                padding: EdgeInsets.zero,
                constraints: const BoxConstraints(),
                icon: const Icon(Icons.cancel, color: Colors.red, size: 25),
                onPressed: () {
                  _removeDepartment(index);
                  // 这里处理删除逻辑，比如：
                  // setState(() => _items.removeAt(num));
                },
              ),
            ),
        ],
      ),
    );
  }

  void _addDepartment() {
    setState(() {
      departments.add(DepartmentEntry(department: '请选择', responsible: '请选择',index:'',departmentId: '',responsibleId:''));
    });
  }



  // #region 不整改
  Widget _noAccepet_repair(bool _accept,int index, ) {

    return Column(
      children: [
        GestureDetector(
          onTap: () {
            showModalBottomSheet(
              context: context,
              isScrollControlled: true,
              barrierColor: Colors.black54,
              backgroundColor: Colors.transparent,
              builder: (ctx) => DepartmentPicker(onSelected: (id, name) async {

                setState(() {
                  // buMenId=id;
                  // buMenName=name;
                  //
                  // // 清空已选人员
                  // renYuanId="";
                  // renYuanName="";
                  departments[index].department=name;
                  departments[index].departmentId=id;

                  departments[index].responsible="";
                  departments[index].responsibleId="";

                });

                // 拉取该单位的人员列表并缓存
                final result = await ApiService.getListTreePersonList(id);
                _personCache=List<Map<String, dynamic>>.from(
                  result['userList'] as List,
                );


              }),
            );
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(5),
            ),
            child: ListItemFactory.createRowSpaceBetweenItem(
              leftText: "整改部门",
              rightText: departments[index].department.isNotEmpty?departments[index].department:"请选择",
              isRight: true,
            ),
          ),
        ),

        Divider(
          height: 10,
          color: _accept ? h_backGroundColor() : Colors.transparent,
        ),

        GestureDetector(
          onTap: () {
            if ( departments[index].departmentId.isEmpty) {
              ToastUtil.showNormal(context, '请先选择部门');
              return;
            }
            DepartmentPersonPicker.show(
              context,
              personsData: _personCache,
              onSelected: (userId, name) {
                setState(() {
                  // renYuanId = userId;
                  // renYuanName = name;

                  departments[index].responsible=name;
                  departments[index].responsibleId=userId;
                  departments[index].index=(index-1).toString();
                });

              },
            );
          },
          child:Container(
            padding: EdgeInsets.symmetric(horizontal: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(5),
            ),
            child: ListItemFactory.createRowSpaceBetweenItem(
              leftText: "整改负责人",
              rightText: departments[index].responsible.isNotEmpty?departments[index].responsible:"请选择",
              isRight: true,
            ),
          ),
        ),
      ],
    );
  }

  void _removeDepartment(int index) {
    if (index == 0) return; // 防止删除第一行
    setState(() {
      departments.removeAt(index);
    });
  }


  Widget _buildConfirmButton() {
    return SizedBox(
      width: 80,
      height: 30,
      child: ElevatedButton(
        onPressed: () async {
          final path = await Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => MineSignPage()),
          );
          // 更新状态（当子页面关闭时）
          setState(() {
            imagePath = path ?? '';
          });

        },
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFF4285F4),
          padding: const EdgeInsets.symmetric(vertical: 5),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
        ),
        child: Text(
          '手写签字',
          style: TextStyle(fontSize: 12, color: Colors.white),
        ),
      ),
    );
  }

  Widget _otherHiddenItem(
     final DepartmentEntry entry,
      int index, {
        required bool showLabel,
      }) {
    return GestureDetector(
        onTap: () => _selectItem(entry,index),
      child: Padding(
      padding: const EdgeInsets.all(10),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Colors.black12, width: 1),
            ),
            child:  ItemListWidget.multiLineTitleTextField(
              label: '隐患描述：',
              isEditable: false,
              controller: contentController,
              text: entry.department,
            ),
          ),

          // 当 num > 1 时，左上角显示删除按钮
          // if (index > 0)
            Positioned(
              top: -20,
              left: -20,
              child: IconButton(
                padding: EdgeInsets.zero,
                constraints: const BoxConstraints(),
                icon: const Icon(Icons.cancel, color: Colors.red, size: 25),
                onPressed: () {
                  _removeOtherHidden(index);
                  // 这里处理删除逻辑，比如：
                  // setState(() => _items.removeAt(num));
                },
              ),
            ),
        ],
      ),
      ),
    );
  }
  void _addOtherHidden() {
    setState(() {
      otherHidden.add(DepartmentEntry(department: '请选择', responsible: '请选择',index:'',departmentId: '',responsibleId:''));
    });
  }

  void _removeOtherHidden(int index) {
    if (index == 0) return; // 防止删除第一行
    setState(() {
      otherHidden.removeAt(index);
    });
  }

  Map<String, dynamic> nullResult={};
  void _selectItem(final item,int index) {
    String hiddenId=item.departmentId;
    if(hiddenId.isNotEmpty) {
      switch(widget.type  ) {
        case 1: //隐患排查
          _getTemporaryStorageOfHiddenYinHuan(item, hiddenId, index);
          break;
        case 2: //标准排查
          _getTemporaryStorageOfHidden(item, hiddenId, index);
          break;
      }

    }else{
      pushPage(CheckInformationOneItem(
        widget.id,item,nullResult,widget.type,
        onClose: (String departmentId,String yinHuanText) {
          setState(() {
            // this.yinHuanText=yinHuanText;
            // item["REFERENCE_BASIS"]="option2";
            // _selectedValue="option2";
            // unqualifiedInspectionItemID=departmentId;
            otherHidden[index].department=yinHuanText;
            otherHidden[index].departmentId=departmentId;
          });

        },
      ), context);
    }

  }


  Future<void> _getTemporaryStorageOfHiddenYinHuan( item,String hiddenId,int index) async {

    try {
      final result = await ApiService.getYinHuanTemporaryStorageOfHidden(hiddenId);
      if (result['result'] == 'success') {

        pushPage(CheckInformationOneItem(
          widget.id,item,result,widget.type,
          onClose: (String departmentId,String yinHuanText) {
            setState(() {
              // this.yinHuanText=yinHuanText;
              // unqualifiedInspectionItemID=departmentId;
              otherHidden[index].department=yinHuanText;
              otherHidden[index].departmentId=departmentId;
            });

          },
        ), context);

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

  Future<void> _getTemporaryStorageOfHidden( item,String hiddenId,int index) async {

    try {
      final result = await ApiService.getTemporaryStorageOfHidden(hiddenId);
      if (result['result'] == 'success') {

        pushPage(CheckInformationOneItem(
          widget.id,item,result,widget.type,
          onClose: (String departmentId,String yinHuanText) {
            setState(() {
              // this.yinHuanText=yinHuanText;
              // unqualifiedInspectionItemID=departmentId;
              otherHidden[index].department=yinHuanText;
              otherHidden[index].departmentId=departmentId;
            });

          },
        ), context);

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


  Widget _buildTrueButton() {
    return Center(
      child: ElevatedButton(
        onPressed: () {
          _customCheckRecordFinish();
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFF4285F4),
          padding: const EdgeInsets.symmetric(vertical:5,horizontal: 80),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
        ),
        child: Text(
          '提交',
          style: TextStyle(fontSize: 14, color: Colors.white),
        ),
      ),

    );
}

  Future<void> _customCheckRecordFinish( ) async {
    try {

      LoadingDialogHelper.show();

      bool departmentsAllInput=true;
      bool departmentsSameMan=false;
      for(int i=0;i<departments.length;i++){
        if( departments[i].responsibleId.isEmpty){
          departmentsAllInput=false;
        }else{
          for(int m=i+1;m<departments.length;m++){
            if(departments[i].responsibleId==departments[m].responsibleId){
              departmentsSameMan=true;
            }
          }
        }
      }


      if(!departmentsAllInput){
        LoadingDialogHelper.hide();
        ToastUtil.showNormal(context, "请添加验收部门负责人");
        return;
      }

      if(departmentsSameMan){
        LoadingDialogHelper.hide();
        ToastUtil.showNormal(context, "不能选择重复的验收部门负责人");
        return;
      }

      _addImgFiles(imagePath,"13",CHECKRECORD_ID) ;

      String time=dataTime + ' ' + stringTime + ':00';
      String text=contentController.text.trim();

      // 转换为 JSON 字符串
      String json = _convertDepartmentsToJson(departments);

      final Map<String, dynamic> result;
      if(widget.type==1){
        result = await ApiService.customCheckRecordFinishYinHuan(time,text,CHECKRECORD_ID,widget.id,json);
      }else{
        result = await ApiService.customCheckRecordFinish(time,text,CHECKRECORD_ID,widget.id,json);
      }
      // final result = await ApiService.customCheckRecordFinish(time,text,CHECKRECORD_ID,widget.id,json);
      if (result['result'] == 'success') {

      setState(() {
        LoadingDialogHelper.hide();
        Navigator.pop(context);
        Navigator.pop(context);
      });

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

  String _convertDepartmentsToJson(List<DepartmentEntry> departments) {
    // 1. 将列表中的每个对象转换为 Map
    List<Map<String, dynamic>> jsonList = departments
        .map((dept) => dept.toJson())
        .toList();

    // 2. 使用 jsonEncode 转换为 JSON 字符串
    return jsonEncode(jsonList);
  }


  Future<String> _addImgFiles(String imagePath,String type,String id) async {
    try {

      final raw = await ApiService.addImgFiles( imagePath, type, id);
      if (raw['result'] == 'success') {
        return raw['imgPath'];
      }else{
        // _showMessage('反馈提交失败');
        return "";
      }

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

}