import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/date_picker_dialog.dart';
import 'package:qhd_prevention/customWidget/department_person_picker.dart';
import 'package:qhd_prevention/customWidget/department_picker.dart';
import 'package:qhd_prevention/customWidget/full_screen_video_page.dart';
import 'package:qhd_prevention/customWidget/photo_picker_row.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';

class SafecheckAssignmentDetailPage extends StatefulWidget {
  const SafecheckAssignmentDetailPage({
    super.key,
    required this.HIDDEN_STATUS,
    required this.INSPECTION_ID,
    required this.HIDDEN_ID,
  });

  final String HIDDEN_STATUS;
  final String INSPECTION_ID;
  final String HIDDEN_ID;

  @override
  State<SafecheckAssignmentDetailPage> createState() =>
      _SafecheckAssignmentDetailPageState();
}

class _SafecheckAssignmentDetailPageState
    extends State<SafecheckAssignmentDetailPage> {
  late bool _isEdit = false;
  late Map<String, dynamic> form = {};
  late List files = [];
  late List<String> hiddenVideo = [];
  late List hiddenExamineList = [];
  final Map<String, dynamic> _danger_des = {
    '1': '隐患快报',
    '2': '清单排查',
    '3': '清单排查',
    '4': '安全检查',
    '5': '安全检查',
    '6': '消防检查',
  };
  late List<dynamic> inspectorList = [];

  // 存储各单位的人员列表
  final Map<String, List<Map<String, dynamic>>> _personCache = {};

  final Map<String, dynamic> _rect_des = {'1': '立即整改', '2': '限期整改'};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.HIDDEN_ID == '-2') {
      _isEdit = true;
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getData();
    });
  }

  @override
  Future<void> _getData() async {
    LoadingDialogHelper.show();
    final data = await ApiService.getDangerDetail(widget.HIDDEN_ID);
    LoadingDialogHelper.hide();
    if (data['result'] == 'success') {
      setState(() {
        form = data['pd'];
        final List videos = data['hiddenVideo'] ?? [];
        hiddenVideo =
            videos
                .map((item) => '${ApiService.baseImgPath}${item['FILEPATH']}')
                .toList();
        files = data['hImgs'];
      });
    }
  }

  /// 弹出单位选择
  void chooseUnitHandle(String typeStr) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      barrierColor: Colors.black54,
      backgroundColor: Colors.transparent,
      builder:
          (_) => DepartmentPicker(
            onSelected: (id, name) async {
              setState(() {
                form['RECTIFICATIONDEPT'] = id;
                form['RECTIFICATIONDEPTNAME'] = name;
              });
              FocusHelper.clearFocus(context);
              _getPersonListForUnitId(typeStr);
            },
          ),
    ).then((_) {});
  }

  Future<void> _getPersonListForUnitId(String typeStr) async {
    String unitId = form['RECTIFICATIONDEPT'] ?? '';
    // 拉取该单位的人员列表并缓存
    final result = await ApiService.getListTreePersonList(unitId);
    setState(() {
      _personCache[typeStr] = List<Map<String, dynamic>>.from(
        result['userList'] as List,
      );
    });
    FocusHelper.clearFocus(context);
  }

  /// 弹出人员选择，需先选择单位
  void choosePersonHandle(String typeStr) async {
    final personList = _personCache[typeStr];
    if (!FormUtils.hasValue(_personCache, typeStr)) {
      ToastUtil.showNormal(context, '请先选择单位');
      return;
    }

    DepartmentPersonPicker.show(
      context,
      personsData: personList!,
      onSelectedWithIndex: (userId, name, index) {
        setState(() {
          form['RECTIFICATIONOR'] = userId;
          form['RECTIFICATIONORNAME'] = name;
        });
        FocusHelper.clearFocus(context);
      },
    ).then((_) {});
  }

  Future<void> _submit() async {
    if (!_isEdit) {
      Navigator.of(context).pop();
      return;
    }
    final textRules = <Map<String, dynamic>>[
      {'value': form['RECTIFICATIONDEPT'], 'message': '整改负责人部门不能为空'},
      {'value': form['RECTIFICATIONOR'], 'message': '整改负责人不能为空'},
      {'value': form['RECTIFICATIONDEADLINE'], 'message': '整改期限不能为空'},
    ];
    for (var rule in textRules) {
      if ((rule['value'] as String).isEmpty) {
        ToastUtil.showNormal(context, rule['message']);
        return;
      }
    }
    Map data = {
      'HIDDEN_ID': form['HIDDEN_ID'],
      'HIDDENLEVEL': form['HIDDENLEVEL'],
      'RECTIFICATIONDEPT': form['RECTIFICATIONDEPT'],
      'RECTIFICATIONDEADLINE': form['RECTIFICATIONDEADLINE'],
      'RECTIFICATIONOR': form['RECTIFICATIONOR'],
      'HIDDEN_STATUS': widget.HIDDEN_STATUS,
      'INSPECTION_ID': widget.INSPECTION_ID,
      'HIDDENDESCR': form['HIDDENDESCR'],
    };
    try {
      LoadingDialogHelper.show();
      final result = await ApiService.safeCheckDangerConfirm(data);
      if (result['result'] == 'success') {
        ToastUtil.showNormal(context, '保存成功');
        Navigator.of(context).pop();
      }else{
        ToastUtil.showNormal(context, '保存失败');

      }
      LoadingDialogHelper.hide();
    } catch (e) {
      LoadingDialogHelper.hide();
    }
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: '安全检查指派'),
      body: SafeArea(
        child: ListView(
          children: [
            Padding(
              padding: EdgeInsetsGeometry.all(12),
              child: ItemListWidget.itemContainer(
                horizontal: 0,
                Column(
                  children: [
                    ItemListWidget.singleLineTitleText(
                      label: '隐患描述',
                      isEditable: false,
                      text: form['HIDDENDESCR'] ?? '',
                    ),
                    const Divider(),
                    ItemListWidget.singleLineTitleText(
                      label: '隐患来源',
                      isEditable: false,
                      text: _danger_des[form['SOURCE'] ?? ''] ?? '',
                    ),
                    const Divider(),
                    ItemListWidget.singleLineTitleText(
                      label: '隐患部位',
                      isEditable: false,
                      text: form['hregionName'] ?? form['HIDDENPART'],
                    ),
                    const Divider(),
                    ItemListWidget.singleLineTitleText(
                      label: '隐患级别',
                      isEditable: false,
                      text: form['HIDDENLEVELNAME'] ?? '',
                    ),
                    const Divider(),
                    ItemListWidget.singleLineTitleText(
                      label: '隐患类型',
                      isEditable: false,
                      text:
                          _rect_des[form['RECTIFICATIONTYPE'].toString()] ?? '',
                    ),
                    const Divider(),
                    ItemListWidget.twoRowTitleAndImages(
                      title: '隐患图片',
                      imageUrls: files.map((item) => item['FILEPATH']).toList(),
                      onTapCallBack: (url) {
                        presentOpaque(
                          SingleImageViewer(imageUrl: url),
                          context,
                        );
                      },
                    ),
                    if (hiddenVideo.isNotEmpty)
                      Column(
                        children: [
                          const Divider(),
                          ItemListWidget.itemContainer(
                            horizontal: 5,
                            RepairedPhotoSection(
                              title: '隐患视频',
                              maxCount: 1,
                              onMediaTapped: (p) {
                                showDialog(
                                  context: context,
                                  barrierColor: Colors.black54,
                                  builder: (_) => VideoPlayerPopup(videoUrl: p),
                                );
                              },
                              isEdit: false,
                              mediaType: MediaType.video,
                              initialMediaPaths: hiddenVideo,
                              onChanged: (files) {},
                              onAiIdentify: () {},
                            ),
                          ),
                        ],
                      ),

                    const Divider(),
                    ItemListWidget.singleLineTitleText(
                      label: '隐患发现人',
                      isEditable: false,
                      text: form['CREATORNAME'] ?? '',
                    ),
                    const Divider(),
                    ItemListWidget.singleLineTitleText(
                      label: '发现时间',
                      isEditable: false,
                      text: form['CREATTIME'] ?? '',
                    ),
                  ],
                ),
              ),
            ),
            // SizedBox(height: 12,),
            Padding(
              padding: EdgeInsetsGeometry.only(left: 12, right: 12),
              child: ItemListWidget.itemContainer(
                horizontal: 0,
                Column(
                  children: [
                    ListItemFactory.createBuildSimpleSection('安全检查隐患指派整改人'),
                    const SizedBox(height: 10),
                    ItemListWidget.selectableLineTitleTextRightButton(
                      label: '整改负责人部门',
                      isEditable: _isEdit,
                      isRequired: false,
                      isClean: false,
                      onTapClean: () {
                        setState(() {});
                      },
                      text: form['RECTIFICATIONDEPTNAME'] ?? '请选择',
                      onTap: () => chooseUnitHandle('key'),
                    ),
                    const Divider(),
                    ItemListWidget.selectableLineTitleTextRightButton(
                      label: '整改负责人',
                      isRequired: false,

                      isEditable: _isEdit,
                      text: form['RECTIFICATIONORNAME'] ?? '请选择',
                      onTap: () => choosePersonHandle('key'),
                    ),
                    const Divider(),
                    ItemListWidget.selectableLineTitleTextRightButton(
                      label: '整改期限',
                      isRequired: false,
                      isEditable: _isEdit,
                      text: form['RECTIFICATIONDEADLINE'] ?? '请选择',
                      onTap: () {
                        showDialog(
                          context: context,
                          builder:
                              (_) => HDatePickerDialog(
                                initialDate: DateTime.now(),
                                onCancel: () => Navigator.of(context).pop(),
                                onConfirm: (selected) {
                                  Navigator.of(context).pop();
                                  setState(() {
                                    form['RECTIFICATIONDEADLINE'] = DateFormat(
                                      'yyyy-MM-dd',
                                    ).format(selected);
                                  });
                                },
                              ),
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(height: 15),
            Padding(padding: EdgeInsets.symmetric(horizontal: 50, vertical: 10), child: CustomButton(
              text: _isEdit ? '保存' : '返回',
              backgroundColor: Colors.blue,
              onPressed: () {
                _submit();
              },
            ),)
          ],
        ),
      ),
    );
  }
}
