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 ElectricityDetailFormWidget 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? cardController;
  final TextEditingController? powerController;
  final TextEditingController? ratedPowerController;
  final TextEditingController? VController;
  final TextEditingController? relatedController;
  final TextEditingController? riskController;
  const ElectricityDetailFormWidget({
    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.cardController,
    this.powerController,
    this.ratedPowerController,
    this.VController,
    this.relatedController,
    this.riskController,
  }) : assert(
  !isEditable ||
      (contentController != null &&
          locationController != null &&
          cardController != null &&
          powerController != null &&
          ratedPowerController != null &&
          VController != null),
  'Editable mode requires all TextEditingController parameters',
  ),
        super(key: key);

  @override
  State<ElectricityDetailFormWidget> createState() => _ElectricityDetailFormWidgetState();
}

class _ElectricityDetailFormWidgetState extends State<ElectricityDetailFormWidget> {
  @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.singleLineTitleText(
            label: '作业地点：',
            isEditable: widget.isEditable,
            controller: widget.locationController,
            text: pd['WORK_PLACE'] ?? '',
          ),
          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.cardController,
            hintText: '请输入电工证号',
            text: pd['CARD_NO'] ?? '',
          ),
          const Divider(),

          if (FormUtils.hasValue(pd, 'WORK_START_DATE'))
            Column(
              children: [
                ItemListWidget.singleLineTitleText(
                  label: '作业开始时间：',
                  isEditable: false,
                  text: pd['WORK_START_DATE'] ?? '',
                ),
                const Divider(),

              ],
            ),
          if (FormUtils.hasValue(pd, 'WORK_END_DATE'))
            Column(
              children: [
                ItemListWidget.singleLineTitleText(
                  label: '作业结束时间：',
                  isEditable: false,
                  text: pd['WORK_END_DATE'] ?? '',
                ),
                const Divider(),

              ],
            ),

          ItemListWidget.singleLineTitleText(
            label: '电源接入点及许可用电功率：',
            isEditable: widget.isEditable,
            controller: widget.powerController,
            hintText: '请输入电源接入点及许可用电功率',
            text: pd['ALLOW_POWER'] ?? '',
          ),
          const Divider(),
          ItemListWidget.singleLineTitleText(
            label: '用电设备名称及额定功率：',
            isEditable: widget.isEditable,
            controller: widget.ratedPowerController,
            hintText: '请输入用电设备名称及额定功率',
            text: pd['RATED_POWER'] ?? '',
          ),
          const Divider(),
          ItemListWidget.singleLineTitleText(
            label: '工作电压：',
            isEditable: widget.isEditable,
            controller: widget.VController,
            hintText: '请输入工作电压',
            text: pd['WORK_VOLTAGE'] ?? '',
          ),
          const Divider(),
          if (FormUtils.hasValue(pd, 'LEADER_CARD_NO'))
            Column(
              children: [
                ItemListWidget.singleLineTitleText(
                  label: '负责人电工号：',
                  isEditable: false,
                  text: pd['LEADER_CARD_NO'] ?? '',
                ),
                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,
            ),
          ],
        ],
      ),
    );
  }
}
