import 'dart:io';

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/full_screen_video_page.dart';
import 'package:qhd_prevention/customWidget/photo_picker_row.dart';
import 'package:qhd_prevention/customWidget/picker/CupertinoDatePicker.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 DangerManagerDetailPage extends StatefulWidget {
  const DangerManagerDetailPage({super.key, required this.info});

  final Map<String, dynamic> info;

  @override
  State<DangerManagerDetailPage> createState() =>
      _DangerManagerDetailPageState();
}

class _DangerManagerDetailPageState extends State<DangerManagerDetailPage> {
  Map<String, dynamic> hiddenForm = {};
  Map<String, dynamic> punishForm = {};
  List<File> ysImages = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getData();
  }

  Future<void> _getData() async {
    final result = await ApiService.getKeyprojectDangerFindHidden(
      widget.info['HIDDEN_ID'] ?? '',
      widget.info['OUTSOURCED_ID'] ?? '',
    );
    try {
      setState(() {
        hiddenForm = result['pd'] ?? {};
        if (FormUtils.hasValue(hiddenForm, 'punishForm')) {
          punishForm = hiddenForm['punishForm'];
        }
        print(hiddenForm);
      });
    } catch (e) {
      ToastUtil.showNormal(context, '$e');
    }
  }

  List<String> _getServerPath(List paths) {
    List<String> p = paths.map((val) => '${val['FILEPATH']}').toList();
    return p;
  }

  String _getServerVideoPath(List paths) {
    List<String> p = paths.map((val) => '${val['FILEPATH']}').toList();
    if (p.isNotEmpty) {
      return '${ApiService.baseImgPath}${p[0]}';
    }
    return '';
  }

  Widget _punishFormWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ListItemFactory.createBuildSimpleSection('处罚信息'),
        ItemListWidget.multiLineTitleTextField(
          label: '处罚原因：',
          isEditable: false,
          text: punishForm['REASON'] ?? '',
        ),
        const Divider(),
        ItemListWidget.multiLineTitleTextField(
          label: '处罚金额：',
          isEditable: false,
          text: punishForm['AMOUT'] ?? '',
        ),
        const Divider(),
        ItemListWidget.multiLineTitleTextField(
          label: '被处罚单位：',
          isEditable: false,
          text: punishForm['UNITS_NAME'] ?? '',
        ),
        const Divider(),
        ItemListWidget.multiLineTitleTextField(
          label: '被处罚人：',
          isEditable: false,
          text: punishForm['PERSON_NAME'] ?? '',
        ),
        const Divider(),
        ItemListWidget.multiLineTitleTextField(
          label: '下发人：',
          isEditable: false,
          text: punishForm['CREATOR_NAME'] ?? '',
        ),
        const Divider(),
        ItemListWidget.multiLineTitleTextField(
          label: '下发处罚时间：',
          isEditable: false,
          text: punishForm['DATE'] ?? '',
        ),
        const Divider(),
        if (FormUtils.hasValue(punishForm, 'HANDLE_IMG'))
          ListItemFactory.createTextImageItem(
            horizontalPadding: 12,
            text: '罚款缴纳单',
            onImageTapped: (index) {
              presentOpaque(
                SingleImageViewer(
                  imageUrl:
                      '${ApiService.baseImgPath}${_getServerPath(punishForm['HANDLE_IMG'])[index]}',
                ),
                context,
              );
            },
            imageUrls: punishForm['HANDLE_IMG'],
          ),
        const Divider(),
        ItemListWidget.multiLineTitleTextField(
          label: '是否缴纳罚款：',
          isEditable: false,
          text: punishForm['已缴'] == '1' ? '已缴' : '未缴',
        ),
        const Divider(),
        if (punishForm['HANDLED'].toString() == '1')
          Column(
            children: [
              ItemListWidget.multiLineTitleTextField(
                label: '处罚处理人：',
                isEditable: false,
                text: punishForm['PERSON_NAME'] ?? '',
              ),
              const Divider(),
              ItemListWidget.multiLineTitleTextField(
                label: '处罚处理时间：',
                isEditable: false,
                text: punishForm['HANLDE_TIME'] ?? '',
              ),
            ],
          ),
      ],
    );
  }

  Future<void> _submit() async {
    if (!FormUtils.hasValue(hiddenForm, 'CHECKTIME')) {
      ToastUtil.showNormal(context, '请选择验收时间');
      return;
    }

    LoadingDialogHelper.show();
    final result = await ApiService.checkKeyprojectDanger(
      widget.info['HIDDEN_ID'] ?? '',
      hiddenForm,
    );
    if (result['result'] == 'success') {
      final List<String> files = _getServerPath(hiddenForm['ysImgs']);
      for (String p in files) {
        final upResult = await ApiService.addNormalImgFiles(p, {
          'TYPE': '5',
          'FOREIGN_KEY': widget.info['HIDDEN_ID'],
        });
        if (FormUtils.hasValue(upResult, 'network_error')) {
          LoadingDialogHelper.hide();
          ToastUtil.showNormal(context, '上传文件出错');
          return;
        }
      }
      Navigator.of(context).pop();
      LoadingDialogHelper.hide();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: '隐患管理'),
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 12, horizontal: 12),
          child: Column(
            children: [
              Expanded(
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 12),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(5),
                  ),
                  child:
                      hiddenForm.isNotEmpty
                          ? ListView(
                            children: [
                              ListItemFactory.createTextImageItem(
                                horizontalPadding: 12,
                                text: '隐患照片',
                                onImageTapped: (index) {
                                  presentOpaque(
                                    SingleImageViewer(
                                      imageUrl:
                                          '${ApiService.baseImgPath}${_getServerPath(hiddenForm['hiddenImgs'])[index]}',
                                    ),
                                    context,
                                  );
                                },
                                imageUrls: _getServerPath(
                                  hiddenForm['hiddenImgs'],
                                ),
                              ),
                              const Divider(),

                              ListItemFactory.createTextVideoItem(
                                horizontalPadding: 12,
                                onVideoTapped: () {
                                  showDialog(
                                    context: context,
                                    barrierColor: Colors.black54,
                                    builder:
                                        (_) => VideoPlayerPopup(
                                          videoUrl: _getServerVideoPath(
                                            hiddenForm['hiddenVideos'],
                                          ),
                                        ),
                                  );
                                },
                                text: '隐患视频',
                                videoUrl: _getServerVideoPath(
                                  hiddenForm['hiddenVideos'],
                                ),
                              ),
                              const Divider(),
                              ItemListWidget.multiLineTitleTextField(
                                label: '隐患描述',
                                isEditable: false,
                                text: hiddenForm['HIDDENDESCR'],
                              ),
                              const Divider(),
                              ItemListWidget.singleLineTitleText(
                                label: '隐患部位',
                                isEditable: false,
                                text: hiddenForm['HIDDENPART'] ?? '',
                              ),
                              const Divider(),
                              ItemListWidget.singleLineTitleText(
                                label: '隐患级别',
                                isEditable: false,
                                text: hiddenForm['HIDDENLEVEL_NAME'] ?? '',
                              ),
                              const Divider(),
                              ItemListWidget.singleLineTitleText(
                                label: '隐患类型',
                                isEditable: false,
                                text: hiddenForm['HIDDENTYPE_NAME'] ?? '',
                              ),
                              const Divider(),
                              ItemListWidget.singleLineTitleText(
                                label: '隐患处置',
                                isEditable: false,
                                text: '限期整改',
                              ),
                              const Divider(),
                              ItemListWidget.singleLineTitleText(
                                label: '整改期限',
                                isEditable: false,
                                text: hiddenForm['RECTIFICATIONDEADLINE'] ?? '',
                              ),
                              const Divider(),
                              ItemListWidget.singleLineTitleText(
                                label: '整改部门',
                                isEditable: false,
                                text:
                                    hiddenForm['RECTIFICATIONDEPT_NAME'] ?? '',
                              ),
                              const Divider(),
                              ItemListWidget.singleLineTitleText(
                                label: '整改人',
                                isEditable: false,
                                text: hiddenForm['RECTIFICATIONOR_NAME'] ?? '',
                              ),
                              const Divider(),
                              if (hiddenForm['STATE'].toString() == '2' ||
                                  hiddenForm['STATE'].toString() == '4')
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ItemListWidget.singleLineTitleText(
                                      label: '整改时间',
                                      isEditable: false,
                                      text:
                                          hiddenForm['RECTIFICATIONTIME'] ?? '',
                                    ),
                                    const Divider(),
                                    ListItemFactory.createTextImageItem(
                                      horizontalPadding: 12,
                                      text: '整改照片',
                                      imageUrls: _getServerPath(
                                        hiddenForm['zgImgs'],
                                      ),
                                      onImageTapped: (index) {
                                        presentOpaque(
                                          SingleImageViewer(
                                            imageUrl:
                                                '${ApiService.baseImgPath}${_getServerPath(hiddenForm['zgImgs'])[index]}',
                                          ),
                                          context,
                                        );
                                      },
                                    ),
                                    const Divider(),
                                  ],
                                ),
                              if (hiddenForm['STATE'].toString() == '4' ||
                                  widget.info['TabCur'].toString() == '1')
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,

                                  children: [
                                    ItemListWidget.selectableLineTitleTextRightButton(
                                      label: '验收时间',
                                      isEditable:
                                          widget.info['TabCur'] == '1'
                                              ? true
                                              : false,
                                      text: hiddenForm['CHECKTIME'] ?? '',
                                      onTap: () async {
                                        DateTime? picked =
                                            await BottomDateTimePicker.showDate(
                                              context,
                                            );
                                        if (picked != null) {
                                          setState(() {
                                            hiddenForm['CHECKTIME'] =
                                                DateFormat(
                                                  'yyyy-MM-dd HH:mm',
                                                ).format(picked);
                                          });
                                        }
                                      },
                                    ),
                                    const Divider(),

                                    Padding(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 8,
                                      ),
                                      child: RepairedPhotoSection(
                                        title: '验收照片',
                                        maxCount: 4,
                                        mediaType: MediaType.image,
                                        isShowAI: false,
                                        isEdit:
                                            widget.info['TabCur'] == '1'
                                                ? true
                                                : false,
                                        isRequired: false,
                                        initialMediaPaths:
                                            _getServerPath(hiddenForm['ysImgs'])
                                                .map(
                                                  (path) =>
                                                      '${ApiService.baseImgPath}$path',
                                                )
                                                .toList(),
                                        onMediaTapped: (p) {
                                          presentOpaque(
                                            SingleImageViewer(imageUrl: p),
                                            context,
                                          );
                                        },
                                        onChanged:
                                            (files) => setState(() {
                                              hiddenForm['ysImgs'] =
                                                  files
                                                      .map(
                                                        (f) => {
                                                          'FILEPATH': f.path,
                                                        },
                                                      )
                                                      .toList();
                                            }),
                                        onAiIdentify: () {},
                                      ),
                                    ),
                                  ],
                                ),

                              if (FormUtils.hasValue(hiddenForm, 'punishForm'))
                                _punishFormWidget(),
                            ],
                          )
                          : SizedBox(width: double.maxFinite),
                ),
              ),
              SizedBox(height: 20),
              CustomButton(
                text: widget.info['TabCur'] == '1' ? '验收' : '返回',
                backgroundColor: Colors.blue,
                onPressed: () {
                  if (widget.info['TabCur'] == '1') {
                    _submit();
                  } else {
                    Navigator.of(context).pop();
                  }
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
