import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/picker/CupertinoDatePicker.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/customWidget/date_picker_dialog.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/dh_work_detai/hotwork_apply_detail.dart';

/// 八项作业先关组件，用于展示“安全防护措施”列表
import 'package:flutter/services.dart';

/// 主安全措施表格组件，支持编辑与只读模式
class MeasuresListWidget extends StatelessWidget {
  const MeasuresListWidget({
    super.key,
    required this.measuresList,
    required this.baseImgPath,
    required this.isAllowEdit,
    this.onSign,
    this.isShowSign = true,
  });

  /// 接口返回的原始 Map 列表
  final List<Map<String, dynamic>> measuresList;

  /// 图片的基础路径
  final String baseImgPath;

  /// 是否允许编辑（输入答案 & 签字按钮）
  final bool isAllowEdit;

  /// 签字按钮回调，回调当前行 item
  final void Function(Map<String, dynamic> item)? onSign;

  /// 操作那里是否显示签名图片
  final bool isShowSign;

  @override
  Widget build(BuildContext context) {
    if (measuresList.isEmpty) {
      return const Center(child: Text('暂无更多数据'));
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.only(top: 10, bottom: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 表格容器
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 5),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey.shade300),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Table(
              defaultVerticalAlignment: TableCellVerticalAlignment.middle,

              // 或 .top / .bottom
              columnWidths: const {
                0: FlexColumnWidth(3),
                1: FixedColumnWidth(100),
              },
              border: TableBorder(
                horizontalInside: BorderSide(color: Colors.grey.shade300),
                verticalInside: BorderSide(color: Colors.grey.shade300),
              ),
              children: [
                // 表头
                TableRow(
                  decoration: BoxDecoration(color: Colors.grey.shade100),
                  children: const [
                    Padding(
                      padding: EdgeInsets.all(8),
                      child: Center(
                        child: Text(
                          '主要安全措施',
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.all(8),
                      child: Center(
                        child: Text(
                          '操作',
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ],
                ),
                // 数据行
                for (var item in measuresList)
                  TableRow(
                    children: [
                      // 第一列：措施 + 签名 + 问题答案
                      Padding(
                        padding: const EdgeInsets.all(8),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 主要安全措施
                            Text(item['PROTECTIVE_MEASURES'] as String? ?? ''),

                            // 签名图片 + 时间
                            if (item.containsKey('SIGN_PATH') &&
                                (item['SIGN_PATH'] as String).isNotEmpty)
                              ..._buildImageRows(
                                context,
                                (item['SIGN_PATH'] as String).split(','),
                                item['SIGN_TIME'] as String? ?? '',
                              ),

                            // 问题1～4 + 答案（可编辑或只读）
                            for (var i = 1; i <= 4; i++)
                              if ((item['QUESTION$i'] as String?)?.isNotEmpty ??
                                  false)
                                _buildQnA(item, i),
                          ],
                        ),
                      ),

                      // 第二列：状态文字/按钮 + 操作图片
                      Padding(
                        padding: const EdgeInsets.all(8),
                        child: Column(
                          children: [
                            // 签字或状态
                            isAllowEdit
                                ? TextButton(
                                  onPressed: () {
                                    onSign?.call(item);
                                  },
                                  child: Text(
                                    (item['SIGN_ITEM'] ?? '')
                                            .toString()
                                            .isNotEmpty
                                        ? '已签字'
                                        : '签字',
                                    style: TextStyle(
                                      color:
                                          (item['SIGN_ITEM'] ?? '')
                                                  .toString()
                                                  .isNotEmpty
                                              ? Colors.grey.shade600
                                              : Colors.blue,
                                    ),
                                  ),
                                )
                                : Text(
                                  (item['STATUS'] as String?) == '-1'
                                      ? '不涉及'
                                      : '涉及',
                                  style: TextStyle(
                                    color:
                                        (item['STATUS'] as String?) == '-1'
                                            ? Colors.black
                                            : Colors.black,
                                  ),
                                ),

                            // 操作图片
                            if (item.containsKey('IMG_PATH') &&
                                (item['IMG_PATH'] as String).isNotEmpty &&
                                isShowSign)
                              ..._buildImageRows(
                                context,
                                (item['IMG_PATH'] as String).split(','),
                                '',
                              ),
                          ],
                        ),
                      ),
                    ],
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构造“问题 + 答案”行，编辑模式下显示数字输入框
  Widget _buildQnA(Map<String, dynamic> item, int index) {
    final question = item['QUESTION$index'] as String? ?? '';
    final key = 'ANSWER$index';
    final answer = item[key]?.toString() ?? '';

    if (isAllowEdit) {
      return Padding(
        padding: const EdgeInsets.only(top: 8),
        child: Row(
          children: [
            Expanded(
              flex: 2,
              child: Text(
                '$question:',
                style: const TextStyle(fontWeight: FontWeight.w800),
              ),
            ),
            Expanded(
              flex: 1,
              child: TextFormField(
                initialValue: answer,
                textAlign: TextAlign.center,
                // 输入文字居中对齐
                keyboardType: TextInputType.number,
                inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                decoration: InputDecoration(
                  isDense: true,
                  contentPadding: const EdgeInsets.symmetric(
                    vertical: 8,
                    horizontal: 4,
                  ),
                  // 自定义边框颜色
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey.shade300),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey.shade300),
                  ),
                ),
                onChanged: (val) {
                  item[key] = val;
                },
              ),
            ),
          ],
        ),
      );
    }

    // 只读模式
    return Padding(
      padding: const EdgeInsets.only(top: 8),
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '$question:',
                  style: const TextStyle(fontWeight: FontWeight.w800),
                ),
                Text(answer.isNotEmpty ? answer : '0'),
              ],
            ),
          ),
          const Divider(),
        ],
      ),
    );
  }

  /// 构造一组图片 + 可选时间文本行
  List<Widget> _buildImageRows(
    BuildContext context,
    List<String> paths,
    String time,
  ) {
    return paths.map((p) {
      return Padding(
        padding: const EdgeInsets.only(top: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center, // ← 这一行

          children: [
            GestureDetector(
              onTap: () {
                presentOpaque(
                  SingleImageViewer(imageUrl: '$baseImgPath$p'),
                  context,
                );
              },
              child: Image.network('$baseImgPath$p', width: 60, height: 60),
            ),
            if (time.isNotEmpty) ...[const SizedBox(width: 8), Text(time)],
          ],
        ),
      );
    }).toList();
  }
}

/// 其他安全防护措施表格组件
class OtherMeasuresWidget extends StatelessWidget {
  /// 其他安全防护措施数据列表
  final List<dynamic>? otherMeasures;
  final String baseImgPath;

  const OtherMeasuresWidget({
    Key? key,
    required this.otherMeasures,
    required this.baseImgPath,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final list =
        (otherMeasures ?? [])
            .where((e) => e is Map<String, dynamic>)
            .map((e) => e as Map<String, dynamic>)
            .toList();
    if (list.isEmpty) {
      return const SizedBox.shrink();
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 10),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey.shade300),
            borderRadius: BorderRadius.circular(4),
          ),
          child: Table(
            border: TableBorder(
              horizontalInside: BorderSide(color: Colors.grey.shade300),
              verticalInside: BorderSide(color: Colors.grey.shade300),
            ),
            children: [
              // 表头
              TableRow(
                decoration: BoxDecoration(color: Colors.grey.shade100),
                children: const [
                  Padding(
                    padding: EdgeInsets.all(8),
                    child: Center(
                      child: Text(
                        '其他安全措施',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.all(8),
                    child: Center(
                      child: Text(
                        '签字',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                ],
              ),
              // 数据行
              for (var item in list)
                TableRow(
                  children: [
                    // 描述
                    Padding(
                      padding: const EdgeInsets.all(8),
                      child: Text(item['DESCR'] as String? ?? ''),
                    ),
                    // 签字图片
                    Padding(
                      padding: const EdgeInsets.all(8),
                      child: _buildSignImages(context, item),
                    ),
                  ],
                ),
            ],
          ),
        ),
      ],
    );
  }

  /// 处理 SIGN_PATH 可能是 List 或 String
  Widget _buildSignImages(BuildContext context, Map<String, dynamic> item) {
    final rawPath = item['SIGN_PATH'];
    List<String> paths = [];
    if (rawPath is String && rawPath.isNotEmpty) {
      paths = [rawPath];
    } else if (rawPath is List) {
      paths = rawPath.whereType<String>().toList();
    }

    // 健壮判断：SIGN_TIME 可能不存在或类型非 String/List
    List<String> times = [];
    if (item.containsKey('SIGN_TIME')) {
      final rawTime = item['SIGN_TIME'];
      if (rawTime is String && rawTime.isNotEmpty) {
        times = [rawTime];
      } else if (rawTime is List) {
        times = rawTime.whereType<String>().toList();
      }
    }

    // 没有图片，直接返回空
    if (paths.isEmpty) return const SizedBox.shrink();

    // 构造每一对“图片 + 时间”
    final children = <Widget>[];
    for (var i = 0; i < paths.length; i++) {
      final path = paths[i];
      // 时间对应同下标，越界则使用空字符串
      final timeLabel = (i < times.length) ? times[i] : '';

      children.add(
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            GestureDetector(
              onTap: () {
                presentOpaque(
                  SingleImageViewer(imageUrl: '$baseImgPath$path'),
                  context,
                );
              },
              child: Image.network(
                '$baseImgPath$path',
                width: 60,
                height: 60,
                fit: BoxFit.fill,
                errorBuilder: (_, __, ___) => const Icon(Icons.broken_image),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                timeLabel,
                style: const TextStyle(fontSize: 12, color: Colors.black54),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      );
      if (i != paths.length - 1) {
        children.add(const SizedBox(height: 8));
      }
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: children,
    );
  }
}

/// 各角色签名展示组件
class SignaturesListWidget extends StatelessWidget {
  final Map<String, dynamic>? signs;
  final Map<String, dynamic>? pd;
  final String baseImgPath;

  const SignaturesListWidget({
    Key? key,
    this.signs,
    this.pd,
    required this.baseImgPath,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final safeSigns = signs ?? {};
    final safePd = pd ?? {};
    return Column(
      children: [
        _buildSection(
          context,
          '监护人',
          safeSigns['GUARDIAN'],
          safePd['GUARDIAN_USER_NAME'],
          EditUserType.GUARDIAN,
        ),
        _buildSection(
          context,
          '安全交底人',
          safeSigns['CONFESS'],
          safePd['CONFESS_USER_NAME'],
          EditUserType.CONFESS,
        ),
        _buildSection(
          context,
          '接受交底人',
          safeSigns['ACCEPT_CONFESS'],
          safePd['ACCEPT_CONFESS_USER_NAME'],
          EditUserType.ACCEPT_CONFESS,
        ),
        _buildTextareaWithSigns(
          context,
          '作业负责人意见',
          safeSigns['CONFIRM'],
          safePd['CONFIRM_USER_NAME'],
          EditUserType.CONFIRM,
        ),
        _buildTextareaWithSigns(
          context,
          '所在单位意见',
          safeSigns['LEADER'],
          safePd['LEADER_USER_NAME'],
          EditUserType.LEADER,
        ),
        _buildTextareaWithSigns(
          context,
          '安全管理部门意见',
          safeSigns['AUDIT'],
          safePd['AUDIT_USER_NAME'],
          EditUserType.AUDIT,
        ),
        _buildTextareaWithSigns(
          context,
          '动火审批人意见',
          safeSigns['APPROVE'],
          safePd['APPROVE_USER_NAME'],
          EditUserType.APPROVE,
        ),
        _buildTextareaWithSigns(
          context,
          '动火前在岗班长意见',
          safeSigns['MONITOR'],
          safePd['MONITOR_USER_NAME'],
          EditUserType.MONITOR,
        ),
        _buildSection(
          context,
          '作业开始负责人',
          safeSigns['WORK_START'],
          safePd['WORK_START_USER_NAME'],
          EditUserType.WORK_START,
        ),
        _buildSection(
          context,
          '作业结束负责人',
          safeSigns['WORK_END'],
          safePd['WORK_END_USER_NAME'],
          EditUserType.WORK_END,
        ),
        _buildTextareaWithSigns(
          context,
          '完工验收',
          safeSigns['ACCEPT'],
          safePd['ACCEPT_USER_NAME'],
          EditUserType.ACCEPT,
          timeKey: 'ACCEPT_TIME',
        ),
      ],
    );
  }

  Widget _buildSection(
    BuildContext context,
    String title,
    dynamic rawList,
    dynamic userName,
    EditUserType type, {
    bool showImages = false,
  }) {
    if (rawList is! List || rawList.isEmpty) return const SizedBox.shrink();
    final list = rawList.cast<Map<String, dynamic>>();
    final first = list.first;
    final name = userName is String ? userName : '';

    // 签字图片和时间
    final signPaths = <String>[];
    final signTimes = <String>[];
    if (first['SIGN_PATH'] != null) {
      final rawPath = first['SIGN_PATH'];
      if (rawPath is String && rawPath.isNotEmpty) signPaths.add(rawPath);
      if (rawPath is List) signPaths.addAll(rawPath.cast<String>());
    }
    if (first['SIGN_TIME'] != null) {
      final rawTime = first['SIGN_TIME'];
      if (rawTime is String && rawTime.isNotEmpty) signTimes.add(rawTime);
      if (rawTime is List) signTimes.addAll(rawTime.cast<String>());
    }

    return Container(
      margin: const EdgeInsets.only(top: 20),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.symmetric(
          vertical: BorderSide(color: Colors.grey.shade300),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(8),
            child: Text(
              '$title: $name',
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
          if (showImages && first['IMG_PATH'] is List)
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Wrap(
                spacing: 8,
                children:
                    (first['IMG_PATH'] as List)
                        .cast<String>()
                        .map(
                          (img) => Image.network(
                            '$baseImgPath$img',
                            width: 50,
                            height: 50,
                          ),
                        )
                        .toList(),
              ),
            ),
          for (var i = 0; i < signPaths.length; i++)
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 20),
              child: Row(
                children: [
                  GestureDetector(
                    onTap:
                        () => presentOpaque(
                          SingleImageViewer(
                            imageUrl: '$baseImgPath${signPaths[i]}',
                          ),
                          context,
                        ),
                    child: Image.network(
                      '$baseImgPath${signPaths[i]}',
                      width: 100,
                      height: 100,
                      errorBuilder:
                          (_, __, ___) => const Icon(Icons.broken_image),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Text(i < signTimes.length ? signTimes[i] : ''),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildTextareaWithSigns(
    BuildContext context,
    String label,
    dynamic rawList,
    dynamic userName,
    EditUserType type, {
    String? timeKey,
  }) {
    if (rawList is! List || rawList.isEmpty) return const SizedBox.shrink();
    final first = (rawList as List).cast<Map<String, dynamic>>().first;
    final descr = first['DESCR'] is String ? first['DESCR'] as String : '';
    final name = pd?['${type.name}_USER_NAME'];
    final personDes = type.personName;

    final signPaths = <String>[];
    final signTimes = <String>[];
    if (first['SIGN_PATH'] != null) {
      final rawPath = first['SIGN_PATH'];
      if (rawPath is String && rawPath.isNotEmpty) signPaths.add(rawPath);
      if (rawPath is List) signPaths.addAll(rawPath.cast<String>());
    }
    if (first['SIGN_TIME'] != null) {
      final rawTime = first['SIGN_TIME'];
      if (rawTime is String && rawTime.isNotEmpty) signTimes.add(rawTime);
      if (rawTime is List) signTimes.addAll(rawTime.cast<String>());
    }

    return Container(
      margin: const EdgeInsets.only(top: 20),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.symmetric(
          vertical: BorderSide(color: Colors.grey.shade300),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  label,
                  style: const TextStyle(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 4),
                TextField(
                  controller: TextEditingController(text: descr),
                  maxLines: null,
                  readOnly: true,
                  decoration: const InputDecoration(border: InputBorder.none),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8),
            child: Text('$personDes: $name'),
          ),
          for (var i = 0; i < signPaths.length; i++)
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 20),
              child: Row(
                children: [
                  GestureDetector(
                    onTap:
                        () => presentOpaque(
                          SingleImageViewer(
                            imageUrl: '$baseImgPath${signPaths[i]}',
                          ),
                          context,
                        ),
                    child: Image.network(
                      '$baseImgPath${signPaths[i]}',
                      width: 100,
                      height: 100,
                      errorBuilder:
                          (_, __, ___) => const Icon(Icons.broken_image),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Text(i < signTimes.length ? signTimes[i] : ''),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }
}

///动火安全申请里的’选择其他‘弹窗
class SelectionPopup extends StatefulWidget {
  /// 类型: 'assignments' 或 'identification'
  final String type;

  /// 初始选中值，以逗号分隔
  final String initialValue;

  /// 确认回调
  final void Function(String) onConfirm;

  const SelectionPopup({
    Key? key,
    required this.type,
    required this.initialValue,
    required this.onConfirm,
  }) : super(key: key);

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

class _SelectionPopupState extends State<SelectionPopup> {
  late List<Map<String, String>> workList;
  late String selectedWorkType;
  late String selectedWorkName;
  DateTime? selectedDate;
  List<String> selectValue = [];
  List<Map<String, dynamic>> list = [];

  @override
  void initState() {
    super.initState();
    // 初始化作业类型列表
    workList = [
      {'WORK_TYPE': '', 'WORK_NAME': '请选择'},
      {'WORK_TYPE': 'HOTWORK', 'WORK_NAME': '动火作业'},
      {'WORK_TYPE': 'CONFINEDSPACE', 'WORK_NAME': '受限作业'},
      {'WORK_TYPE': 'HIGHWORK', 'WORK_NAME': '高处作业'},
      {'WORK_TYPE': 'ELECTRICITY', 'WORK_NAME': '临时用电'},
      {'WORK_TYPE': 'BREAKGROUND', 'WORK_NAME': '动土作业'},
      {'WORK_TYPE': 'HOISTING', 'WORK_NAME': '吊装作业'},
      {'WORK_TYPE': 'CUTROAD', 'WORK_NAME': '断路作业'},
      {'WORK_TYPE': 'BLINDBOARD', 'WORK_NAME': '盲板作业'},
    ];
    selectedWorkType = workList[0]['WORK_TYPE']!;
    selectedWorkName = workList[0]['WORK_NAME']!;
    // 初始选中值
    if (widget.initialValue.isNotEmpty) {
      selectValue = widget.initialValue.split(',');
    }
    // 立即加载数据
    _getData();
  }

  Future<void> _pickDate() async {
    DateTime? picked = await BottomDateTimePicker.showDate(
      context,
      mode: BottomPickerMode.date, // 或 BottomPickerMode.dateTime（默认）
      allowFuture: true,
      minTimeStr: '0-0-0 00:00',
    );
    if (picked != null) {
      setState(() {
        selectedDate = picked;
      });
    }
  }

  Future<void> _getData() async {
    // 构造参数
    Map<String, dynamic> params;
    if (widget.type == 'assignments') {
      params = {
        'WORK_TYPE': selectedWorkType,
        'KEYWORDS':
            selectedDate == null
                ? ''
                : DateFormat('yyyy-MM-dd').format(selectedDate!),
        'CORPINFO_ID': SessionService.instance.corpinfoId,
      };
    } else {
      params = {
        'vectors': jsonEncode(['accidentType']),
      };
    }
    try {
      if (widget.type == 'assignments') {
        final result = await ApiService.getEightWorkStartList(params);
        setState(() {
          list = (result['varList'] as List).cast<Map<String, dynamic>>();
          for (var item in list) {
            final type = item['WORK_TYPE'] as String? ?? '';
            final no = item['CHECK_NO'] as String? ?? '';
            final prefixMap = {
              'HOTWORK': '动火作业',
              'CONFINEDSPACE': '受限作业',
              'HIGHWORK': '高处作业',
              'ELECTRICITY': '临时用电',
              'BREAKGROUND': '动土作业',
              'HOISTING': '吊装作业',
              'CUTROAD': '断路作业',
              'BLINDBOARD': '盲板作业',
            };
            item['CHECK_NO'] = (prefixMap[type] ?? '') + ' ' + no;
          }
        });
      } else {
        final result = await ApiService.getEightWorkInfo(params);
        setState(() {
          list = (result['accidentType'] as List).cast<Map<String, dynamic>>();
        });
      }
    } catch (e) {
      ToastUtil.showError(context, '$e');
    }
  }

  void _reset() {
    setState(() {
      // 回到下拉列表的初始选项（第 0 项）
      selectedWorkType = workList[0]['WORK_TYPE']!;
      selectedWorkName = workList[0]['WORK_NAME']!;

      selectedDate = null;
      list.clear();
      selectValue.clear();
    });
    _getData();
  }

  void _determine() {
    // 合并选中
    final result = selectValue.join(',');
    widget.onConfirm(result);
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {

    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(5), // 圆角半径
      ),
      backgroundColor: Colors.white,
      insetPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 40),
      child: SizedBox(
        width: double.infinity,
        height: screenHeight(context),
        child: Column(
          children: [
            // 筛选栏
            if (widget.type == 'assignments')
              Padding(
                padding: const EdgeInsets.all(12),
                child: Column(
                  children: [
                    Row(
                      children: [
                        // 作业类型下拉
                        Text('作业类型:'),
                        Expanded(
                          child: DropdownButton<String>(
                            dropdownColor: Colors.white,
                            isExpanded: true,
                            value: selectedWorkName,
                            // 下拉列表里的项（菜单中居中）
                            items:
                                workList
                                    .map(
                                      (e) => DropdownMenuItem<String>(
                                        value: e['WORK_NAME'],
                                        child: Center(
                                          child: Text(
                                            e['WORK_NAME'] ?? '',
                                            style: TextStyle(
                                              color: Colors.black87,
                                              fontSize: 15,
                                            ),
                                            textAlign: TextAlign.center,
                                          ),
                                        ),
                                      ),
                                    )
                                    .toList(),

                            // selectedItemBuilder 决定按钮上显示的已选项样式（在按钮上居中显示）
                            selectedItemBuilder: (BuildContext context) {
                              return workList.map<Widget>((e) {
                                return Center(
                                  child: Text(
                                    e['WORK_NAME'] ?? '',
                                    style: TextStyle(
                                      color: Colors.black87,
                                      fontSize: 15,
                                    ),
                                    textAlign: TextAlign.center,
                                  ),
                                );
                              }).toList();
                            },

                            onChanged: (v) {
                              final idx = workList.indexWhere(
                                (e) => e['WORK_NAME'] == v,
                              );
                              if (idx >= 0) {
                                setState(() {
                                  selectedWorkType =
                                      workList[idx]['WORK_TYPE']!;
                                  selectedWorkName = v!;
                                });
                                _getData();
                              }
                            },
                          ),
                        ),
                        const SizedBox(width: 12),
                        TextButton(
                          onPressed: _pickDate,
                          child: Row(
                            children: [
                              Text(
                                selectedDate == null
                                    ? '选择作业申请时间'
                                    : selectedDate!.toString().split(' ')[0],
                                style: TextStyle(color: Colors.blue),
                              ),
                              SizedBox(width: 5),
                              Icon(
                                Icons.arrow_drop_down,
                                color: Colors.grey,
                                size: 20,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    Row(
                      children: [
                        // 清空
                        Expanded(
                          child: CustomButton(
                            text: '搜索',
                            padding: EdgeInsets.symmetric(horizontal: 15),
                            margin: const EdgeInsets.symmetric(horizontal: 0),
                            height: 35,
                            backgroundColor: Colors.green,
                            onPressed: _getData,
                          ),
                        ),
                        const SizedBox(width: 10,),
                        // 清空
                        Expanded(
                          child: CustomButton(
                            text: '清空',
                            margin: const EdgeInsets.symmetric(horizontal: 0),
                            textStyle: TextStyle(color: Colors.black),
                            padding: EdgeInsets.symmetric(horizontal: 15),
                            height: 35,
                            backgroundColor: Colors.grey.shade200,
                            onPressed: _reset,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            // 列表多选
            Expanded(
              child: ListView.builder(
                padding: const EdgeInsets.symmetric(horizontal: 0),
                itemCount: list.length,
                itemBuilder: (c, i) {
                  final item = list[i];
                  final value = selectValue;
                  final key =
                      widget.type == 'assignments'
                          ? item['CHECK_NO'] as String? ?? ''
                          : item['NAME'] as String? ?? '';
                  final checked = value.contains(key);
                  return CheckboxListTile(
                    controlAffinity: ListTileControlAffinity.leading, // <-- 把图标放左边
                    contentPadding: EdgeInsets.zero, // 可选：移除左右默认 padding，使图标贴近左侧
                    activeColor: Colors.blue,
                    title: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(key, style: TextStyle(fontSize: 15)),
                        if (widget.type == 'assignments') ...[
                          Text('作业内容: ${item['WORK_CONTENT'] ?? ''}', style: TextStyle(fontSize: 15),),
                          Text('作业负责人: ${item['CONFIRM_USER_NAME'] ?? ''}', style: TextStyle(fontSize: 15)),
                          Text('作业申请时间: ${item['CREATTIME'] ?? ''}', style: TextStyle(fontSize: 15)),
                        ],
                      ],
                    ),
                    value: checked,
                    onChanged: (v) {
                      setState(() {
                        if (v == true)
                          selectValue.add(key);
                        else
                          selectValue.remove(key);
                      });
                    },
                  );

                },
              ),
            ),
            // 确定/关闭
            Padding(
              padding: const EdgeInsets.all(12),
              child: Row(
                children: [
                  Expanded(
                    child: CustomButton(
                      text: '确定',
                      height: 40,
                      backgroundColor: Colors.blue,
                      onPressed: _determine,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: CustomButton(
                      text: '关闭',
                      height: 40,
                      backgroundColor: Colors.grey.shade300,
                      textStyle: TextStyle(color: Colors.grey.shade600),
                      onPressed: () => Navigator.of(context).pop(),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
