import 'dart:convert';

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

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

class MBCD_data_model {
  String BOARD_MATERIAL;
  String BOARD_SPECIFICATION;
  String BOARD_NO;

  MBCD_data_model({
    required this.BOARD_MATERIAL,
    required this.BOARD_SPECIFICATION,
    required this.BOARD_NO,
  });

  factory MBCD_data_model.fromJson(Map<String, dynamic> json) {
    return MBCD_data_model(
      BOARD_MATERIAL: json['BOARD_MATERIAL'] as String? ?? '',
      BOARD_SPECIFICATION: json['BOARD_SPECIFICATION'] as String? ?? '',
      // 修复：这里应该读取 BOARD_NO，而不是 BOARD_SPECIFICATION
      BOARD_NO: json['BOARD_NO'] as String? ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'BOARD_MATERIAL': BOARD_MATERIAL,
      'BOARD_SPECIFICATION': BOARD_SPECIFICATION,
      'BOARD_NO': BOARD_NO,
    };
  }
}

/// 通用盲板作业明细表单组件（支持编辑/只读）
class BlindboardDetailFormWidget extends StatefulWidget {
  final Map<String, dynamic> pd;
  final List<dynamic> boardList;

  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? nameController; // 名称
  /// 管道参数
  final TextEditingController? mediumController; // 介质
  final TextEditingController? temperatureController; // 温度
  final TextEditingController? pressureController; // 压力
  final TextEditingController? relatedController;
  final TextEditingController? riskController;

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

    this.nameController,
    this.mediumController,
    this.temperatureController,
    this.pressureController,
    this.relatedController,
    this.riskController,
  }) : assert(
         !isEditable ||
             (nameController != null &&
                 mediumController != null &&
                 temperatureController != null &&
                 pressureController != null &&
                 relatedController != null &&
                 riskController != null),
         'Editable mode requires all TextEditingController parameters',
       ),
       super(key: key);

  @override
  State<BlindboardDetailFormWidget> createState() =>
      _BlindboardDetailFormWidgetState();
}

class _BlindboardDetailFormWidgetState
    extends State<BlindboardDetailFormWidget> {
  /// 盲板抽堵参数
  late final List<Map<String, dynamic>> boardList;

  String _getWorkLevelText(dynamic level) {
    switch (level?.toString()) {
      case '1':
        return '堵盲板';
      case '2':
        return '抽盲板';
      default:
        return '';
    }
  }

  @override
  Widget build(BuildContext context) {
    final boardList = widget.boardList;
    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: false,
            text: pd['APPLY_DEPARTMENT_NAME'] ?? '',
          ),
          const Divider(),
          ItemListWidget.singleLineTitleText(
            label: '申请人：',
            isEditable: false,
            text: pd['APPLY_USER_NAME'] ?? '',
          ),
          const Divider(),
          ItemListWidget.selectableLineTitleTextRightButton(
            label: '作业方式：',
            isEditable: widget.isEditable,
            onTap: widget.onChooseLevel,
            text: _getWorkLevelText(pd['WORK_TYPE']),
          ),
          const Divider(),
          ItemListWidget.singleLineTitleText(
            label: '设备管道名称：',
            isEditable: widget.isEditable,
            controller: widget.nameController,
            text: pd['NAME'] ?? '',
          ),
          const Divider(),
          ListItemFactory.createBuildSimpleSection('管道参数'),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 10),
            child: Column(
              children: [
                ItemListWidget.singleLineTitleText(
                  label: '介质：',
                  isEditable: widget.isEditable,
                  controller: widget.mediumController,
                  text: pd['MEDIUM'] ?? '',
                ),
                const Divider(),
                ItemListWidget.singleLineTitleText(
                  label: '温度：',
                  isEditable: widget.isEditable,
                  controller: widget.temperatureController,
                  text: pd['TEMPERATURE'] ?? '',
                ),
                const Divider(),
                ItemListWidget.singleLineTitleText(
                  label: '压力：',
                  isEditable: widget.isEditable,
                  controller: widget.pressureController,
                  text: pd['PRESSURE'] ?? '',
                ),
              ],
            ),
          ),

          const Divider(),
          ...boardList.map((board) {
            return Container(
              padding: EdgeInsets.symmetric(horizontal: 10),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      ListItemFactory.createBuildSimpleSection('盲板抽堵参数', horPadding: 0),
                      if (widget.isEditable)
                        CustomButton(
                          onPressed: () {
                            setState(() {
                              if (boardList.indexOf(board) == 0) {
                                boardList.add({
                                  'BOARD_MATERIAL': '',
                                  'BOARD_SPECIFICATION': '',
                                  'BOARD_NO': '',
                                });
                              } else {
                                boardList.remove(board);
                              }
                            });
                          },
                          text: boardList.indexOf(board) == 0 ? '添加' : '删除',
                          backgroundColor:
                              boardList.indexOf(board) == 0
                                  ? Colors.blue
                                  : Colors.red,
                          padding: EdgeInsets.symmetric(
                            horizontal: 15,
                            vertical: 2,
                          ),
                          height: 30,
                          borderRadius: 15,
                        ),
                    ],
                  ),
                  ItemListWidget.singleLineTitleText(
                    label: '材质：',
                    isEditable: widget.isEditable,
                    text: board['BOARD_MATERIAL'],
                    hintText: '请输入材质',
                    onChanged: (val) {
                      setState(() {
                        board['BOARD_MATERIAL'] = val;
                      });
                    },
                    isRequired: false,
                  ),
                  const Divider(),

                  ItemListWidget.singleLineTitleText(
                    label: '规格：',
                    isEditable: widget.isEditable,
                    text: board['BOARD_SPECIFICATION'],
                    onChanged: (val) {
                      setState(() {
                        board['BOARD_SPECIFICATION'] = val;
                      });
                    },
                    hintText: '请输入规格',
                    isRequired: false,
                  ),
                  const Divider(),

                  ItemListWidget.singleLineTitleText(
                    label: '编号：',
                    isEditable: widget.isEditable,
                    text: board['BOARD_NO'],
                    onChanged: (val) {
                      setState(() {
                        board['BOARD_NO'] = val;
                      });
                    },
                    hintText: '请输入编号',
                    isRequired: false,
                  ),
                  if (boardList.indexOf(board) != boardList.length-1)
                    const Divider(),

                ],
              ),
            );
          }),
          const Divider(),
          if (!widget.isEditable && FormUtils.hasValue(pd, 'BOARD_PATH')) ...[
            ItemListWidget.singleLineTitleText(
              label: '盲板抽堵位置及安全措施：',
              isEditable: false,
              text:'',
            ),
            const Divider(),

          ],
          if (!widget.isEditable && FormUtils.hasValue(pd, 'BOARD_PATH')) ...[
            ItemListWidget.twoRowTitleAndImages(
              onTapCallBack: (val) {
                presentOpaque(SingleImageViewer(imageUrl: val), context);
              },
              title: '断路地段示意图：',
              imageUrls: pd['BOARD_PATH'],
            ),
            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 ? '' : '无'),
          ),
        ],
      ),
    );
  }
}
