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 HighWorkDetailFormWidget extends StatefulWidget {
  final Map<String, dynamic> pd;
  final bool isEditable;
  final VoidCallback onChooseLevel;
// 新增
  final VoidCallback? onChooseVideoManager;
  /// 选择摄像头
  final VoidCallback? onWorkStartTimeHandle;
  final VoidCallback? onWorkEndTimeHandle;
  /// 承包商
  final VoidCallback? onContractorHandle;
  /// 作业区域
  final VoidCallback? onWorkAreaHandle;
  /// 作业地点经纬度
  final VoidCallback? onWorkAreaLocationHandle;

  /// 编辑模式下需提供以下控制器，非编辑模式可不传
  final TextEditingController? locationController; // 地点
  final TextEditingController? hightController;    // 高度
  final TextEditingController? contentController;  // 内容、
  final TextEditingController? relatedController;
  final TextEditingController? riskController;

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

    this.locationController,
    this.hightController,
    this.contentController,
    this.relatedController,
    this.riskController,
  }) : assert(
  !isEditable ||
      (locationController != null &&
          hightController != null &&
          contentController != null &&
          relatedController != null &&
          riskController != null),
  'Editable mode requires all TextEditingController parameters',
  ),
        super(key: key);

  @override
  State<HighWorkDetailFormWidget> createState() => _HighWorkDetailFormWidgetState();
}

class _HighWorkDetailFormWidgetState extends State<HighWorkDetailFormWidget> {
  String _getWorkLevelText(dynamic level) {
    switch (level?.toString()) {
      case '1': return 'I级高处作业';
      case '2': return 'II级高处作业';
      case '3': return 'III级高处作业';
      case '4': return 'IV级高处作业';
      default:  return '';
    }
  }

  @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: const EdgeInsets.symmetric(vertical: 10),
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(5)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          if (!widget.isEditable && FormUtils.hasValue(pd, 'CHECK_NO')) ...[
            ItemListWidget.singleLineTitleText(
              label: '编号：',
              isEditable: false,
              text: pd['CHECK_NO'] ?? '',
            ),
            const Divider(),
          ],
          ItemListWidget.singleLineTitleText(
            label: '作业地点：',
            isEditable: widget.isEditable,
            controller: widget.locationController,
            text: pd['WORK_PLACE'] ?? '',
          ),
          const Divider(),
          ItemListWidget.singleLineTitleText(
            label: '作业高度（米）：',
            keyboardType: TextInputType.numberWithOptions(
              decimal: true,     // 允许小数点
              signed: false,     // 允许负号（如需）
            ),
            isEditable: widget.isEditable,
            controller: widget.hightController,
            text: pd['WORK_HIGH'] ?? '',
          ),
          const Divider(),
          ItemListWidget.selectableLineTitleTextRightButton(
            label: '高处作业级别：',
            isEditable: widget.isEditable,
            onTap: widget.onChooseLevel,
            text: _getWorkLevelText(pd['WORK_LEVEL']),
          ),
          const Divider(),
          ItemListWidget.multiLineTitleTextField(
            label: '作业内容：',
            isEditable: widget.isEditable,
            controller: widget.contentController,
            text: pd['WORK_CONTENT'] ?? '',
          ),

          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: (v) {
                    setState(() {
                      pd['SPECIAL_WORK'] = v;
                      widget.relatedController?.text = v;
                    });
                  },
                ),
              );
              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: (v) {
                    setState(() {
                      pd['RISK_IDENTIFICATION'] = v;
                      widget.riskController?.text = v;
                    });
                  },
                ),
              );
              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 ? '' : '无'),
          ),
        ],
      ),
    );
  }
}
