import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:http/http.dart' as http;
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'dart:convert';

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 CommitmentWorkshopDetailPage extends StatefulWidget {
  final String commitmentWorkshopId;

  const CommitmentWorkshopDetailPage({
    Key? key,
    required this.commitmentWorkshopId,
  }) : super(key: key);

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

class _CommitmentWorkshopDetailPageState extends State<CommitmentWorkshopDetailPage> {
  Map<String, dynamic> pd = {};
  bool isLoading = true;
  String errorMessage = '';

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

  Future<void> _getData() async {
    setState(() {
      isLoading = true;
    });

    try {
     final response = await ApiService.getWorkshopSafetyCommitmentDetail( widget.commitmentWorkshopId);

        if (response['result'] == 'success') {
          setState(() {
            pd = response['pd'];
            isLoading = false;
          });
        } else {
          ToastUtil.showNormal(context, '数据加载失败');
          setState(() {
            isLoading = false;
          });
        }

    } catch (e) {
      ToastUtil.showNormal(context, '发生错误: ${e.toString()}');
      setState(() {
        isLoading = false;
      });
    }
  }




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

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

    if (errorMessage.isNotEmpty) {
      return Scaffold(
        appBar: AppBar(),
        body: Center(child: Text(errorMessage)),
      );
    }

    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['DEPARTMENT_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: [

                    ListItemFactory.createBlueDotSection('高危生产活动及作业的安全风险可控状态'),
                    // _buildSubTitle('高危生产活动及作业的安全风险可控状态'),


                    _buildParagraph([
                      _buildInfoItem('特殊作业 ', pd['INPUT1'] ?? ''),
                      _buildInfoItem('风险辨识、作业许可及管控措施的落实情况: ',
                          (pd['RADIO1'] == 1 ? '是' : '否')),

                      _buildWorkInfoParagraph(),

                      _buildInfoItem('处于试生产情况： ', (pd['RADIO2'] == 1 ? '是' : '否')),
                      _buildInfoItem('处于开停车情况： ', (pd['RADIO3'] == 1 ? '开' : '停')),
                      _buildWorkInfoParagraphThree(),
                      // _buildInfoItem('承包商作业 ${pd['INPUT14'] ?? ''} 处，管控情况： ',
                      //     (pd['RADIO4'] == 1 ? '受控' : '非受控')),
                      _buildInfoItem('变更情况： ', (pd['RADIO5'] == 1 ? '是' : '否')),
                      _buildInfoItem('落实审批程序情况： ', (pd['RADIO6'] == 1 ? '是' : '否')),
                      _buildInfoItem('罐区、仓库等危险源是否处于安全状态： ',
                          (pd['RADIO7'] == 1 ? '是' : '否')),
                    ]),

                    ListItemFactory.createBlueDotSection('车间安全状态'),
                    // _buildSubTitle('车间安全状态：'),
                    _buildParagraph([
                      _buildWorkInfoParagraphSecond(),
                      // _buildInfoItem(
                      //     '车间岗位 ${pd['INPUT15'] ?? ''} 处，其中运行 ${pd['INPUT16'] ?? ''} 处，'
                      //         '停产 ${pd['INPUT17'] ?? ''} 处，检修 ${pd['INPUT18'] ?? ''} 处。',
                      //     '', isMarked: false),
                    ]),

                    ListItemFactory.createBlueDotSection('生产装置的安全运行状态'),
                    // _buildSubTitle('生产装置的安全运行状态'),
                    _buildParagraph([
                      _buildInfoItem('生产装置的温度、压力、组分液位、流量等主要工艺参数是否处于指标范围： ',
                          (pd['RADIO8'] == 1 ? '是' : '否')),
                      _buildInfoItem('压力容器、压力管道等特种设备处于安全运行状态： ',
                          (pd['RADIO9'] == 1 ? '是' : '否')),
                      _buildInfoItem('设备设施的静动密封完好无泄漏： ',
                          (pd['RADIO10'] == 1 ? '是' : '否')),
                      _buildInfoItem('超限报警、紧急切断、联锁等各类安全设施配备完好投用，并可靠运行： ',
                          (pd['RADIO11'] == 1 ? '是' : '否')),
                    ]),

                    ListItemFactory.createBlueDotSection('危险化学品罐区、仓库等重大危险源的安全运行状态'),
                    // _buildSubTitle('危险化学品罐区、仓库等重大危险源的安全运行状态'),
                    _buildParagraph([
                      _buildInfoItem('储罐、管道、机泵、阀门及仪表系统完好无泄漏： ',
                          (pd['RADIO12'] == 1 ? '是' : '否')),
                      _buildInfoItem('储罐的液位、温度、压力、气柜钟罩无超限运行： ',
                          (pd['RADIO13'] == 1 ? '是' : '否')),
                      _buildInfoItem('手动放脱水、装卸车时确保人员在岗： ',
                          (pd['RADIO14'] == 1 ? '是' : '否')),
                      _buildInfoItem('可燃及有毒气体报警和联锁处于可靠运行状态： ',
                          (pd['RADIO15'] == 1 ? '是' : '否')),
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 8),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const Text(
                              '仓库是否按照国家标准分区分类储存危险化学品，是否超量、超品种储存，相互禁配物质是否混放混存。',
                              style: TextStyle(fontSize: 14),
                            ),
                            const SizedBox(height: 8),
                            // Container(
                            //   padding: const EdgeInsets.all(12),
                            //   decoration: BoxDecoration(
                            //     border: Border.all(color: Colors.blue),
                            //     borderRadius: BorderRadius.circular(4),
                            //   ),
                            //   child:
                              Text(
                                pd['INPUT19'] ?? '',
                                style: const TextStyle(
                                  fontWeight: FontWeight.bold,
                                  color: Colors.blue,
                                ),
                              ),
                            // ),
                          ],
                        ),
                      ),
                    ]),
                  ],
                ),
              ),


              // 企业承诺部分
              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 _buildWorkInfoParagraph() {
    // 定义一个样式映射函数，将数据部分标记为蓝色加粗
    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: 8),
      child: RichText(
        text: TextSpan(
          style: const TextStyle(fontSize: 14, color: Colors.black87),
          children: [
            _buildStyledText('动火作业 ', pd['INPUT2']?.toString()),
            const TextSpan(text: ' 处，其中特级 '),
            _buildStyledText('', pd['INPUT3']?.toString()),
            const TextSpan(text: ' 处，一级 '),
            _buildStyledText('', pd['INPUT4']?.toString()),
            const TextSpan(text: ' 处，二级 '),
            _buildStyledText('', pd['INPUT5']?.toString()),
            const TextSpan(text: ' 处，高处作业 '),
            _buildStyledText('', pd['INPUT6']?.toString()),
            const TextSpan(text: ' 处，受限空间作业 '),
            _buildStyledText('', pd['INPUT7']?.toString()),
            const TextSpan(text: ' 处，吊装作业 '),
            _buildStyledText('', pd['INPUT8']?.toString()),
            const TextSpan(text: ' 处，临时用电作业 '),
            _buildStyledText('', pd['INPUT9']?.toString()),
            const TextSpan(text: ' 处，盲板抽堵作业 '),
            _buildStyledText('', pd['INPUT10']?.toString()),
            const TextSpan(text: ' 处，动土作业 '),
            _buildStyledText('', pd['INPUT11']?.toString()),
            const TextSpan(text: ' 处，断路作业 '),
            _buildStyledText('', pd['INPUT12']?.toString()),
            const TextSpan(text: ' 处，检修作业 '),
            _buildStyledText('', pd['INPUT13']?.toString()),
            const TextSpan(text: ' 处。'),
          ],
        ),
      ),
    );
  }


  Widget _buildWorkInfoParagraphSecond() {
    // 定义一个样式映射函数，将数据部分标记为蓝色加粗
    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: 8),
      child: RichText(
        text: TextSpan(
          style: const TextStyle(fontSize: 14, color: Colors.black87),
          children: [
            _buildStyledText('车间岗位 ', pd['INPUT15']?.toString()),
            const TextSpan(text: ' 处，其中运行 '),
            _buildStyledText('', pd['INPUT16']?.toString()),
            const TextSpan(text: ' 处，停产 '),
            _buildStyledText('', pd['INPUT17']?.toString()),
            const TextSpan(text: '  处，检修 '),
            _buildStyledText('', pd['INPUT18']?.toString()),
            const TextSpan(text: ' 处。'),
          ],
        ),
      ),
    );
  }


  Widget _buildWorkInfoParagraphThree() {
    // 定义一个样式映射函数，将数据部分标记为蓝色加粗
    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: 8),
      child: RichText(
        text: TextSpan(
          style: const TextStyle(fontSize: 14, color: Colors.black87),
          children: [
            _buildStyledText('承包商作业 ', pd['INPUT14']?.toString()),
            const TextSpan(text: ' 处，管控情况： '),
            _buildStyledText('',  (pd['RADIO4'] == 1 ? '受控' : '非受控')),

          ],
        ),
      ),
    );
  }


}