import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

import 'package:photo_view/photo_view.dart';
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';

class CompanySafetyCommitmentDetail extends StatefulWidget {
  final String commitmentId;

  const CompanySafetyCommitmentDetail({Key? key, required this.commitmentId}) : super(key: key);

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

class _CompanySafetyCommitmentDetailState extends State<CompanySafetyCommitmentDetail> {
  Map<String, dynamic> pd = {};
  bool isLoading = true;


  @override
  void initState() {
    super.initState();
    _getData();
  }

  Future<void> _getData() async {
    try {

      final data = await ApiService.getCompanySafetyCommitmentDetail( widget.commitmentId);

        if (data['result'] == 'success') {
          setState(() {
            pd = data['pd'];
            isLoading = false;
          });
        } else {
          _showError('数据加载失败: ${data['message']}');
        }

    } catch (e) {
      _showError('网络请求失败: $e');
    }
  }

  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
    setState(() => isLoading = false);
  }

  void _showImagePreview(String imageUrl) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Scaffold(
          appBar: AppBar(),
          body: PhotoView(
            imageProvider: NetworkImage(imageUrl),
          ),
        ),
      ),
    );
  }

  // 构建高亮文本
  Widget _highlightText(String text) {
    return Text(
      text,
      style: const TextStyle(
        fontWeight: FontWeight.bold,
        color: Colors.blue,
      ),
    );
  }

  // 构建问题行
  Widget _questionRow(String question, String answer) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        children: [
          Expanded(
            child: Text(question),
          ),
          const SizedBox(width: 8),
          Text(
            answer,
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.blue,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }


    return Scaffold(
      appBar: MyAppbar(title: "安全承诺"),
      body: Container(
        color: Colors.white,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child:Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题部分
              Center(
                child: Text(
                  pd['CORP_NAME'] ?? '未知企业',
                  style: const TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              const SizedBox(height: 5),

              // 企业状态部分
              ListItemFactory.createBuildSimpleSection('企业状态',horPadding: 0),

              Container(
                padding: EdgeInsets.only(top: 15,bottom: 15,left: 15,right: 15),
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey,width: 1)
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [


                    _buildParagraph([

                      _buildWorkInfoParagraph1(),
                      _buildWorkInfoParagraph2(),

                      const SizedBox(height: 2),
                      const Text('特殊作业：'),
                      const SizedBox(height: 2),
                      _buildWorkInfoParagraph3(),


                      _buildInfoItem('是否处于生产： ', (pd['RADIO1'] == 1 ? '是' : '否')),
                      _buildInfoItem('是否处于开停车状态： ', (pd['RADIO2'] == 1 ? '是' : '否')),
                      _buildInfoItem('罐区、库房等危险源是否处于安全状态： ', (pd['RADIO3'] == 1 ? '是' : '否')),]),

                  ],
                ),
              ),


              // 企业承诺部分
              ListItemFactory.createBuildSimpleSection('企业承诺',horPadding: 0),
              // _buildSectionTitle('企业承诺'),

              Container(
                padding: EdgeInsets.only(top: 5,bottom: 5,left: 15,right: 15),
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey,width: 1)
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 8),
                      child: Text.rich(
                        TextSpan(
                          children: [
                            const TextSpan(text: '今日（'),
                            TextSpan(
                              text: pd['START_TIME'] ?? '',
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                                color: Colors.blue,
                              ),
                            ),
                            const TextSpan(text: ' 至 '),
                            TextSpan(
                              text: pd['END_TIME'] ?? '',
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                                color: Colors.blue,
                              ),
                            ),
                            const TextSpan(
                              text: '）我车间已进行安全风险研判，各项安全风险防控措施已落实到位。'
                                  '我承诺本生产装置/业务活动处于安全运行状态，涉及罐区、仓库等危险源安全风险得到有效管控。',
                            ),
                          ],
                        ),
                        style: const TextStyle(fontSize: 14),
                      ),
                    ),

                    // 签名部分
                    GestureDetector(
                      onTap: () {
                        presentOpaque(SingleImageViewer(imageUrl: ApiService.baseImgPath+pd['SIGN_PATH']), context);
                      },
                      child:    Row(
                        children: [
                          // if (imagePath.isNotEmpty)
                          Text('签字照片：',
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.bold,
                              color: Colors.grey,
                            ),
                          ),
                          const SizedBox(width: 15),
                          if (pd['SIGN_PATH'] != null)
                          Image.network(ApiService.baseImgPath+pd['SIGN_PATH'] ,width: 230,height: 150,fit: BoxFit.contain,),

                        ],
                      ),
                    ),

                    //签字时间
                    _buildParagraph([
                      _buildInfoItem('签字时间： ', pd['SIGN_TIME']??""),
                    ]),

                  ],
                ),
              ),

            ],
          ),
        ),

      ),
    );
  }


  Widget _buildParagraph(List<Widget> children) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: children,
      ),
    );
  }

  Widget _buildInfoItem(String label, dynamic value, {bool isMarked = true}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: RichText(
        text: TextSpan(
          style: const TextStyle(fontSize: 14, color: Colors.black87),
          children: [
            TextSpan(text: label),
            if (isMarked)
              TextSpan(
                text: value.toString(),
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.blue,
                ),
              )
            else
              TextSpan(text: value.toString()),
          ],
        ),
      ),
    );
  }

  Widget _buildWorkInfoParagraph1() {
    // 定义一个样式映射函数，将数据部分标记为蓝色加粗
    TextSpan _buildStyledText(String label, String? value) {
      return TextSpan(
        children: [
          TextSpan(text: label),
          TextSpan(
            text: value ?? '',
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.blue,
            ),
          ),
        ],
      );
    }

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: RichText(
        text: TextSpan(
          style: const TextStyle(fontSize: 14, color: Colors.black87),
          children: [
            _buildStyledText('生产装置 ', pd['INPUT1']?.toString()??"0"),
            const TextSpan(text: ' 套，其中 '),

          ],
        ),
      ),
    );
  }


  Widget _buildWorkInfoParagraph2() {
    // 定义一个样式映射函数，将数据部分标记为蓝色加粗
    TextSpan _buildStyledText(String label, String? value) {
      return TextSpan(
        children: [
          TextSpan(text: label),
          TextSpan(
            text: value ?? '',
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.blue,
            ),
          ),
        ],
      );
    }

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: RichText(
        text: TextSpan(
          style: const TextStyle(fontSize: 14, color: Colors.black87),
          children: [
            _buildStyledText('运行 ', pd['INPUT2']?.toString()??"0"),
            _buildStyledText(' 套， 停产', pd['INPUT3']?.toString()??"0"),
            _buildStyledText('套， 检修 ', pd['INPUT4']?.toString()??"0"),
            const TextSpan(text: ' 套。 '),

          ],
        ),
      ),
    );
  }


  Widget _buildWorkInfoParagraph3() {
    // 定义一个样式映射函数，将数据部分标记为蓝色加粗
    TextSpan _buildStyledText(String label, String? value) {
      return TextSpan(
        children: [
          TextSpan(text: label),
          TextSpan(
            text: value ?? '',
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.blue,
            ),
          ),
        ],
      );
    }

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: RichText(
        text: TextSpan(
          style: const TextStyle(fontSize: 14, color: Colors.black87),
          children: [
            _buildStyledText('特级动火作业', pd['INPUT5']?.toString()??"0"),
            _buildStyledText('  处， 一级动火作业', pd['INPUT6']?.toString()??"0"),
            _buildStyledText('处， 二级动火作业  ', pd['INPUT7']?.toString()??"0"),
            _buildStyledText('处， 受限空间作业 ', pd['INPUT8']?.toString()??"0"),
            _buildStyledText(' 处， 登高作业', pd['INPUT9']?.toString()??"0"),
            _buildStyledText('处， 其他特殊作业 ', pd['INPUT10']?.toString()??"0"),
            const TextSpan(text: ' 处。 '),

          ],
        ),
      ),
    );
  }


}