import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/BaiDuMap/Map_page.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/home/tap/tabList/special_wrok/dh_work/HotWorkDetailFormWidget.dart';
import 'package:qhd_prevention/pages/home/tap/workArea_picker.dart';
import 'package:qhd_prevention/tools/h_colors.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/qtfx_work_detail/hotwork_gas_list.dart';
import 'package:qhd_prevention/customWidget/bottom_picker.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_Wrok/MeasuresListWidget.dart';

enum EditUserType {
  ANALYZE('分析单位', '分析单位负责人', true),
  GUARDIAN('监护人单位', '监护人', true),
  CONFESS('安全交底人单位', '安全交底人', true),
  ACCEPT_CONFESS('接受交底人单位', '接受交底人', true),
  WORK_USER('作业人单位', '作业人', true),
  CONFIRM('作业负责人单位', '作业负责人', true),
  LEADER('所在单位', '所在单位负责人', true),
  AUDIT('安全管理部门', '安全管理部门负责人', true),
  APPROVE('动火审批单位', '动火审批负责人', true),
  MONITOR('动火前在岗部门', '动火前在岗班长', true),
  WORK_START('作业开始负责人单位', '作业开始负责人', true),
  WORK_END('作业结束负责人单位', '作业结束负责人', true),
  ACCEPT('验收部门', '验收部门负责人', true);

  /// 对应的单位显示名
  final String displayName;
  final String personName;
  final bool isRequired;

  const EditUserType(this.displayName, this.personName, this.isRequired);
}

class HotworkApplyDetail extends StatefulWidget {
  const HotworkApplyDetail({
    super.key,
    required this.HOTWORK_ID,
    required this.flow,
  });

  final String HOTWORK_ID;
  final String flow;

  @override
  State<HotworkApplyDetail> createState() => _HotworkApplyDetailState();
}

class _HotworkApplyDetailState extends State<HotworkApplyDetail> {
  late bool isEditable = false;
  final levelList = ["特级", "一级", "二级"];

  /// 编辑还是新增
  late String msg = 'add';

  /// 详情
  late Map<String, dynamic> pd = {};
  late Map<String, dynamic> signs = {};
  late List<Map<String, dynamic>> measuresList = [];

  final TextEditingController _contentController = TextEditingController();
  final TextEditingController _locationController = TextEditingController();
  final TextEditingController _methodController = TextEditingController();
  final TextEditingController _hotworkPersonController =
      TextEditingController();
  final TextEditingController _relatedController = TextEditingController();
  final TextEditingController _riskController = TextEditingController();

  /// 动火人及证书编号
  late List<dynamic> workUserList = [];

  /// ------------------- 新增 -------------------
  /// 视频监控摄像
  late List<dynamic> videoMonitoringList = [];
  /// 承包商列表
  late List<dynamic> unitAllList = [];
  /// 作业区域列表
  late List<Map<String, dynamic>> workAreaList = [];
  /// --------------------------------------

  // 存储各单位的人员列表
  final Map<EditUserType, List<Map<String, dynamic>>> _personCache = {};

  @override
  void initState() {
    super.initState();
    if (widget.HOTWORK_ID.length > 0) {
      msg = 'edit';
      _getData();
    } else {
      isEditable = true;
      // pd['ANALYZE_TIME'] = 1;
      pd['APPLY_DEPARTMENT_ID'] = SessionService.instance.deptId;
      pd['APPLY_DEPARTMENT_NAME'] =
          SessionService.instance.loginUser!['DEPARTMENT_NAME'] ?? '';
      pd['APPLY_USER_ID'] = SessionService.instance.loginUserId;
      pd['APPLY_USER_NAME'] = SessionService.instance.username;
      pd['IS_CONTRACTOR_WORK'] = '0';

    }
    _getHotWorkNameList();
    _getVideoList();
    _getUnitListAll();
    _getPlsList();

    _contentController.addListener(() {
      setState(() {
        pd['WORK_CONTENT'] = _contentController.text.trim();
      });
    });
    _locationController.addListener(() {
      pd['WORK_PLACE'] = _locationController.text.trim();
    });
    _methodController.addListener(() {
      pd['WORK_FUNCTION'] = _methodController.text.trim();
    });
    _hotworkPersonController.addListener(() {
      pd['WORK_USER'] = _hotworkPersonController.text.trim();
    });
    _relatedController.addListener(() {
      pd['SPECIAL_WORK'] = _relatedController.text.trim();
    });
    _riskController.addListener(() {
      pd['RISK_IDENTIFICATION'] = _riskController.text.trim();
    });
  }

  void set_pd_DEPARTMENT_ID(EditUserType type, String id) {
    pd['${type.name}_DEPARTMENT_ID'] = id;
  }

  void set_pd_DEPARTMENT_NAME(EditUserType type, String name) {
    pd['${type.name}_DEPARTMENT_NAME'] = name;
  }

  void set_pd_USER_ID(EditUserType type, String id) {
    if (type == EditUserType.WORK_USER) {
      pd['${type.name}_ID'] = id;
    }else{
      pd['${type.name}_USER_ID'] = id;
    }
  }

  void set_pd_USER_Name(EditUserType type, String name) {
    pd['${type.name}_USER_NAME'] = name;
  }

  String get_pd_DEPARTMENT_ID(EditUserType type) {
    return pd['${type.name}_DEPARTMENT_ID'] ?? '';
  }

  String get_pd_DEPARTMENT_NAME(EditUserType type) {
    return pd['${type.name}_DEPARTMENT_NAME'] ?? '';
  }

  String get_pd_USER_ID(EditUserType type) {
    if (type == EditUserType.WORK_USER) {
      return pd['${type.name}_ID'] ?? '';
    } else {
      return pd['${type.name}_USER_ID'] ?? '';
    }
  }

  String get_pd_USER_Name(EditUserType type) {
    return pd['${type.name}_USER_NAME'] ?? '';
  }

  Future<void> _chooseLevel() async {
    final choice = await BottomPicker.show<String>(
      context,
      items: levelList,
      itemBuilder: (item) => Text(item, textAlign: TextAlign.center),
      initialIndex: 0,
    );
    if (choice != null) {
      // 用户点击确定并选择了 choice
      setState(() {
        pd['WORK_LEVEL'] = choice;
        FocusHelper.clearFocus(context);
      });
    }
  }

  Future<void> _chooseHorkUser() async {
    final choice = await BottomPicker.show<String>(
      context,
      items: workUserList.map((item) => item['NAME'] as String).toList(),
      itemBuilder: (item) => Text(item, textAlign: TextAlign.center),
      initialIndex: 0,
    );
    if (choice != null) {
      setState(() {
        pd['WORK_USER'] = choice;
        _hotworkPersonController.text = choice;
        Map<String, dynamic> result = workUserList.firstWhere(
          (item) => item['NAME'] == choice,
          orElse: () => {}, // 避免找不到时报错
        );
        if (FormUtils.hasValue(result, 'USER_ID')) {
          pd['WORK_USER_ID'] = result['USER_ID'];
        }
        FocusHelper.clearFocus(context);
      });
    }
  }

  /// ---------------------------- 新增 --------------------------------
  /// 视频监控摄像头
  Future<void> _chooseVideoManager() async {
    final choice = await BottomPicker.show<String>(
      context,
      items:
          videoMonitoringList
              .map((item) => item['VIDEONAME'] as String)
              .toList(),
      itemBuilder: (item) => Text(item, textAlign: TextAlign.center),
      initialIndex: 0,
    );
    if (choice != null) {
      setState(() {
        pd['VIDEONAME'] = choice;

        Map<String, dynamic> result = videoMonitoringList.firstWhere(
          (item) => item['VIDEONAME'] == choice,
          orElse: () => {}, // 避免找不到时报错
        );
        if (FormUtils.hasValue(result, 'VIDEOMANAGER_ID')) {
          pd['VIDEOMANAGER_ID'] = result['VIDEOMANAGER_ID'];
        }
        FocusHelper.clearFocus(context);
      });
    }
  }
  /// 选择承包商
  Future<void> _chooseUnitManager() async {
    final choice = await BottomPicker.show<String>(
      context,
      items: unitAllList.map((item) => item['UNITS_NAME'] as String).toList(),
      itemBuilder: (item) => Text(item, textAlign: TextAlign.center),
      initialIndex: 0,
    );
    if (choice != null) {
      setState(() {
        pd['UNITS_NAME'] = choice;

        Map<String, dynamic> result = unitAllList.firstWhere(
          (item) => item['UNITS_NAME'] == choice,
          orElse: () => {}, // 避免找不到时报错
        );
        if (FormUtils.hasValue(result, 'UNITS_ID')) {
          pd['UNITS_ID'] = result['UNITS_ID'];
        }
        FocusHelper.clearFocus(context);
      });
    }
  }
  /// 预计作业开始时间
  Future<void> _chooseWorkStartTime() async {
    DateTime? picked = await BottomDateTimePicker.showDate(
      context,
      allowFuture: true,
    );
    if (picked != null) {
      setState(() {
        pd['WORK_EXPECTED_START_TIME'] = DateFormat(
          'yyyy-MM-dd HH:mm:ss',
        ).format(picked);

        /// 开始时间必须早于结束时间
        if (FormUtils.hasValue(pd, 'WORK_EXPECTED_END_TIME') &&
            !isBeforeStr(
              pd['WORK_EXPECTED_START_TIME'],
              pd['WORK_EXPECTED_END_TIME'],
            )) {
          pd['WORK_EXPECTED_END_TIME'] = '';
        }
      });
    }
  }
  /// 预计作业结束时间
  Future<void> _chooseWorkEndTime() async {
    DateTime? picked = await BottomDateTimePicker.showDate(
      context,
      minTimeStr: pd['WORK_EXPECTED_START_TIME'] ?? '',
      allowFuture: true,
    );
    if (picked != null) {
      setState(() {
        pd['WORK_EXPECTED_END_TIME'] = DateFormat(
          'yyyy-MM-dd HH:mm:ss',
        ).format(picked);
      });
    }
  }
  /// 选择经纬度
  Future<void> _showLocationHandle() async{
    if (!FormUtils.hasValue(pd, 'ELECTRONIC_FENCE_AREA_ID')) {
      ToastUtil.showNormal(context, '请选择作业区域');
      return;
    }
    Map mapData = await pushPage(MapPage(gson: pd['POSITIONS']), context);
    setState(() {
      pd['LONGITUDE'] = mapData['longitue'];
      pd['LATITUDE'] = mapData['latitude'];
      pd['LATITUDE_LONGITUDE'] = '${mapData['longitue']},${mapData['latitude']}';
    });

  }
  /// 作业区域
  Future<void> _getWorkArea() async {
    FocusHelper.clearFocus(context);
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      barrierColor: Colors.black54,
      backgroundColor: Colors.transparent,
      builder:
          (_) => WorkAreaPicker(
        onSelected: (String id, String POSITIONS, String name) {
          pd['ELECTRONIC_FENCE_AREA_ID'] = id;
          pd['POSITIONS'] = POSITIONS;
          pd['PLS_NAME'] = name;
        },
      ),
    ).then((_) {
      FocusHelper.clearFocus(context);
    });
  }
  /// 获取摄像头列表
  Future<void> _getVideoList() async {
    final result = await ApiService.getVideomanagerList();
    setState(() {
      videoMonitoringList = result['varList'] ?? [];
    });
  }
  /// 获承包商列表
  Future<void> _getUnitListAll() async {
    final result = await ApiService.getUnitListAll();
    setState(() {
      unitAllList = result['varList'] ?? [];
    });
  }
  /// 作业区域列表
  Future<void> _getPlsList() async {
    final result = await ApiService.getWorkAreaList();
    setState(() {
      final String zTreeNodes = result['zTreeNodes'] ?? '';
      workAreaList = jsonDecode(zTreeNodes);
    });
  }
  /// ------------------------------------------------------------


  Widget _card(Widget child) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 5),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5),
      ),
      child: child,
    );
  }

  Widget _chooseItem(EditUserType type) {
    bool isClean = false;
    bool isRequired = true;

    if (isEditable) {
      if (type == EditUserType.AUDIT && (pd['WORK_LEVEL'] ?? '') == '二级') {
        isClean = true;
        isRequired = false;
      }

      // 如果既不是二级也不是一级，就加上 APPROVE
      if (type == EditUserType.APPROVE && pd['WORK_LEVEL'] != '特级') {
        isRequired = false;
        isClean = true;
      }
      // EditUserType.APPROVE,
      if (type == EditUserType.APPROVE &&
          ((pd['WORK_LEVEL'] ?? '') == '二级' ||
              (pd['WORK_LEVEL'] ?? '') == '一级')) {
        isClean = true;
      }
    }

    return Column(
      children: [
        ItemListWidget.selectableLineTitleTextRightButton(
          isRequired: isRequired,
          label: type.displayName,
          isEditable: isEditable,
          isClean: isClean,
          onTapClean: () {
            setState(() {
              pd['${type.name}_DEPARTMENT_NAME'] = '';
              pd['${type.name}_USER_NAME'] = '';
              _personCache.remove(type);
            });
          },
          text: pd['${type.name}_DEPARTMENT_NAME'] ?? '请选择',
          onTap: () => chooseUnitHandle(type),
        ),
        Divider(),
        ItemListWidget.selectableLineTitleTextRightButton(
          isRequired: isRequired,
          label: type.personName,
          isEditable: isEditable,
          text: pd['${type.name}_USER_NAME'] ?? '请选择',
          onTap: () => choosePersonHandle(type),
        ),
      ],
    );
  }

  /// 弹出单位选择
  void chooseUnitHandle(EditUserType type) {
    FocusHelper.clearFocus(context);
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      barrierColor: Colors.black54,
      backgroundColor: Colors.transparent,
      builder:
          (_) => DepartmentPicker(
            onSelected: (id, name) async {
              setState(() {
                set_pd_DEPARTMENT_ID(type, id);
                set_pd_DEPARTMENT_NAME(type, name);
                set_pd_USER_ID(type, '');
                set_pd_USER_Name(type, '');
              });
              _getPersonListForUnitId(id, type);
            },
          ),
    ).then((_) {
      FocusHelper.clearFocus(context);
    });
  }

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

  /// 弹出人员选择，需先选择单位
  void choosePersonHandle(EditUserType type) async {
    FocusHelper.clearFocus(context);

    String unitId = get_pd_DEPARTMENT_ID(type);
    final personList = _personCache[type] ?? [];
    if (!unitId.isNotEmpty) {
      final unitName = type.displayName;
      ToastUtil.showNormal(context, '请先选择$unitName');
      return;
    }

    if (personList.isEmpty) {
      // 一般这种情况是因为重新编辑没有缓存对应部门的负责人，所以先拉取一下接口
      await _getPersonListForUnitId(unitId, type);
      final list = _personCache[type] ?? [];

      if (list.isEmpty) {
        // 如果还是没数据，说明该部门没有可选的人
        ToastUtil.showNormal(context, '暂无数据，请选择其他单位');
      } else {
        choosePersonHandle(type);
      }
      return;
    }
    if (personList.isEmpty) {
      // 如果还是没数据，说明该部门没有可选的人
      ToastUtil.showNormal(context, '请先选择' + type.displayName);

      return;
    }
    DepartmentPersonPicker.show(
      context,
      personsData: personList,
      onSelected: (userId, name) {
        setState(() {
          set_pd_USER_ID(type, userId);
          set_pd_USER_Name(type, name);
        });
      },
    ).then((_) {
      FocusHelper.clearFocus(context);
    });
  }

  /// 提交  1 提交 0暂存
  Future<void> _submit(String status) async {
    // 通用文本字段校验规则
    final textRules = <Map<String, dynamic>>[
      {'value': _contentController.text.trim(), 'message': '请填写作业内容'},
      {'value': _locationController.text.trim(), 'message': '请填写动火地点及部位'},
      {'value': _methodController.text.trim(), 'message': '请填写动火方式'},
      {'value': _hotworkPersonController.text.trim(), 'message': '请填写动火人及证书编号'},
      {
        'value': _relatedController.text.trim(),
        'message': '请输入关联的其他特殊作业及安全作业票编号',
      },
      {'value': _riskController.text.trim(), 'message': '请填写风险辨识结果'},
    ];
    final level = pd['WORK_LEVEL'] ?? '';
    print('---level-$level');

    /// 各项负责人校验
    final unitRules = <EditUserType>[
      EditUserType.ANALYZE,
      EditUserType.GUARDIAN,
      EditUserType.CONFESS,
      EditUserType.ACCEPT_CONFESS,
      EditUserType.WORK_USER,
      EditUserType.CONFIRM,
      EditUserType.LEADER,
      // 如果不是二级，或者SAFETY_USER_ID有值就加上 AUDIT
      if (pd['WORK_LEVEL'] != '二级' || FormUtils.hasValue(pd, 'SAFETY_USER_ID'))
        EditUserType.AUDIT,
      EditUserType.AUDIT,
      // 如果既不是二级也不是一级，就加上 APPROVE
      if (pd['WORK_LEVEL'] == '特级') EditUserType.APPROVE,

      EditUserType.MONITOR,
      EditUserType.WORK_START,
      EditUserType.WORK_END,
      EditUserType.ACCEPT,
    ];

    if (status == '1') {
      // 文本校验
      for (var rule in textRules) {
        if ((rule['value'] as String).isEmpty) {
          ToastUtil.showNormal(context, rule['message']);
          return;
        }
      }
      // 级别校验
      if (level.length == 0) {
        ToastUtil.showNormal(context, '请选择动火级别');
        return;
      }
      if (level == '特级') {
        if (!FormUtils.hasValue(pd, 'VIDEOMANAGER_ID')) {
          ToastUtil.showNormal(context, '请选择视频监控');
          return;
        }
      }
      if (!FormUtils.hasValue(pd, 'WORK_EXPECTED_START_TIME')) {
        ToastUtil.showNormal(context, '请选择预计作业开始时间');
        return;
      }
      if (!FormUtils.hasValue(pd, 'WORK_EXPECTED_START_TIME')) {
        ToastUtil.showNormal(context, '请选择预计作业开始时间');
        return;
      }

      if (pd['IS_CONTRACTOR_WORK'] == '1' && !FormUtils.hasValue(pd, 'UNITS_ID')) {
        ToastUtil.showNormal(context, '请选择承包商');
        return;
      }

      if (!FormUtils.hasValue(pd, 'LATITUDE_LONGITUDE')) {
        ToastUtil.showNormal(context, '请定位作业地点');
        return;
      }

      for (var type in unitRules) {
        if (get_pd_DEPARTMENT_ID(type).length == 0) {
          ToastUtil.showNormal(context, '请选择${type.displayName}');
          return;
        }
        if (get_pd_USER_ID(type).length == 0) {
          ToastUtil.showNormal(context, '请选择${type.displayName}负责人');
          return;
        }
      }
    }
    // LoadingDialogHelper.show();

    String taskId = '0';
    if (level == '特级') {
      taskId = '1';
    } else if (level == '一级') {
      taskId = '2';
    } else if (level == '二级') {
      taskId = '3';
    }
    pd['USER_ID'] = SessionService.instance.loginUserId;
    pd['STEP_ID'] = status;
    pd['CORPINFO_ID'] = SessionService.instance.corpinfoId;
    pd['OPERATOR'] = SessionService.instance.loginUserId;
    pd['CREATOR'] = SessionService.instance.loginUserId;
    pd['ACTION_USER'] = SessionService.instance.username;
    pd['APPLY_STATUS'] = status;
    pd['TASK_ID'] = taskId;

    // 提交参数
    if (msg == 'add') {
      pd['HOTWORK_ID'] = widget.HOTWORK_ID;
      pd['APPLY_DEPARTMENT_ID'] = SessionService.instance.deptId;
      pd['APPLY_DEPARTMENT_NAME'] =
          SessionService.instance.loginUser?['DEPARTMENT_NAME'] ?? '';
      pd['APPLY_USER_ID'] = SessionService.instance.loginUserId;
      pd['APPLY_USER_NAME'] = SessionService.instance.username;
    }

    LoadingDialogHelper.show();
    String jsonStr = jsonEncode(pd);
    printLongString(jsonStr);
    try {
      String url = "/app/hotwork/" + msg;
      final result = await ApiService.submitHomework(url, pd);
      LoadingDialogHelper.hide();
      if (result['result'] == 'success') {
        ToastUtil.showSuccess(context, status == '1' ? '提交成功' : '已暂存');
        Navigator.of(context).pop(true);
      } else {
        ToastUtil.showError(context, '提交失败');
      }
    } catch (e) {
      LoadingDialogHelper.hide();
      ToastUtil.showNormal(context, '操作失败：$e');
    }
  }

  Future<void> _getHotWorkNameList() async {
    final result = await ApiService.getHotWorkNameList();
    setState(() {
      workUserList = result['varList'] ?? [];
    });
  }



/// ---------------------------- 接口请求 --------------------------------

  /// 初始化拉取数据
  Future<void> _getData() async {
    final data = await ApiService.getHomeworkFindById(
      'hotwork',
      widget.HOTWORK_ID,
    );
    setState(() {
      pd = data['pd'];
      if (pd['STEP_ID'] == 0) {
        isEditable = true;
      } else {
        _getSigns(pd['HOTWORK_ID'] ?? '');
        _getMeasures(pd['HOTWORK_ID'] ?? '');
      }
      //  给所有输入框赋值
      _contentController.text = pd['WORK_CONTENT'] ?? '';
      _locationController.text = pd['WORK_PLACE'] ?? '';
      _methodController.text = pd['WORK_FUNCTION'] ?? '';
      _hotworkPersonController.text = pd['WORK_USER'] ?? '';
      _relatedController.text = pd['SPECIAL_WORK'] ?? '';
      _riskController.text = pd['RISK_IDENTIFICATION'] ?? '';
    });
    // final data = await ApiService.getHomeworkFindById('hotwork', widget.HOTWORK_ID);
    // setState(() {
    //   pd = data['pd'];
    // });
    // LoadingDialogHelper.hide();
  }
  Future<void> _getSigns(String homework_id) async {
    final data = await ApiService.listSignFinished(
      'hotwork',
      homework_id.length > 0 ? homework_id : widget.HOTWORK_ID,
    );
    setState(() {
      signs = data['signs'] ?? {};
    });
  }
  Future<void> _getMeasures(String homework_id) async {
    final data = await ApiService.listSignFinishMeasures(
      'hotwork',
      homework_id.length > 0 ? homework_id : widget.HOTWORK_ID,
    );
    setState(() {
      measuresList = List<Map<String, dynamic>>.from(
        data['finishMeasuresList'] ?? <Map<String, dynamic>>[],
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: h_backGroundColor(),
      appBar: MyAppbar(title: '动火安全作业申请'),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.all(12),
          child: Column(
            children: [
              _card(
                HotWorkDetailFormWidget(
                  pd: pd,
                  isEditable: isEditable,
                  contentController: _contentController,
                  locationController: _locationController,
                  methodController: _methodController,
                  hotworkPersonController: _hotworkPersonController,
                  relatedController: _relatedController,
                  riskController: _riskController,
                  onChooseLevel: _chooseLevel,
                  onChooseHotworkUser: _chooseHorkUser,
                  // 新增
                  onChooseVideoManager: _chooseVideoManager,
                  onWorkStartTimeHandle: _chooseWorkStartTime,
                  onWorkEndTimeHandle: _chooseWorkEndTime,
                  onContractorHandle: _chooseUnitManager,
                  onWorkAreaHandle: _getWorkArea,
                  onWorkAreaLocationHandle: _showLocationHandle,


                  onAnalyzeTap: () {
                    pushPage(
                      HotworkGasList(HOTWORK_ID: widget.HOTWORK_ID),
                      context,
                    );
                  },
                ),
              ),
              if (isEditable)
                Column(
                  children: [
                    SizedBox(height: 15),
                    _card(_chooseItem(EditUserType.ANALYZE)),
                    SizedBox(height: 15),
                    _card(_chooseItem(EditUserType.GUARDIAN)),
                    SizedBox(height: 15),
                    _card(_chooseItem(EditUserType.CONFESS)),
                    SizedBox(height: 15),
                    _card(_chooseItem(EditUserType.ACCEPT_CONFESS)),
                    SizedBox(height: 15),
                    _card(_chooseItem(EditUserType.WORK_USER)),
                    SizedBox(height: 15),
                    _card(_chooseItem(EditUserType.CONFIRM)),
                    SizedBox(height: 15),
                    _card(_chooseItem(EditUserType.LEADER)),
                    SizedBox(height: 15),
                    _card(_chooseItem(EditUserType.AUDIT)),
                    SizedBox(height: 15),
                    _card(_chooseItem(EditUserType.APPROVE)),
                    SizedBox(height: 15),
                    _card(_chooseItem(EditUserType.MONITOR)),
                    SizedBox(height: 15),
                    _card(
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          _chooseItem(EditUserType.WORK_START),
                          Divider(),
                          Row(
                            children: [
                              SizedBox(width: 12),
                              Text(
                                '友情提示：负责填写作业实际开始时间',
                                style: TextStyle(color: Colors.red),
                              ),
                            ],
                          ),
                          SizedBox(height: 5),
                        ],
                      ),
                    ),
                    SizedBox(height: 15),
                    _card(
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          _chooseItem(EditUserType.WORK_END),
                          Divider(),
                          Row(
                            children: [
                              SizedBox(width: 12),
                              Text(
                                '友情提示：负责填写作业实际结束时间',
                                style: TextStyle(color: Colors.red),
                              ),
                            ],
                          ),
                          SizedBox(height: 5),
                        ],
                      ),
                    ),
                    SizedBox(height: 15),
                    _card(_chooseItem(EditUserType.ACCEPT)),
                    SizedBox(height: 15),
                  ],
                ),
              if (measuresList.length > 0)
                Column(
                  children: [
                    SizedBox(height: 20),
                    ListItemFactory.createBuildSimpleSection('安全防护措施'),
                    Container(
                      color: Colors.white,
                      child: MeasuresListWidget(
                        measuresList:
                            measuresList, // List<Map<String, dynamic>>
                        baseImgPath: ApiService.baseImgPath,
                        isAllowEdit: false,
                      ),
                    ),
                  ],
                ),
              if (FormUtils.hasValue(signs, 'MEASURES_CONFIRM'))
                Column(
                  children: [
                    SizedBox(height: 20),
                    ListItemFactory.createBuildSimpleSection('其他安全防护措施'),
                    Container(
                      color: Colors.white,
                      child: OtherMeasuresWidget(
                        otherMeasures: signs['MEASURES_CONFIRM'],
                        baseImgPath: ApiService.baseImgPath,
                      ),
                    ),
                  ],
                ),
              SignaturesListWidget(
                signs: signs,
                pd: pd,
                baseImgPath: ApiService.baseImgPath,
              ),
              isEditable
                  ? Row(
                    spacing: 10,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Expanded(
                        child: CustomButton(
                          height: 45,
                          textStyle: TextStyle(
                            fontSize: 16,
                            color: Colors.white,
                          ),
                          text: '提交',
                          backgroundColor: Colors.blue,
                          onPressed: () {
                            _submit('1');
                          },
                        ),
                      ),

                      Expanded(
                        child: CustomButton(
                          textStyle: TextStyle(
                            fontSize: 16,
                            color: Colors.white,
                          ),
                          text: '暂存',
                          backgroundColor: Colors.green,
                          onPressed: () {
                            _submit('0');
                          },
                        ),
                      ),
                    ],
                  )
                  : Column(
                    children: [
                      SizedBox(height: 20),
                      Row(
                        children: [
                          SizedBox(width: 50),
                          Expanded(
                            child: CustomButton(
                              height: 45,
                              textStyle: TextStyle(
                                fontSize: 16,
                                color: Colors.white,
                              ),
                              text: '返回',
                              backgroundColor: Colors.green,
                              onPressed: () {
                                Navigator.pop(context);
                              },
                            ),
                          ),
                          SizedBox(width: 50),
                        ],
                      ),
                    ],
                  ),
            ],
          ),
        ),
      ),
    );
  }
}
