import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/tools/h_colors.dart';

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

/// 通用动土作业明细表单组件（支持编辑/只读）
class BreakgroundDetailFormWidget extends StatefulWidget {
  final Map<String, dynamic> pd;
  final bool isEditable;
  final VoidCallback onChooseLevel;
  final Map<String, dynamic> signs;

  /// 编辑模式下需提供以下控制器，非编辑模式可不传
  final TextEditingController? locationController; // 地点
  final TextEditingController? contentController; // 内容
  final TextEditingController? relatedController;
  final TextEditingController? riskController;
// 新增
  final VoidCallback? onChooseVideoManager;
  /// 选择摄像头
  final VoidCallback? onWorkStartTimeHandle;
  final VoidCallback? onWorkEndTimeHandle;
  /// 承包商
  final VoidCallback? onContractorHandle;
  /// 作业区域
  final VoidCallback? onWorkAreaHandle;
  /// 作业地点经纬度
  final VoidCallback? onWorkAreaLocationHandle;

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

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

  @override
  State<BreakgroundDetailFormWidget> createState() =>
      _BreakgroundDetailFormWidgetState();
}

class _BreakgroundDetailFormWidgetState
    extends State<BreakgroundDetailFormWidget> {
  Widget signItemWidget(
    String signKey,
    String nameKey,
    String name,
    BuildContext context,
  ) {
    return _itemContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题行
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
            child: Row(
              children: [
                Expanded(child: ListItemFactory.headerTitle(name)),
                if (FormUtils.hasValue(widget.pd, nameKey))
                  Text(
                    widget.pd[nameKey]?.toString() ?? '',
                    style: const TextStyle(fontSize: 16),
                  ),
              ],
            ),
          ),
          const SizedBox(height: 8),

          if (FormUtils.hasValue(widget.signs, signKey))
            ...((widget.signs[signKey] as List<dynamic>)
                .cast<Map<String, dynamic>>()
                .map((item) {
                  // 解析 SIGN_PATH
                  List<String> signPaths = [];
                  final rawSP =
                      FormUtils.hasValue(item, 'SIGN_PATH')
                          ? item['SIGN_PATH']
                          : null;
                  if (rawSP is String && rawSP.isNotEmpty) {
                    signPaths = rawSP.split(',').map((s) => s.trim()).toList();
                  } else if (rawSP is List) {
                    signPaths = rawSP.cast<String>();
                  }

                  // 解析 SIGN_TIME 保留空格
                  List<String> signTimes = [];
                  final rawST =
                      FormUtils.hasValue(item, 'SIGN_TIME')
                          ? item['SIGN_TIME']
                          : null;
                  if (rawST is String && rawST.isNotEmpty) {
                    signTimes = rawST.split(',');
                  } else if (rawST is List) {
                    signTimes = rawST.cast<String>();
                  }

                  final pairCount = math.min(
                    signPaths.length,
                    signTimes.length,
                  );

                  // 解析 IMG_PATH, 最多 2 张
                  List<String> imgPaths = [];
                  final rawIP =
                      FormUtils.hasValue(item, 'IMG_PATH')
                          ? item['IMG_PATH']
                          : null;
                  if (rawIP is String && rawIP.isNotEmpty) {
                    imgPaths =
                        rawIP.split(',').map((s) => s.trim()).take(2).toList();
                  } else if (rawIP is List) {
                    imgPaths = rawIP.cast<String>().take(2).toList();
                  }

                  return Padding(
                    padding: const EdgeInsets.symmetric(
                      vertical: 8.0,
                      horizontal: 10,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        if (imgPaths.isNotEmpty) ...[
                          Row(
                            children:
                                imgPaths.map((p) {
                                  final fullUrl = '${ApiService.baseImgPath}$p';
                                  return GestureDetector(
                                    onTap:
                                        () => presentOpaque(
                                          SingleImageViewer(imageUrl: fullUrl),
                                          context,
                                        ),
                                    child: Padding(
                                      padding: const EdgeInsets.only(
                                        right: 8.0,
                                      ),
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.circular(2),
                                        child: Image.network(
                                          fullUrl,
                                          width: 50,
                                          height: 50,
                                          fit: BoxFit.fill,
                                          errorBuilder:
                                              (_, __, ___) => const Icon(
                                                Icons.broken_image,
                                                size: 40,
                                              ),
                                        ),
                                      ),
                                    ),
                                  );
                                }).toList(),
                          ),
                          const SizedBox(height: 8),
                        ],

                        // 签名及时间
                        ...List.generate(pairCount, (index) {
                          final imgPath = signPaths[index];
                          final timeLabel = signTimes[index];
                          final fullUrl = '${ApiService.baseImgPath}$imgPath';
                          const imageWidth = 200.0;
                          const imageHeight = 100.0;

                          return Padding(
                            padding: const EdgeInsets.symmetric(vertical: 8.0),
                            child: Column(
                              children: [
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    GestureDetector(
                                      onTap:
                                          () => presentOpaque(
                                            SingleImageViewer(
                                              imageUrl: fullUrl,
                                            ),
                                            context,
                                          ),
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.circular(4),
                                        child: Image.network(
                                          fullUrl,
                                          width: imageWidth,
                                          height: imageHeight,
                                          fit: BoxFit.fill,
                                          errorBuilder:
                                              (_, __, ___) => const Icon(
                                                Icons.broken_image,
                                                size: 60,
                                              ),
                                        ),
                                      ),
                                    ),
                                    const SizedBox(width: 12),
                                    Expanded(
                                      child: SizedBox(
                                        height: imageHeight,
                                        child: Align(
                                          alignment: Alignment.bottomRight,
                                          child: Text(
                                            timeLabel,
                                            style: const TextStyle(
                                              fontSize: 14,
                                              color: Colors.black87,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                if (index < pairCount - 1)
                                  const Padding(
                                    padding: EdgeInsets.only(top: 8.0),
                                    child: Divider(height: 1),
                                  ),
                              ],
                            ),
                          );
                        }),
                      ],
                    ),
                  );
                })
                .toList()),
        ],
      ),
    );
  }

  Widget _itemContainer(Widget child) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 8),
      child: child,
    );
  }

  @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(),
          ],
          if (
              FormUtils.hasValue(pd, 'APPLY_DEPARTMENT_NAME')) ...[
            ItemListWidget.singleLineTitleText(
              label: '申请部门：',
              isEditable: false,
              text: pd['APPLY_DEPARTMENT_NAME'] ?? '',
            ),
            const Divider(),
          ],

          ItemListWidget.singleLineTitleText(
            label: '作业地点：',
            isEditable: widget.isEditable,
            controller: widget.locationController,
            hintText: '请输入作业地点',
            text: pd['WORK_PLACE'] ?? '',
          ),
          const Divider(),
          ItemListWidget.multiLineTitleTextField(
            label: '作业内容：',
            isEditable: widget.isEditable,
            controller: widget.contentController,
            hintText: '请输入作业内容',
            text: pd['JOB_CONTENT'] ?? '',
          ),
          const Divider(),
          if (FormUtils.hasValue(pd, 'WORK_CONTENT')) ...[
            ItemListWidget.singleLineTitleText(
              label: '作业内容、范围、方式：',
              isEditable: false,
              text: pd['WORK_CONTENT'] ?? '',
            ),
            const Divider(),
          ],
          if (FormUtils.hasValue(pd, 'CONTENT_IMG_PATH')) ...[
            ItemListWidget.singleLineTitleText(
              label: '作业内容、范围、方式简图：',
              isEditable: false,
              text: '',
            ),
            SizedBox(height: 5,),
            Padding(padding: EdgeInsets.symmetric(horizontal: 12), child: Row(
              crossAxisAlignment: CrossAxisAlignment.end, // 对齐到底部
              children: List.generate(pd['CONTENT_IMG_PATH'].length, (index) {
                final fullUrl =
                    ApiService.baseImgPath + pd['CONTENT_IMG_PATH'][index];
                return Container(
                  margin: const EdgeInsets.only(right: 20), // 右侧 20px 间隔
                  width: 60,
                  height: 60,
                  child: GestureDetector(
                    onTap: () {
                      presentOpaque(SingleImageViewer(imageUrl: fullUrl), context);
                    },
                    child: Image.network(fullUrl, fit: BoxFit.fill),
                  ),
                );
              }),
            ),),
            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 ? '' : '无'),
          ),
          // 作业人签字
          if (FormUtils.hasValue(widget.signs, 'WORK_USER'))
            Column(
              children: [
                Container(height: 10,width: double.maxFinite,color: h_backGroundColor(),),
                signItemWidget('WORK_USER', 'WORK_USER_USER_NAME', '作业人', context),
              ],
            )

        ],
      ),
    );
  }
}
