// safe_check_form_view.dart
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/custom_alert_dialog.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/dotted_border_box.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/KeyProjects/SafeCheck/custom/MultiTextFieldWithTitle.dart';
import 'package:qhd_prevention/pages/KeyProjects/SafeCheck/custom/safeCheck_table.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/tools/tools.dart';

class SafeCheckFormView extends StatefulWidget {
  const SafeCheckFormView({
    Key? key,
    required this.form,
    required this.isEdit,
    required this.onHiddenShow,
  }) : super(key: key);

  // === 数据 ===
  final Map<String, dynamic> form;
  final bool isEdit;

  /// 显示隐患详情（点击）
  final void Function(Map<String, dynamic> item, int idx) onHiddenShow;

  @override
  _SafeCheckFormViewState createState() => _SafeCheckFormViewState();
}

class _SafeCheckFormViewState extends State<SafeCheckFormView> {
  /// 将 widget.form['situationList'] 转为 MultiTextFieldWithTitle 需要的 List<String>
  List<String> _situationListToStrings() {
    final List<dynamic> cur = List<dynamic>.from(
      widget.form['situationList'] ?? [],
    );
    if (cur.isEmpty) return ['']; // 保持至少一行，和 uni-app 行为一致
    return cur.map((e) {
      if (e is Map && e['SITUATION'] != null) return e['SITUATION'].toString();
      if (e is String) return e;
      return '';
    }).toList();
  }

  Widget _personUnitItem(Map item, int index) {
    return Stack(
      children: [
        Container(
          padding: EdgeInsets.symmetric(vertical: 5),
          child: DottedBorderBox(
            child: SizedBox(
              child: Column(
                children: [
                  ItemListWidget.selectableLineTitleTextRightButton(
                    isRequired: false,
                    label: '${index + 1}.检查人员单位：',
                    isEditable: false,
                    onTapClean: () {
                      setState(() {});
                    },
                    text: item['INSPECTION_DEPARTMENT_NAME'] ?? '请选择',
                  ),
                  Divider(),
                  ItemListWidget.selectableLineTitleTextRightButton(
                    isRequired: false,
                    label: '${index + 1}.检查人员：',
                    isEditable: false,
                    text: item['INSPECTION_USER_NAME'] ?? '请选择',
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
    // 删除按钮（叠加在左上角）
  }

  Widget _checkItem(Map item, int index) {
    return Column(
      children: [
        const SizedBox(height: 10),
        ItemListWidget.singleLineTitleText(
          label: '检查人员核查结果：',
          isEditable: false,
          text: '',
        ),
        const Divider(),
        ItemListWidget.multiLineTitleTextField(
          label: '检查人意见',
          isEditable: false,
          text: item['INSPECTION_USER_OPINION'] ?? '',
        ),
        const Divider(),
        ItemListWidget.OneRowImageTitle(
          label: '检查人签字',
          text: item['INSPECTION_USER_SIGN_TIME'],
          onTapCallBack: (path) {
            presentOpaque(SingleImageViewer(imageUrl: path), context);
          },
          imgPath: item['INSPECTION_USER_SIGN_IMG'],
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final form = widget.form;
    final isEdit = widget.isEdit;
    List<dynamic> inspectorList = widget.form['inspectorList'] ?? [];
    List<dynamic> inspectorVerifyList =
        widget.form['inspectorVerifyList'] ?? widget.form['inspectorList'];

    return SizedBox(
      // padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
      child: Column(
        children: [
          // 顶部表单区容器
          ItemListWidget.itemContainer(
            horizontal: 0,
            Column(
              children: [
                // 检查题目选择（示例复用你项目的 ListItemFactory）
                ListItemFactory.createYesNoSection(
                  title: '检查题目：',
                  groupValue:
                      (form['INSPECTION_CATEGORY']?.toString() ?? '')
                                  .toLowerCase() ==
                              '安全'
                          ? true
                          : (form['INSPECTION_CATEGORY']?.toString() ?? '')
                                  .toLowerCase() ==
                              '综合'
                          ? false
                          : null,
                  yesLabel: '安全',
                  noLabel: '综合',
                  isEdit: isEdit,
                  isRequired: true,
                  horizontalPadding: 5,
                  verticalPadding: 0,
                  text: '${form['INSPECTION_SUBJECT'] ?? ''}现场检查记录',

                  onChanged: (val) {
                    // 如果需要把选择写回 form，可以在这里 setState 更新 widget.form
                    // setState(() { widget.form['INSPECTION_CATEGORY'] = val ? '安全' : '综合'; });
                  },
                ),

                const Divider(),
                ItemListWidget.singleLineTitleText(
                  label: '被检查单位：',
                  isEditable: false,
                  text: form['INSPECTED_DEPARTMENT_NAMES'] ?? '',
                ),
                const Divider(),

                ItemListWidget.selectableLineTitleTextRightButton(
                  label: '被检查单位现场负责人:',
                  isEditable: isEdit,
                  text: form['INSPECTED_SITEUSER_NAME'] ?? '',
                ),
                const Divider(),

                ItemListWidget.singleLineTitleText(
                  label: '检查场所：',
                  isEditable: isEdit,
                  text: form['INSPECTION_PLACE'],
                  hintText: '请输入检查场所',
                  onChanged: (val) {
                    // 可选择写回 form
                    // setState(() { widget.form['INSPECTION_PLACE'] = val; });
                  },
                ),
                const Divider(),

                ItemListWidget.selectableLineTitleTextRightButton(
                  label: '检查类型:',
                  isEditable: isEdit,
                  text: form['INSPECTION_TYPE_NAME'] ?? '',
                ),
                const Divider(),

                ItemListWidget.selectableLineTitleTextRightButton(
                  label: '检查开始时间:',
                  isEditable: isEdit,
                  text: form['INSPECTION_TIME_START'] ?? '',
                  onTap: () {},
                ),
                const Divider(),

                ItemListWidget.selectableLineTitleTextRightButton(
                  label: '检查结束时间:',
                  isEditable: isEdit,
                  text: form['INSPECTION_TIME_END'] ?? '',
                  onTap: () {},
                ),

                const Divider(),

                // MultiTextFieldWithTitle（检查情况），外部通过 onMultiTextsChanged 更新 form['situationList']
                MultiTextFieldWithTitle(
                  label: "检查情况",
                  isEditable: isEdit,
                  hintText: "请输入检查情况...",
                  texts: _situationListToStrings(),
                  onTextsChanged: (val) {},
                ),

                const Divider(),

                ItemListWidget.itemContainer(
                  Column(
                    children: [
                      ListItemFactory.headerTitle('检查人员'),
                      SizedBox(height: 5),
                      ListView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: inspectorList.length,
                        itemBuilder: (context, index) {
                          return _personUnitItem(inspectorList[index], index);
                        },
                      ),
                    ],
                  ),
                ),

                const Divider(),

                ItemListWidget.itemContainer(
                  horizontal: 12,
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [ListItemFactory.headerTitle('发现问题')],
                  ),
                ),

                // HiddenListTable：隐患列表展示（外部通过 onHiddenShow/onHiddenRemove 处理具体交互）
                HiddenListTable(
                  hiddenList: (form['hiddenList'] as List<dynamic>?) ?? [],
                  forbidEdit: false,
                  baseImgPath: ApiService.baseImgPath,
                  personSignImg: '',
                  personSignTime: '',
                  showHidden: widget.onHiddenShow,
                  removeHidden: (item, index) {},
                  context: context,
                ),
              ],
            ),
          ),
          SizedBox(height: 10,),
          ItemListWidget.itemContainer(
            horizontal: 0,
            inspectorVerifyList.isNotEmpty
                ? ListView.builder(
                  padding: EdgeInsets.symmetric(horizontal: 0),
                  itemCount: inspectorVerifyList.length,
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemBuilder: (context, index) {
                    return _checkItem(inspectorVerifyList[index], index);
                  },
                )
                : SizedBox(),
          ),
        ],
      ),
    );
  }
}
