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 HotWorkDetailFormWidget extends StatefulWidget {
  final Map<String, dynamic> pd;
  final bool isEditable;
  final VoidCallback onChooseLevel;
  final VoidCallback onChooseHotworkUser;
  final VoidCallback onAnalyzeTap;



  // 新增
  final VoidCallback? onChooseVideoManager;
  /// 选择摄像头
  final VoidCallback? onWorkStartTimeHandle;
  final VoidCallback? onWorkEndTimeHandle;
  /// 承包商
  final VoidCallback? onContractorHandle;
  /// 作业区域
  final VoidCallback? onWorkAreaHandle;
  /// 作业地点经纬度
  final VoidCallback? onWorkAreaLocationHandle;


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

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

    this.contentController,
    this.locationController,
    this.methodController,
    this.hotworkPersonController,
    this.relatedController,
    this.riskController,

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

  @override
  State<HotWorkDetailFormWidget> createState() =>
      _HotWorkDetailFormWidgetState();
}

class _HotWorkDetailFormWidgetState extends State<HotWorkDetailFormWidget> {
  bool IS_CONTRACTOR_WORK = false;
  @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: [
          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(),
          ItemListWidget.multiLineTitleTextField(
            label: '作业内容：',
            isEditable: widget.isEditable,
            controller: widget.contentController,
            text: pd['WORK_CONTENT'] ?? '',
          ),

          const Divider(),
          ItemListWidget.singleLineTitleText(
            label: '动火地点及动火部位：',
            isEditable: widget.isEditable,
            controller: widget.locationController,
            text: pd['WORK_PLACE'] ?? '',
          ),
          const Divider(),
          ItemListWidget.selectableLineTitleTextRightButton(
            label: '动火作业级别：',
            isEditable: widget.isEditable,
            onTap: widget.onChooseLevel,
            text: pd['WORK_LEVEL'] ?? '',
          ),

          const Divider(),
          ItemListWidget.singleLineTitleText(
            label: '动火方式：',
            isEditable: widget.isEditable,
            controller: widget.methodController,
            text: pd['WORK_FUNCTION'] ?? '',
          ),
          if (pd['WORK_START_DATE']?.toString().isNotEmpty == true) ...[
            const Divider(),
            ItemListWidget.singleLineTitleText(
              label: '动火作业实施时间：',
              isEditable: false,
              text: '${pd['WORK_START_DATE']} 至 ${pd['WORK_END_DATE'] ?? '--'}',
            ),
          ],
          const Divider(),
          ItemListWidget.twoRowSelectableTitleText(
            label: '动火人及证书编号：',
            isEditable: widget.isEditable,
            onTap: widget.onChooseHotworkUser,
            text: pd['WORK_USER'] ?? '',
            controller: widget.hotworkPersonController,
          ),
          const Divider(),
          ItemListWidget.twoRowButtonTitleText(
            label: '关联其他特殊作业及安全作业票编号',
            isEditable: widget.isEditable,
            onTap: () async {
              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 && (pd['WORK_LEVEL'] == '一级' || pd['WORK_LEVEL'] == '二级'),
            cleanText: '清除监控',
            isRequired: pd['WORK_LEVEL'] == '特级',
            isEditable: widget.isEditable,
            onTapClean: () {
              setState(() {
                pd['VIDEONAME'] = '';
                pd['VIDEOMANAGER_ID'] = '';
              });
            },
            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,
            ),
          ],
        ],
      ),
    );
  }
}
