import 'dart:io';

import 'package:flutter/cupertino.dart';
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/single_image_viewer.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/http/HttpManager.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/pages/mine/mine_sign_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';



class SafetyMeetingDetailPage extends StatefulWidget {
  const SafetyMeetingDetailPage(this.id, this.selectedTab,   {super.key,required this.onClose});

  final int selectedTab;
  final String id;
  final Function(String) onClose; // 回调函数

  @override
  State<SafetyMeetingDetailPage> createState() => _SafetyMeetingDetailPageState();
}

class _SafetyMeetingDetailPageState extends State<SafetyMeetingDetailPage> {

  final TextEditingController contentController = TextEditingController();
  List<String> signImages = [];
  late List<dynamic> _listImage = [];
  late Map<String, dynamic> pd = {};

  late List<dynamic> qianZiImages = [];

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


  Future<void> getSafetyMeetDetail() async {

    try {

      final result = await ApiService.getSafetyMeetDetail(widget.id );

      if (result['result'] == 'success') {
        final List<dynamic> newList = result['imgs'] ?? [];
        setState(() {
          pd= result['pd'];
          _listImage.addAll(newList);
          if(widget.selectedTab==1&&result.containsKey('singImgs')){
            final List<dynamic> singList = result['singImgs'] ?? [];
            if(singList.isNotEmpty){
              qianZiImages.add(singList[0]);
            }

            // qianZiImages=result['singImgs'][0]["FILEPATH"]?? [];
          }
        });

      }else{
        ToastUtil.showNormal(context, "加载数据失败");
        // _showMessage('加载数据失败');
      }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: "安全例会-详情"),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [

                Container(
                padding: EdgeInsets.only(top: 5,left: 5,right: 5,bottom: 15),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Column(
                        children: [
                          // 例会标题
                          ItemListWidget.singleLineTitleText(
                            label: '例会标题：',
                            isEditable: false,
                            text: pd['SAFETY_MEETING_TITLE'] ?? '',
                          ),
                          Divider(height: 30),

                          // 内容
                          ItemListWidget.singleLineTitleText(
                            label: '内容：',
                            isEditable: false,
                            text: pd['SAFETY_MEETING_CONTENT'] ?? '',
                          ),
                          Divider(height: 30),

                          // 附件
                          ItemListWidget.twoRowTitleAndImages(
                            onTapCallBack: (val) {
                              presentOpaque(SingleImageViewer(imageUrl: val), context);
                            },
                            title: '附件：',
                            imageUrls: _listImage
                                .map((item) => item['FILEPATH'] as String) // 提取并转换为 String
                                .toList(),
                          ),
                        ],

                )
              ),

            SizedBox(height: 15),

      if(widget.selectedTab==1)
      Container(
        padding: EdgeInsets.only(top: 5,left: 5,right: 5,bottom: 15),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(5),
        ),
        child: Column(
          children: [
            // 反馈意见
            ItemListWidget.multiLineTitleTextField(
              label: '反馈意见：',
              isEditable: false,
              isRequired: false,
              controller: contentController,
              text:pd["FEED_BACK"],
            ),
            Divider(),

            // 签字区域
            if(qianZiImages.isNotEmpty)
              ItemListWidget.twoRowTitleAndImages(
                onTapCallBack: (val) {
                  presentOpaque(SingleImageViewer(imageUrl: val), context);
                },
                title: '签字信息：',
                imageUrls: qianZiImages
                    .map((item) => item['FILEPATH'] as String) // 提取并转换为 String
                    .toList(),
              ),

          ],

        )
      ),

            if(widget.selectedTab==0)
              Container(
                  padding: EdgeInsets.only(top: 5,left: 5,right: 5,bottom: 15),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(5),
                  ),
                  child: Column(
                    children: [
                      // 反馈意见
                      ItemListWidget.multiLineTitleTextField(
                        label: '反馈意见：',
                        isEditable: true,
                        controller: contentController,
                        hintText: "(必填)",
                        text:'',
                      ),
                      Divider(),

                      // 签字区域
                      Padding(
                        padding: EdgeInsets.only(left: 10,right: 10),
                        child:  Column(
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                ListItemFactory.headerTitle('签字'),
                                CustomButton(
                                  text: '手写签字',
                                  height: 36,
                                  backgroundColor: Colors.green,
                                  onPressed: () {
                                    _sign();
                                  },
                                ),
                              ],
                            ),
                            if (signImages.isNotEmpty) _signListWidget(),
                          ],
                        ),
                      ),
                    ],

                  )
              ),
            SizedBox(height: 15),

            // 提交按钮
            if (widget.selectedTab==0)
              CustomButton(
                text: '提交',
                backgroundColor: Colors.blue,
                textStyle: TextStyle(color: Colors.white,fontSize: 12),
                onPressed: () {
                  setSafetyMeetDetailFeedback();
                },
              ),

          ],
        ),
      ),


    );
  }


  Future<void> setSafetyMeetDetailFeedback() async {
    try {

      String text=contentController.text.trim();
      if(text.isEmpty){
        ToastUtil.showNormal(context, "请填写反馈意见");
        return;
      }

      if(signImages.isEmpty){
        ToastUtil.showNormal(context, "请签字");
        return;
      }


      LoadingDialogHelper.show();
      final result = await ApiService.setSafetyMeetDetailFeedback(widget.id ,text);
      if (result['result'] == 'success') {
        String SAFETY_MEETING_PEOPLE_ID= result['pd']['SAFETY_MEETING_PEOPLE_ID'];

        addSafetyMeetDetailFeedBack(SAFETY_MEETING_PEOPLE_ID);
        setState(() {
          LoadingDialogHelper.hide();
            ToastUtil.showNormal(context, "提交成功");
            widget.onClose('提交成功');
            Navigator.pop(context);
        });

      }else{
        ToastUtil.showNormal(context, "加载数据失败");
        LoadingDialogHelper.hide();
        // _showMessage('加载数据失败');
      }

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



  Future<void> addSafetyMeetDetailFeedBack(id) async {
    try {

      final result = await ApiService.addSafetyMeetDetailFeedBack(signImages[0] ,id);
      if (result['result'] == 'success') {


      }else{
        ToastUtil.showNormal(context, "加载数据失败");
        // _showMessage('加载数据失败');
      }

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



  /// 签字
  Future<void> _sign() async {
    await NativeOrientation.setLandscape();
    final path = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => MineSignPage()),
    );
    if (path != null) {
      // final now = DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now());

      final file = File(path);
      if (!await file.exists()) {
        throw ApiException('file_not_found', '图片不存在：$path');
      }

      setState(() {
        signImages.add(path);
        // signTimes.add(now);
        FocusHelper.clearFocus(context);
      });
    }
  }

  Widget _signListWidget() {
    return Column(
      children:
      signImages.map((path) {
        return Column(
          children: [
            const SizedBox(height: 10),
            const Divider(),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                GestureDetector(
                  child: // 用一个 ConstrainedBox 限制最大尺寸，并改为 BoxFit.contain
                  ConstrainedBox(
                    constraints: const BoxConstraints(
                      maxWidth: 200,
                      maxHeight: 150,
                    ),
                    child: Image.file(
                      File(path),
                      // 改为完整显示
                      fit: BoxFit.contain,
                    ),
                  ),
                  onTap: () {
                    presentOpaque(
                      SingleImageViewer(imageUrl: path),
                      context,
                    );
                  },
                ),
                Column(
                  children: [
                    Container(
                      padding: const EdgeInsets.only(right: 5),
                      child: CustomButton(
                        text: 'X',
                        height: 30,
                        padding: const EdgeInsets.symmetric(horizontal: 10),
                        backgroundColor: Colors.red,
                        onPressed: () {
                          setState(() {
                            signImages.remove(path);
                          });
                        },
                      ),
                    ),
                    const SizedBox(height: 80),
                  ],
                ),
              ],
            ),
          ],
        );
      }).toList(),
    );
  }


}