import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/photo_picker_row.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:qhd_prevention/pages/mine/mine_sign_page.dart';

///安全措施

/// 本地路径 + 线上路径模型
class ImageData {
  String localPath;
  String serverPath;

  ImageData({required this.localPath, required this.serverPath});
}

class SignImageData {
  String SIGNER_TIME;
  String? filePath;
  int? key = 0;

  SignImageData({
    required this.SIGNER_TIME,
    required this.filePath,
    required this.key,
  });

  Map<String, dynamic> toJson() => {
    'SIGNER_TIME': SIGNER_TIME,
    'filePath': filePath,
    'key': key,
  };

  factory SignImageData.fromJson(Map<String, dynamic> json) {
    return SignImageData(
      SIGNER_TIME: json['SIGNER_TIME'] as String,
      filePath: json['filePath'] as String?,
      key:
          json['key'] is int
              ? json['key'] as int
              : int.tryParse(json['key']?.toString() ?? ''),
    );
  }
}

class DangerousOptionsPage extends StatefulWidget {
  final int index;
  final int status;
  final String measures;
  final List<ImageData> imgList;
  final List<Map<String, dynamic>> signImgList;

  const DangerousOptionsPage({
    Key? key,
    required this.index,
    this.status = 1,
    this.measures = '',
    this.imgList = const [],
    this.signImgList = const [],
  }) : super(key: key);

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

class _DangerousOptionsPageState extends State<DangerousOptionsPage> {
  late int index;
  late int status;
  late String measures;
  late List<ImageData> imgList;
  late List<SignImageData> signImgList;
  List<String> signTimes = [];

  bool buttonLoading = false;

  @override
  void initState() {
    super.initState();
    index = widget.index;
    status = widget.status;
    measures = widget.measures;
    imgList = List<ImageData>.from(widget.imgList);
    signImgList =
        widget.signImgList.map((map) => SignImageData.fromJson(map)).toList();
  }

  /// 拍照或选图后的回调
  Future<void> _onImageAdded(String localPath) async {
    // 上传到服务器
    final res = await ApiService.uploadSaveFile(localPath);
    final url = res['FILE_PATH'] as String;
    setState(() {
      imgList.add(ImageData(localPath: localPath, serverPath: url));
    });
  }

  /// 删除图片处理：调用删除接口并更新列表
  Future<void> _onImageRemoved(ImageData item) async {
    if (item.serverPath != null) {
      await ApiService.deleteSaveFile(item.serverPath!);
    }
    setState(() {
      imgList.remove(item);
    });
  }

  Future<void> _submit() async {
    if (signImgList.isEmpty) {
      ToastUtil.showNormal(context, '请签字');
      return;
    }
    List<String> filePaths =
        signImgList.map((img) => img.filePath ?? '').toList();
    final result = await ApiService.saveDangerousOptionsFile(filePaths);
    final List<dynamic> signList = result['FILE_PATH_LIST'];
    List<Map<String, dynamic>> sineImageList = [];
    for (SignImageData data in signImgList) {
      for (Map<String, dynamic> img in signList) {
        String imgName = 'file${data.key}';
        if (data.filePath!.contains('uploadFiles')) {
          final idata = {
            'filePath': data.filePath,
            'SIGNER_TIME': data.SIGNER_TIME,
            'key': data.key,
          };
          sineImageList.add(idata);
        }
        if (imgName == img['key']) {
          final idata = {
            'filePath': img['filePath'] ?? '',
            'SIGNER_TIME': data.SIGNER_TIME,
            'key': data.key,
          };
          sineImageList.add(idata);
        }
      }
    }
    setState(() => buttonLoading = true);
    Navigator.pop(context, {
      'imgList':
          imgList
              .map((e) => {'local': e.localPath, 'remote': e.serverPath})
              .toList(),
      'signImgList': sineImageList,
      'index': index,
      'status': status,
    });
  }

  Future<void> _sign() async {
    await NativeOrientation.setLandscape();    
    final String path = await Navigator.push(
      context,
      MaterialPageRoute(builder: (c) => MineSignPage()),
    );
    await NativeOrientation.setPortrait();
if (path != null) {
      final now = DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now());
      setState(() {
        final imageData = SignImageData(
          SIGNER_TIME: now,
          filePath: path,
          key: signImgList.length,
        );
        signImgList.add(imageData);
        signTimes.add(now);
      });
      FocusHelper.clearFocus(context);
    }
  }

  Widget _signListWidget() {
    return Column(
      children:
          signImgList.map((imgData) {
            final idx = signImgList.indexOf(imgData);
            return Column(
              children: [
                const SizedBox(height: 10),
                const Divider(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    GestureDetector(
                      child: ConstrainedBox(
                        constraints: const BoxConstraints(
                          maxWidth: 230,
                          maxHeight: 150,
                        ),
                        child:
                            (imgData.filePath ?? '').contains('uploadFiles')
                                ? Image.network(
                                  '${ApiService.baseImgPath}${imgData.filePath}',
                                )
                                : Image.file(
                                  File(imgData.filePath ?? ''),
                                  fit: BoxFit.contain,
                                ),
                      ),
                      onTap:
                          () => presentOpaque(
                            SingleImageViewer(imageUrl: imgData.filePath ?? ''),
                            context,
                          ),
                    ),
                    Column(
                      children: [
                        CustomButton(
                          text: '删除',
                          height: 30,
                          padding: const EdgeInsets.symmetric(horizontal: 10),
                          backgroundColor: Colors.red,
                          onPressed: () {
                            setState(() => signImgList.removeAt(idx));
                          },
                        ),
                        const SizedBox(height: 80),
                      ],
                    ),
                  ],
                ),
              ],
            );
          }).toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: '安全措施'),
      body: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
          color: Colors.white,
          child: ListView(
            children: [
              Table(
                border: TableBorder.all(color: Colors.grey.shade300),
                columnWidths: {0: FlexColumnWidth(3), 1: FlexColumnWidth(2)},
                children: [
                  TableRow(
                    decoration: BoxDecoration(color: Colors.grey.shade200),
                    children: [
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: Center(
                          child: Text(
                            '主要安全措施',
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: Center(
                          child: Text(
                            '操作',
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ),
                      ),
                    ],
                  ),
                  TableRow(
                    children: [
                      Padding(
                        padding: const EdgeInsets.symmetric(
                          vertical: 12,
                          horizontal: 5,
                        ),
                        child: Text(measures),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(0),
                        child: Column(
                          children: [
                            RadioListTile<int>(
                              value: -1,
                              groupValue: status,
                              title: Text('不涉及'),
                              contentPadding: const EdgeInsets.symmetric(
                                vertical: 0,
                                horizontal: 8.0,
                              ),
                              visualDensity: VisualDensity(
                                vertical: -4,
                                horizontal: 0,
                              ),
                              onChanged: (v) => setState(() => status = v!),
                            ),
                            RadioListTile<int>(
                              value: 1,
                              groupValue: status,
                              title: Text('涉及'),
                              contentPadding: const EdgeInsets.symmetric(
                                vertical: 4.0,
                                horizontal: 8.0,
                              ),
                              visualDensity: VisualDensity(
                                vertical: -4,
                                horizontal: 0,
                              ),
                              onChanged: (v) => setState(() => status = v!),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              const SizedBox(height: 20),
              RepairedPhotoSection(
                title: '上传图片',
                maxCount: 2,
                mediaType: MediaType.image,
                initialMediaPaths:
                    imgList
                        .map((e) => '${ApiService.baseImgPath}${e.serverPath}')
                        .toList(),
                onChanged: (paths) {},
                onMediaAdded: _onImageAdded,
                onMediaTapped: (path) {
                  presentOpaque(SingleImageViewer(imageUrl: path), context);
                },
                onMediaRemoved: (path) {
                  final item = imgList.firstWhere((e) => e.localPath == path);
                  _onImageRemoved(item);
                },
                onAiIdentify: () {},
              ),
              const SizedBox(height: 20),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('签字：', style: TextStyle(fontSize: 16)),
                  CustomButton(
                    text: '新增手写签字',
                    height: 36,
                    backgroundColor: Colors.green,
                    onPressed: _sign,
                  ),
                ],
              ),
              if (signImgList.isNotEmpty) _signListWidget(),
              const SizedBox(height: 30),
              CustomButton(
                text: '保存',
                backgroundColor: Colors.blue,
                onPressed: buttonLoading ? null : _submit,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
