import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart' show DateFormat;
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/bottom_picker.dart';
import 'package:qhd_prevention/customWidget/bottom_picker_two.dart';
import 'package:qhd_prevention/customWidget/department_person_picker.dart';
import 'package:qhd_prevention/customWidget/department_picker.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/http/ApiService.dart';

import 'package:qhd_prevention/tools/tools.dart';
import '../../../tools/h_colors.dart';
import '/customWidget/custom_button.dart';


class CustomRecordBean {

  // 已选择的分类 id
 final String departmentId;
 final String departmentName;

 final String responsibleId;
 final String responsibleName;

  // 清单类型
 final String? selectedQDType;
 final String? selectedQDTypeId;
  // 排查周期
 final String? selectedZQTime;
 final String? selectedZQTimeId;

  // 新增：开始/结束时间
 final String startTime;
 final String endTime;


 CustomRecordBean({
    required this.departmentId,
    required this.departmentName,
    required this.responsibleId,
    required this.responsibleName,

    required this.selectedQDType,
    required this.selectedQDTypeId,
    required this.selectedZQTime,
    required this.selectedZQTimeId,


    required this.startTime,
    required this.endTime,


  });


  factory CustomRecordBean.fromJson(
      String departmentId,String departmentName, String responsibleId, String responsibleName,
      String selectedQDType, String selectedQDTypeId, String selectedZQTime,String selectedZQTimeId,
     String startTime,String endTime,
      ) {
    return CustomRecordBean(
      departmentId:departmentId,
      departmentName:departmentName,
      responsibleId:responsibleId,
      responsibleName:responsibleName,

      selectedQDType:selectedQDType,
      selectedQDTypeId:selectedQDTypeId,
      selectedZQTime:selectedZQTime,
      selectedZQTimeId:selectedZQTimeId,


      startTime:startTime,
      endTime:endTime,

    );
  }

  Map<String, dynamic> toJson() {
    return {"departmentId":departmentId,"departmentName":departmentName, "responsibleId":responsibleId,"responsibleName":responsibleName,
      "selectedQDType":selectedQDType,"selectedQDTypeId":selectedQDTypeId,"selectedZQTime":selectedZQTime,"selectedZQTimeId":selectedZQTimeId,
      "startTime":startTime,"endTime":endTime,};
  }

}

/// 自定义抽屉
class CustomRecordDrawer extends StatefulWidget {
  const CustomRecordDrawer(this.listType,this.listInspectionCycle,   {super.key,required this.onClose});

  final List<dynamic> listType ;
  final List<dynamic> listInspectionCycle ;
  final Function(String,String,String,String,String,String,) onClose;
  @override
  _CustomRecordDrawerState createState() => _CustomRecordDrawerState();
}

class _CustomRecordDrawerState extends State<CustomRecordDrawer> {

  // 存储各单位的人员列表
  List<Map<String, dynamic>> _personCache = [];


  // 已选择的分类 id
  String departmentId="";
  String departmentName="";

  String responsibleId="";
  String responsibleName="";

  // 清单类型
  String _selectedQDType="";
  String _selectedQDTypeId="";
  // 排查周期
  String _selectedZQTime="";
  String _selectedZQTimeId="";

  // 新增：开始/结束时间
  DateTime? _startDate;
  DateTime? _endDate;
  String startTime="";
  String endTime="";

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

    setState(() {

      try {
        String? dangerJson = SessionService.instance.customRecordDangerJson;
        if(null!=dangerJson&&dangerJson.isNotEmpty) {
          Map<String, dynamic> dangerWaitBean = json.decode(dangerJson);
          departmentId= dangerWaitBean["departmentId"];
          departmentName= dangerWaitBean["departmentName"];
          responsibleId= dangerWaitBean["responsibleId"];
          responsibleName= dangerWaitBean["responsibleName"];

          _selectedQDType= dangerWaitBean["selectedQDType"];
          _selectedQDTypeId= dangerWaitBean["selectedQDTypeId"];
          _selectedZQTime= dangerWaitBean["selectedZQTime"];
          _selectedZQTimeId= dangerWaitBean["selectedZQTimeId"];

          startTime= dangerWaitBean["startTime"];
          endTime= dangerWaitBean["endTime"];

        }

      } catch (e) {
        print("解析失败: $e");
      }

    });

  }

  @override
  Widget build(BuildContext context) {

    Future<void> showCategoryPicker(int type) async {
      if (type == 1) {
        showModalBottomSheet(
          context: context,
          isScrollControlled: true,
          barrierColor: Colors.black54,
          backgroundColor: Colors.transparent,
          builder: (ctx) => DepartmentPicker(onSelected: (id, name) async {
            setState(() {

               departmentId=id;
               departmentName=name;

               responsibleId="";
               responsibleName="";
               setResult();
            });

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

          }),
        );
      } else if (type == 2) {

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

                  responsibleId=userId;
                  responsibleName=name;
                  setResult();
                });

              },
            );



      }else if (type == 3) {
        final choice = await BottomPickerTwo.show<String>(
          context,
          items: widget.listType,
          itemBuilder: (item) => Text(item["NAME"], textAlign: TextAlign.center),
          initialIndex: 0,
        );
        if (choice != null) {
          for(int i=0;i<widget.listType.length;i++){
            if(choice==widget.listType[i]["NAME"]){
              _selectedQDTypeId = widget.listType[i]["BIANMA"];
            }
          }

          setState(() {
            _selectedQDType = choice;
            setResult();
          });
        }
      }else if (type == 4) {
        final choice = await BottomPickerTwo.show<String>(
          context,
          items: widget.listInspectionCycle,
          itemBuilder: (item) => Text(item["NAME"], textAlign: TextAlign.center),
          initialIndex: 0,
        );
        if (choice != null) {
          for(int i=0;i<widget.listInspectionCycle.length;i++){
            if(choice==widget.listInspectionCycle[i]["NAME"]){
              _selectedZQTimeId = widget.listInspectionCycle[i]["BIANMA"];
            }
          }

          setState(() {
            _selectedZQTime = choice;
            setResult();
          });

        }
      }


    }

    Future<void> _pickStartDate() async {
      final now = DateTime.now();
      final picked = await showDatePicker(
        context: context,
        initialDate: _startDate ?? now,
        firstDate: DateTime(now.year - 5),
        lastDate: DateTime(now.year + 5),
      );
      if (picked != null) {
        setState(() {

          _startDate = picked;
          final dateFormat = DateFormat('yyyy-MM-dd');
          startTime=dateFormat.format(picked);

          // 保证开始 <= 结束
          if (_endDate != null && _endDate!.isBefore(picked)) {
            _endDate = null;
          }


          setResult();

        });
      }
    }

    Future<void> _pickEndDate() async {
      final now = DateTime.now();
      final initial = _endDate ??
          (_startDate != null && _startDate!.isAfter(now)
              ? _startDate!
              : now);
      final picked = await showDatePicker(
        context: context,
        initialDate: initial,
        firstDate: _startDate ?? DateTime(now.year - 5),
        lastDate: DateTime(now.year + 5),
      );
      if (picked != null) {
        setState(() {
          _endDate = picked;

          final dateFormat = DateFormat('yyyy-MM-dd');
          endTime=dateFormat.format(picked);

          setResult();

        });
      }
    }

    Widget _buildDatePickerBox({
      required String label,
      DateTime? date,
      required VoidCallback onTap,
    }) {
      final display = date != null
          ? "${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}"
          : label;
      return Expanded(
        child: GestureDetector(
          onTap: onTap,
          child: Container(
            height: 35,
            padding: const EdgeInsets.symmetric(horizontal: 5),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              border: Border.all(color: Colors.grey.shade400),
              color: Colors.white,
            ),
            child: Row(
              children: [
                const Icon(Icons.calendar_today, size: 18, color: Colors.grey),
                const SizedBox(width: 6),
                Text(display, style: const TextStyle(fontSize: 14, color: Colors.black38)),
              ],
            ),
          ),
        ),
      );
    }

    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              "高级查询",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const Divider(height: 24, color: Colors.grey),

            // 分类筛选
            _buildDropdownBox(
              "检查部门",
              display: departmentName.isNotEmpty ?departmentName: '请选择',
              onTap: () => showCategoryPicker(1),
            ),
            const SizedBox(height: 12),
            _buildDropdownBox(
              "检查人",
              display: responsibleName .isNotEmpty ?responsibleName: '请选择',
              onTap: () => showCategoryPicker(2),
            ),
            const SizedBox(height: 12),
            _buildDropdownBox(
              "清单类型",
              display: _selectedQDType .isNotEmpty ?_selectedQDType: '请选择',
              onTap: () => showCategoryPicker(3),
            ),
            const SizedBox(height: 12),
            _buildDropdownBox(
              "排查周期",
              display: _selectedZQTime .isNotEmpty ?_selectedZQTime: '请选择',
              onTap: () => showCategoryPicker(4),
            ),
            const SizedBox(height: 24),

            // 时间查询
            const Text(
              "时间查询",
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
            ),
            const SizedBox(height: 12),

            // 开始时间 - 结束时间 —— //
            Row(
              children: [
                _buildDatePickerBox(
                  label: "开始时间",
                  date: _startDate,
                  onTap: _pickStartDate,
                ),
                const SizedBox(width: 5),
                const Text("—", style: TextStyle(fontSize: 8)),
                const SizedBox(width: 5),
                _buildDatePickerBox(
                  label: "结束时间",
                  date: _endDate,
                  onTap: _pickEndDate,
                ),
              ],
            ),

            const Spacer(),

            // 底部按钮
            Row(
              children: [
                Expanded(
                  flex: 1,
                  child: CustomButton(
                    text: "重置",
                    backgroundColor: h_backGroundColor(),
                    textStyle: const TextStyle(color: Colors.black45),
                    onPressed: () {
                      setState(() {

                        // 已选择的分类 id
                         departmentId="";
                         departmentName="";
                         responsibleId="";
                         responsibleName="";

                        // 清单类型
                         _selectedQDType="";
                         _selectedQDTypeId="";
                        // 排查周期
                         _selectedZQTime="";
                         _selectedZQTimeId="";

                        // 新增：开始/结束时间
                         _startDate=null;
                         _endDate=null;
                         startTime="";
                         endTime="";

                      });
                    },
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  flex: 2,
                  child: CustomButton(
                    text: "完成",
                    backgroundColor: Colors.blue,
                    onPressed: () {
                      // TODO: 提交筛选条件，包括 _startDate、_endDate
                      Navigator.pop(context);
                      // setResult();// 关闭加载对话框
                    },
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDropdownBox(String title,
      {required String display, required VoidCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 48,
        padding: const EdgeInsets.symmetric(horizontal: 12),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          border: Border.all(color: Colors.grey.shade400),
          color: Colors.white,
        ),
        child: Row(
          children: [
            Text(title, style: const TextStyle(fontSize: 14)),
            const Spacer(),
            Row(
              children: [
                Text(display),
                const Icon(Icons.arrow_drop_down, color: Colors.grey),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void setResult(){

    CustomRecordBean  waitBean= CustomRecordBean.fromJson(
        departmentId ?? "", departmentName?? "", responsibleId?? "",responsibleName?? "",
        _selectedQDType?? "", _selectedQDTypeId?? "",_selectedZQTime?? "", _selectedZQTimeId?? "",
        startTime, endTime);

    String jsonString = jsonEncode(waitBean.toJson());
    SessionService.instance.setCustomRecordDangerJson(jsonString);

    widget.onClose(
      departmentId ?? "",  responsibleName ?? "",
       _selectedQDTypeId ?? "",  _selectedZQTimeId ?? "",
      _startDate!=null?startTime:"",
      _endDate!=null?endTime:"",
    ); // 触发回调
  }


}
