import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/photo_picker_row.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/http/ApiService.dart';

import 'package:qhd_prevention/pages/my_appbar.dart';

class PhotoItem {
  final String id;
  final String filePath;
  final String type;

  PhotoItem({
    required this.id,
    required this.filePath,
    required this.type, //1 网络 2 本地
  });
}

class DangerImageUpdataPage extends StatefulWidget {
  const DangerImageUpdataPage(this.id, {super.key, required this.imgList});
  final List<PhotoItem> imgList;

  final String id;

  @override
  State<DangerImageUpdataPage> createState() => _DangerImageUpdataPageState();
}

class _DangerImageUpdataPageState extends State<DangerImageUpdataPage> {
  late List<PhotoItem> _imgList = [];

  // List<dynamic> alreadyImageList=[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _imgList = widget.imgList;
    _getAlreadyUpImages();
  }

  Future<void> _getAlreadyUpImages() async {
    try {
      final result = await ApiService.getAlreadyUpImages(widget.id);
      if (result['result'] == 'success') {
        final List<dynamic> newList = result['imgs'] ?? [];
        setState(() {
          for (Map item in newList) {
            String id = item['IMGFILES_ID'] ?? '';
            String filePath = item['FILEPATH'] ?? '';
            _imgList.add(
              PhotoItem(
                id: id, // 新图片没有ID
                filePath: ApiService.baseImgPath+filePath,
                type: "1",
              ),
            );

          }

        });
      } else {
        ToastUtil.showNormal(context, "加载数据失败");
        // _showMessage('加载数据失败');
      }
    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载数据失败：$e');
    }
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: MyAppbar(title: "检查照片"),
      body: Column(
        children: [
          RepairedPhotoSection(
            title: "检查照片",
            maxCount: 4,
            mediaType: MediaType.image,
            isShowAI: false,
            initialMediaPaths: _imgList.map((e)=> e.filePath).toList(),
            onMediaAdded: (value) {
              setState(() {
                _imgList.add(
                  PhotoItem(
                    id: "", // 新图片没有ID
                    filePath: value,
                    type: "2",
                  ),
                );
              });
            },

            onMediaRemoved: (path) {
              int delete = 0;
              _onImageRemoved(_imgList[delete]);
              _imgList.removeAt(delete);
            },
            onAiIdentify: () {},
            onChanged: (List<File> value) {},
          ),

          // 下一步按钮
          Container(
            margin: const EdgeInsets.only(bottom: 20),
            height: 50,
            decoration: BoxDecoration(
              color: Colors.green,
              borderRadius: BorderRadius.circular(10),
              boxShadow: [
                BoxShadow(
                  color: Colors.black12,
                  blurRadius: 6,
                  offset: Offset(0, 2),
                ),
              ],
            ),
            child: SizedBox(
              width: screenWidth - 30,
              height: 50,
              child: TextButton(
                onPressed: () async {
                  if (_imgList.length > 4) {
                    ToastUtil.showNormal(context, "图片不能大于4张");
                    return;
                  }
                  _submitAll();
                },
                child: Text(
                  "提交",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
  Future<void> _submitAll() async {
    int i = 0;
    for (PhotoItem item in _imgList) {
      if (item.type == '2') {
        String imgPath = await _addImgFiles(item.filePath, "14", widget.id);
        if (imgPath.isEmpty) {
          // 单张上传失败时的处理
          ToastUtil.showError(context, "第${i+1}张上传失败");
          return;
        }
      }
      i++;
    }

    ToastUtil.showNormal(context, "提交成功");
    Navigator.of(context).pop();
  }
  Future<String> _addImgFiles(String imagePath, String type, String id) async {
    try {
      final raw = await ApiService.addImgFiles(imagePath, type, id);
      if (raw['result'] == 'success') {
        Map pd = raw['pd'];
        final String img = pd['FILEPATH'];
        return img;
      } else {
        return "";
      }
    } catch (e) {
      print('上传图片失败：$e');
      return "";
    }
  }


  Future<String> _onImageRemoved(PhotoItem item) async {
    try {
      final raw = await ApiService.onImageRemoved(item.id);
      if (raw['result'] == 'success') {
        return raw['imgPath'];
      } else {
        // _showMessage('反馈提交失败');
        return "";
      }
    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载首页数据失败：$e');
      return "";
    }
  }
}
