import 'dart:math' as math;

import 'package:flutter/material.dart';
import '../../../../../../customWidget/ItemWidgetFactory.dart';
import '../../../../../../customWidget/single_image_viewer.dart';
import '../../../../../../tools/tools.dart';
import '../../special_Wrok/MeasuresListWidget.dart';
import 'SpaceWorkDetailFormWidget.dart';

class SpecialWorkFormBaseWork extends StatelessWidget {
  /// 基础数据
  final Map<String, dynamic> pd;

  /// 安全防护措施列表
  final List<Map<String, dynamic>> measuresList;

  /// 其他签字数据
  final Map<String, dynamic> signs;

  /// 图片前缀
  final String baseImgPath;

  /// 是否可编辑
  final bool isEditable;

  /// 回调：选择级别
  final VoidCallback onChooseLevel;

  /// 回调：选择动火作业人员
  final VoidCallback onChooseSpaceName;

  /// 回调：分析按钮
  final VoidCallback onAnalyzeTap;

  const SpecialWorkFormBaseWork({
    Key? key,
    required this.pd,
    required this.measuresList,
    required this.signs,
    required this.baseImgPath,
    this.isEditable = false,
    required this.onChooseLevel,
    required this.onChooseSpaceName,
    required this.onAnalyzeTap,
  }) : super(key: key);

  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,
    );
  }

  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(pd, nameKey))
                  Text(
                    pd[nameKey]?.toString() ?? '',
                    style: const TextStyle(fontSize: 16),
                  ),
              ],
            ),
          ),
          const SizedBox(height: 8),

          if (FormUtils.hasValue(signs, signKey))
            ...((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 = '$baseImgPath$p';
                          return GestureDetector(
                            onTap: () => SingleImageViewer(imageUrl: fullUrl),
                            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 = '$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()),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      spacing: 12,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 1. 作业详情表单
        SpaceWorkDetailFormWidget(
          pd: pd,
          isEditable: isEditable,
          onChooseLevel: onChooseLevel,
          onChooseSpaceName: onChooseSpaceName,
          onAnalyzeTap: onAnalyzeTap,
        ),

        // 2. 安全防护措施
        if (measuresList.isNotEmpty)
          _itemContainer(
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                ListItemFactory.createBuildSimpleSection('安全防护措施'),
                MeasuresListWidget(
                  measuresList: measuresList,
                  baseImgPath: baseImgPath,
                  isAllowEdit: isEditable,
                  isShowSign: true,
                ),
              ],
            ),
          ),

        // 3. 其他安全防护措施
        if (FormUtils.hasValue(signs, 'MEASURES_CONFIRM'))
          _itemContainer(
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                ListItemFactory.createBuildSimpleSection('其他安全防护措施'),
                OtherMeasuresWidget(
                  otherMeasures: signs['MEASURES_CONFIRM'],
                  baseImgPath: baseImgPath,
                ),
              ],
            ),
          ),

        // 4. 各环节签字及意见
        if (FormUtils.hasValue(signs, 'GUARDIAN'))
          signItemWidget('GUARDIAN', 'GUARDIAN_USER_NAME', '监护人', context),

        if (FormUtils.hasValue(signs, 'CONFESS'))
          signItemWidget('CONFESS', 'CONFESS_USER_NAME', '安全交底人', context),

        if (FormUtils.hasValue(signs, 'ACCEPT_CONFESS'))
          signItemWidget('ACCEPT_CONFESS', 'ACCEPT_CONFESS_USER_NAME', '接受交底人', context),

        // 作业负责人意见
        if (FormUtils.hasValue(signs, 'CONFIRM')) ...[
          Column(
            children: [
              _itemContainer(
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(padding: EdgeInsets.symmetric(horizontal: 8), child: ListItemFactory.headerTitle('作业负责人意见'),),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(signs['CONFIRM'][0]['DESCR'] ?? ''),
                    ),
                  ],
                ),
              ),
              Divider(height: 1,),
              signItemWidget('CONFIRM', 'CONFIRM_USER_NAME', '作业负责人', context),
            ],
          )

        ],

        // 所在单位负责人意见
        if (FormUtils.hasValue(signs, 'LEADER')) ...[
          Column(
            children: [
              _itemContainer(
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(padding: EdgeInsets.symmetric(horizontal: 8), child: ListItemFactory.headerTitle('所在单位意见'),),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(signs['LEADER'][0]['DESCR'] ?? ''),
                    ),
                  ],
                ),
              ),
              Divider(height: 1,),
              signItemWidget('LEADER', 'LEADER_USER_NAME', '所在单位负责人', context),
            ],
          )
        ],

        // 安全管理部门负责人意见
        if (FormUtils.hasValue(signs, 'AUDIT')) ...[
          Column(
            children: [
              _itemContainer(
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(padding: EdgeInsets.symmetric(horizontal: 8), child: ListItemFactory.headerTitle('安全管理部门意见'),),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(signs['AUDIT'][0]['DESCR'] ?? ''),
                    ),
                  ],
                ),
              ),
              Divider(height: 1,),
              signItemWidget('AUDIT', 'AUDIT_USER_NAME', '安全管理部门负责人', context),
            ],
          )
        ],

        // 动火审批人意见
        if (FormUtils.hasValue(signs, 'APPROVE')) ...[
          Column(
            children: [
              _itemContainer(
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(padding: EdgeInsets.symmetric(horizontal: 8), child: ListItemFactory.headerTitle('动火审批人意见'),),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(signs['APPROVE'][0]['DESCR'] ?? ''),
                    ),
                  ],
                ),
              ),
              Divider(height: 1,),
              signItemWidget('APPROVE', 'APPROVE_USER_NAME', '动火审批人', context),
            ],
          )
        ],

        // 作业开始负责人签字
        if (FormUtils.hasValue(signs, 'MONITOR'))
          signItemWidget('MONITOR', 'MONITOR_USER_NAME', '动火前在岗班长', context),

        // 作业开始负责人签字
        if (FormUtils.hasValue(signs, 'WORK_START'))
          signItemWidget('WORK_START', 'WORK_START_USER_NAME', '作业开始负责人', context),

        // 作业结束负责人签字
        if (FormUtils.hasValue(signs, 'WORK_END'))
          signItemWidget('WORK_END', 'WORK_END_USER_NAME', '作业结束负责人', context),

        // 完工验收意见和签字
        if (FormUtils.hasValue(signs, 'ACCEPT')) ...[
          Column(
            children: [
              _itemContainer(
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(padding: EdgeInsets.symmetric(horizontal: 8), child: ListItemFactory.headerTitle('完工验收意见'),),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(signs['ACCEPT'][0]['DESCR'] ?? ''),
                    ),
                  ],
                ),
              ),
              Divider(height: 1,),
              signItemWidget('ACCEPT', 'ACCEPT_USER_NAME', '验收部门负责人', context),
            ],
          )
        ],
      ],
    );
  }
}
