import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';

import '../../../../../../tools/tools.dart';
import '../../../item_list_widget.dart';
import '../../special_Wrok/MeasuresListWidget.dart';

/// 通用明细表单组件（支持编辑/只读）
class SpaceWorkDetailFormWidget extends StatefulWidget {
  final Map<String, dynamic> pd;
  final bool isEditable;
  late bool isEditSpaceName; // 是否手动输入受限空间名称
  final VoidCallback onChooseLevel;
  final VoidCallback onChooseSpaceName;
  final VoidCallback onAnalyzeTap;
// 新增
  final VoidCallback? onChooseVideoManager;
  /// 选择摄像头
  final VoidCallback? onWorkStartTimeHandle;
  final VoidCallback? onWorkEndTimeHandle;
  /// 承包商
  final VoidCallback? onContractorHandle;
  /// 作业区域
  final VoidCallback? onWorkAreaHandle;
  /// 作业地点经纬度
  final VoidCallback? onWorkAreaLocationHandle;

  /// 编辑模式下需提供以下控制器，非编辑可不传
  final TextEditingController? spaceNameController;
  final TextEditingController? spaceNumberController;
  final TextEditingController? jzController;
  final TextEditingController? contentController;
  final TextEditingController? relatedController;
  final TextEditingController? riskController;

  SpaceWorkDetailFormWidget({
    Key? key,
    required this.pd,
    required this.isEditable,
    required this.onChooseLevel,
    required this.onChooseSpaceName,
    required this.onAnalyzeTap,
    /// 新增
    this.onChooseVideoManager,
    this.onWorkStartTimeHandle,
    this.onWorkEndTimeHandle,
    this.onContractorHandle,
    this.onWorkAreaHandle,
    this.onWorkAreaLocationHandle,

    this.isEditSpaceName = false,  /// 受限空间可选择可手写，默认选择，受限空间编号也要跟着变化
    this.contentController,
    this.spaceNameController,
    this.spaceNumberController,
    this.jzController,
    this.relatedController,
    this.riskController,
  }) : assert(
         !isEditable ||
             (contentController != null &&
                 spaceNameController != null &&
                 jzController != null &&
                 spaceNumberController != null &&
                 relatedController != null &&
                 riskController != null),
         'Editable mode requires all TextEditingController parameters',
       ),
       super(key: key);

  @override
  State<SpaceWorkDetailFormWidget> createState() =>
      _SpaceWorkDetailFormWidgetState();
}

class _SpaceWorkDetailFormWidgetState extends State<SpaceWorkDetailFormWidget> {
  @override
  Widget build(BuildContext context) {
    if (FormUtils.hasValue(widget.pd, 'LATITUDE')) {
      widget.pd['LATITUDE_LONGITUDE'] = '${widget.pd['LATITUDE']},${widget.pd['LONGITUDE']}'; //参数map
    }
    final pd = widget.pd;

    return Container(
      padding: EdgeInsets.symmetric(vertical: 10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(5)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          ItemListWidget.singleLineTitleText(
            label: '申请单位：',
            isEditable: false,
            text: pd['APPLY_DEPARTMENT_NAME'] ?? '',
          ),
          const Divider(),
          ItemListWidget.singleLineTitleText(
            label: '申请人：',
            isEditable: false,
            text: pd['APPLY_USER_NAME'] ?? '',
          ),
          if (FormUtils.hasValue(pd, 'CHECK_NO')) ...[
            const Divider(),
            ItemListWidget.singleLineTitleText(
              label: '编号：',
              isEditable: false,
              text: pd['CHECK_NO'] ?? '',
            ),
          ],
          const Divider(),
          if (!widget.isEditSpaceName)
          ItemListWidget.selectableLineTitleTextRightButton(
            label: '受限空间名称：',
            isEditable: widget.isEditable,
            cleanText: '输入',
            isClean: widget.isEditable,
            text: pd['LIMITSPACE_NAME'] ?? '',
            onTapClean: () {
              setState(() {
                pd['LIMITSPACE_NAME'] = '';
                pd['LIMITSPACE_NUMBER'] = '';

                widget.isEditSpaceName = !widget.isEditSpaceName;
              });
            },
            onTap: widget.onChooseSpaceName,
          ),
          if (widget.isEditSpaceName)
            ItemListWidget.selectableLineTitleTextField(
              label: '受限空间名称：',
              isEditable: widget.isEditable,
              isClean: true,
              cleanText: '选择',
              text: pd['LIMITSPACE_NAME'] ?? '',
              onTapClean: () {
                setState(() {
                  pd['LIMITSPACE_NAME'] = '';
                  pd['LIMITSPACE_NUMBER'] = '';
                  widget.isEditSpaceName = !widget.isEditSpaceName;
                });
              },
              onTap: widget.onChooseSpaceName,
            ),
            if (FormUtils.hasValue(pd, 'LIMITSPACE_NUMBER') || widget.isEditable) ...[
            const Divider(),
            ItemListWidget.singleLineTitleText(
              label: '受限空间编号：',
              isEditable: widget.isEditSpaceName,
              strongRequired: widget.isEditable,
              text: pd['LIMITSPACE_NUMBER'] ?? '',
            ),
          ],
          const Divider(),
          ItemListWidget.singleLineTitleText(
            label: '受限空间内原有介质名称：',
            isEditable: widget.isEditable,
            controller: widget.jzController,
            text: pd['MEDIUM_NAME'] ?? '',
          ),
          const Divider(),

          ItemListWidget.multiLineTitleTextField(
            label: '作业内容：',
            isEditable: widget.isEditable,
            controller: widget.contentController,
            text: pd['WORK_CONTENT'] ?? '',
          ),
          if (FormUtils.hasValue(pd, 'WORK_START_DATE')) ...[
            const Divider(),
            ItemListWidget.selectableLineTitleTextRightButton(
              label: '作业开始时间：',
              isEditable: false,
              onTap: widget.onChooseLevel,
              text: pd['WORK_START_DATE'] ?? '',
            ),
          ],
          if (FormUtils.hasValue(pd, 'WORK_END_DATE')) ...[
            const Divider(),
            ItemListWidget.selectableLineTitleTextRightButton(
              label: '作业结束时间：',
              isEditable: false,
              onTap: widget.onChooseLevel,
              text: pd['WORK_END_DATE'] ?? '',
            ),
          ],
          const Divider(),
          ItemListWidget.twoRowButtonTitleText(
            label: '关联其他特殊作业及安全作业票编号',
            isEditable: widget.isEditable,
            onTap: () async {
              final val = await showDialog<String>(
                context: context,
                builder:
                    (_) => SelectionPopup(
                      type: 'assignments',
                      initialValue: pd['SPECIAL_WORK'] ?? '',
                      onConfirm: (val) {
                        setState(() {
                          pd['SPECIAL_WORK'] = val;
                          widget.relatedController?.text = val;
                        });
                      },
                    ),
              );
              FocusHelper.clearFocus(context);
            },
            hintText: '请输入关联的其他特殊作业及安全作业票编号',
            controller: widget.relatedController,
            text: pd['SPECIAL_WORK'] ?? '',
          ),
          const Divider(),
          ItemListWidget.twoRowButtonTitleText(
            label: '风险辨识结果',
            isEditable: widget.isEditable,
            onTap: () async {
              await showDialog<String>(
                context: context,
                builder:
                    (_) => SelectionPopup(
                      type: 'identification',
                      initialValue: pd['RISK_IDENTIFICATION'] ?? '',
                      onConfirm: (val) {
                        setState(() {
                          pd['RISK_IDENTIFICATION'] = val;
                          widget.riskController?.text = val;
                        });
                      },
                    ),
              );
              FocusHelper.clearFocus(context);
            },
            hintText: '请输入风险辨识结果',
            controller: widget.riskController,
            text: pd['RISK_IDENTIFICATION'] ?? '',
          ),
          const Divider(),
          ItemListWidget.selectableLineTitleTextRightButton(
            label: '视频监控：',
            isClean: widget.isEditable,
            cleanText: '清除监控',
            onTapClean: () {
              setState(() {
                pd['VIDEONAME'] = '';
                pd['VIDEOMANAGER_ID'] = '';
              });
            },
            isRequired: false,
            isEditable: widget.isEditable,
            onTap: widget.onChooseVideoManager ?? () {},
            text: pd['VIDEONAME'] ?? '',
          ),
          const Divider(),
          ItemListWidget.selectableLineTitleTextRightButton(
            label: '预计作业开始时间：',
            isEditable: widget.isEditable,
            onTap: widget.onWorkStartTimeHandle ?? () {},
            text: pd['WORK_EXPECTED_START_TIME'] ?? '',
          ),
          const Divider(),
          ItemListWidget.selectableLineTitleTextRightButton(
            label: '预计作业结束时间：',
            isEditable: widget.isEditable,
            onTap: widget.onWorkEndTimeHandle ?? () {},
            text: pd['WORK_EXPECTED_END_TIME'] ?? '',
          ),
          const Divider(),
          ListItemFactory.createYesNoSection(
            verticalPadding: 0,
            horizontalPadding: 0,
            title: '是否承包商作业',
            isEdit: widget.isEditable,
            text: widget.pd['IS_CONTRACTOR_WORK'] == '1' ? '是' : '否',
            isRequired: true,
            groupValue: widget.pd['IS_CONTRACTOR_WORK'] == '1',
            onChanged: (bool value) {
              setState(() {
                widget.pd['IS_CONTRACTOR_WORK'] = value ? '1' : "0";
              });
            },
          ),
          if (pd['IS_CONTRACTOR_WORK'] == '1')
            Column(
              children: [
                const Divider(),
                ItemListWidget.selectableLineTitleTextRightButton(
                  label: '承包商：',
                  isEditable: widget.isEditable,
                  onTap: widget.onContractorHandle ?? () {},
                  text: pd['UNITS_NAME'] ?? '',
                ),
              ],
            ),
          const Divider(),

          ItemListWidget.selectableLineTitleTextRightButton(
            label: '作业区域：',
            isEditable: widget.isEditable,
            onTap: widget.onWorkAreaHandle ?? () {},
            text: pd['PLS_NAME'] ?? '',
          ),
          const Divider(),

          ItemListWidget.twoRowButtonTitleText(
            label: '作业地点经纬度',
            isInput: false,
            isEditable: widget.isEditable,
            buttonText: '定位',
            onTap: widget.onWorkAreaLocationHandle ?? (){},
            hintText: '',
            text: pd['LATITUDE_LONGITUDE'] ?? (widget.isEditable ? '' : '无'),
          ),
          if (FormUtils.hasValue(pd, 'ANALYZE_TIME')) ...[
            const Divider(),
            ItemListWidget.OneRowButtonTitleText(
              label: '分析人：',
              text: pd['ANALYZE_USER_NAME'] ?? '',
              onTap: widget.onAnalyzeTap,
            ),
          ],
        ],
      ),
    );
  }
}
