import 'package:amos_iot_login_tpl/const/global_config.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:full_screen_image/full_screen_image.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/Logger.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/dispatch/disaster/planWebView.dart';
import './../entity/alarm_disaster.dart';
import './../event_bus.dart';
import './../map/task_feedback.dart';
import './../native_bridge.dart';
import './realtime_distance.dart';
import 'ImportantPoint.dart';
import 'TaskFeedBack.dart';
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:flutter_swiper/flutter_swiper.dart';
/// 灾情数据
class DisasterInfo extends StatefulWidget {
  const DisasterInfo({
    Key key,
    this.callJSMethod,
    this.controller,
    this.isCar,
    this.currentLngLat,
    this.alarmDisaster,
    this.plans , //救援预案
    this.powerInfo, //力量信息
    this.helpInfo,//救援对象信息
    this.keySiteBuildTree, //重点部位树

  }) : super(key: key);
  final ExecuteJSMethod callJSMethod;
  final AlarmDisaster alarmDisaster;
  final bool isCar;
  final ScrollController controller;
  final Map currentLngLat;

  final Map helpInfo;//救援对象信息
  final List plans ; //救援预案
  final List powerInfo; //力量信息
  final List keySiteBuildTree; //重点部位树

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


class _DisasterInfoState extends State<DisasterInfo> {
  String bindingCarId = ''; //绑定的车辆ID
  String alertCallId = ''; //加入的灾情ID
  String status = ''; //灾情状态
  String statusName = ''; //灾情状态名称
  String imageUrl = '';
  AudioPlayer audioPlayer = AudioPlayer();
  bool isPlaySound = false;
  List plans = []; //救援预案
  List powerInfo = []; //力量信息
  Map helpInfo = {'scenePicture': [], 'planePicture': [], 'facadePicture': [], 'orgUsrzhDto': {}}; //救援对象信息
  List keySiteBuildTree = []; //重点部位树
  Timer timer;
   final ValueNotifier<String> _valueNotifier = ValueNotifier<String>('');
  @override
  void initState() {
    super.initState();
    _getStatus();
    // _getPlan(widget.alarmDisaster.sequenceNbr);
    // _getPowerInfo(widget.alarmDisaster.sequenceNbr);
    // _getOrgUsrzhDto(widget.alarmDisaster.sequenceNbr);
    // _getKeySiteBuildTree(widget.alarmDisaster.sequenceNbr);

     

    audioPlayer.onPlayerStateChanged.listen((AudioPlayerState event) {
      switch (event) {
        case AudioPlayerState.PLAYING:
          break;
        case AudioPlayerState.STOPPED:
        case AudioPlayerState.PAUSED:
        case AudioPlayerState.COMPLETED:
          setState(() {
            isPlaySound = false;
          });
          break;
      }
    });
    audioPlayer.onPlayerError.listen((event) {
      ToastUtils.showToast(event);
    });
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imageUrl = value;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    audioPlayer.release();
  }

  /// 播放
  Future<void> play() async {
    setState(() {
      isPlaySound = true;
    });
    await audioPlayer.play((widget.alarmDisaster.alarmDetails ?? {})['voiceRecordFile']);
  }

  ///暂停
  Future<void> pause() async {
    await audioPlayer.pause();
  }

void checkForNewSharedLists(AlarmDisaster alarm){
  
const timeout =  Duration(seconds: 1);

timer?.cancel();
timer=Timer.periodic(timeout, (timer) { //callback function
  //1s 回调一次
   _valueNotifier.value= DateUtils.upToNow(alarm.callTime?? '');
});


}



  @override
  Widget build(BuildContext context) {
     AlarmDisaster alarm = widget.alarmDisaster ?? AlarmDisaster();
      if(alarm.alarmTypeCode == '230'){
       return ListView(
      controller: widget.controller,
      padding: const EdgeInsets.all(8.0),
      children: <Widget>[
        const SizedBox(
          height: 18.0,
        ),
        buildBasicInfo(context),
        const SizedBox(
          height: 10.0,
        ),
        buildTitle('警情信息'),
        buildInfo(context),
        const SizedBox(
          height: 10.0,
        ),
        buildTitle('灾情统计'),
        buildStatistics(context),
        const SizedBox(
          height: 10.0,
        ),
        buildTitle('报警信息'),
        buildAlarmInfo(context),


        const SizedBox(
          height: 10.0,
        ),
        buildTitle('救援对象'),
        buildHelpInfo(),
              
        const SizedBox(
          height: 10.0,
        ),
        buildTitle('救援预案'),
        buildPlan(),
        const SizedBox(
          height: 10.0,
        ),
        buildTitle('力量信息'),
        buildPowerInfo(),
        const SizedBox(
          height: 10.0,
        ),
        buildTitle('战斗统计'),
        buildFightingStatistics(context)
      ],
    );
        } else {
      return ListView(
      controller: widget.controller,
      padding: const EdgeInsets.all(8.0),
      children: <Widget>[
        const SizedBox(
          height: 18.0,
        ),
        buildBasicInfo(context),
        const SizedBox(
          height: 10.0,
        ),
        buildTitle('警情信息'),
        buildInfo(context),
        const SizedBox(
          height: 10.0,
        ),
        buildTitle('灾情统计'),
        buildStatistics(context),
        const SizedBox(
          height: 10.0,
        ),
        buildTitle('报警信息'),
        buildAlarmInfo(context),


        const SizedBox(
          height: 10.0,
        ),
        buildTitle('救援对象'),
        buildHelpInfo(),
       
        const SizedBox(
            height: 10.0,
          ),
          buildTitle('重点部位'),
          buildImportantPoint(),
                
        const SizedBox(
          height: 10.0,
        ),
        buildTitle('救援预案'),
        buildPlan(),
        const SizedBox(
          height: 10.0,
        ),
        buildTitle('力量信息'),
        buildPowerInfo(),
        const SizedBox(
          height: 10.0,
        ),
        buildTitle('战斗统计'),
        buildFightingStatistics(context)
      ],
    );
        }
    
  }

  Widget buildPlan() {
    return ListView.separated(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (BuildContext context, int index) {
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              children: [
                InkWell(
                  onTap: () => Get.to(PlanWebView(sequenceNbr: widget.plans[index]['sequenceNbr'] ?? '')),
                  child: Row(
                    children: [
                      Expanded(
                          child: Text(
                        widget.plans[index]['docTitle'] ?? '',
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      )),
                      const Opacity(
                          opacity: 0.6,
                          child: Icon(
                            Icons.arrow_forward_ios,
                            size: 14,
                          ))
                    ],
                  ),
                )
              ],
            ),
          );
        },
        separatorBuilder: (BuildContext context, int index) {
          return const Divider(
            color: Colors.black,
            height: 5,
            thickness: 0.2,
          );
        },
        itemCount: widget.plans.length);
  }

  Container buildTitle(String title) {
    return Container(
      padding: const EdgeInsets.only(left: 5),
      child: Text(
        title,
        style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
      ),
      decoration: const BoxDecoration(border: Border(left: BorderSide(width: 2, color: Colors.blue))),
    );
  }

  /// 基本信息
  Widget buildBasicInfo(BuildContext context) {
    AlarmDisaster alarm = widget.alarmDisaster ?? AlarmDisaster();
 checkForNewSharedLists(widget.alarmDisaster ?? AlarmDisaster());

    return Container(
        child: Column(children: [
      Row(children: [
        Expanded(
          child: Container(
            child: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
              Row(children: [
                Expanded(
                  child: Row(children: [
                    Flexible(
                      child: Container(
                          child: Text(
                        '${alarm.address ?? ''}${alarm.alertType ?? ''}',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(color: Color(0xff333333), fontWeight: FontWeight.bold, fontSize: 20.0),
                      )),
                    ),
                    ClipRRect(
                      borderRadius: const BorderRadius.all(Radius.circular(5)),
                      child: Container(
                        color: Colors.red,
                        child: Image.asset(
                          _getTypeIcon(alarm.alarmTypeCode),
                          width: 25.0,
                          height: 25.0,
                        ),
                      ),
                    ),
                    const SizedBox(
                      width: 5,
                    ),
                    alarm.responseLevelCode.isNotEmpty
                        ? Container(
                            padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 5),
                            decoration:
                                const BoxDecoration(color: Colors.orange, borderRadius: BorderRadius.all(Radius.circular(5))),
                            child: Text(
                              '${alarm.responseLevelCode}',
                              style: const TextStyle(color: Colors.white),
                            ))
                        : const Text(''),
                    widget.isCar
                        ? Container(
                            height: 25,
                            child: GradientButton(
                              color: const Color(0xff2780ec),
                              child: const Text(
                                '任务反馈',
                                style: TextStyle(fontSize: 12),
                              ),
                              onPressed: () {
                                Navigator.push(context, MaterialPageRoute(builder: (context) {
                                  return TaskFeedback(alarmId: alarm.sequenceNbr);
                                }));
                              },
                              borderRadius: BorderRadius.circular(30),
                            ))
                        : const Text(''),
                  ]),
                ),
                Row(
                  children: [_buildStatusButton()],
                ),
              ]),
              Row(
                children: [
                  RealtimeDistance(
                      callJSMethod: widget.callJSMethod,
                      targetLanLat: {'latitude': alarm.latitude, 'longitude': alarm.longitude},
                      currentLngLat: widget.currentLngLat,
                      distance: alarm.distance,
                      msgType: EventDataType.Self2AlarmDistance),
                  Expanded(
                    child: Text(
                      '${alarm.address}',
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
              const SizedBox(
                height: 3,
              ),
              Row(
                children: [
                  Text(
                    alarm.callTime ?? '',
                    style: const TextStyle(color: Color(0xff999999)),
                  )
                ],
              ),
              const SizedBox(
                height: 2,
              ),

            ValueListenableBuilder<String>(
            valueListenable: _valueNotifier,
            builder: (context, value, child) {
              return Visibility(
                child: Container(
                  child: LabelValue(label: '已持续', value: value),
                ),
              );
            },
          ),



            ]),
          ),
        ),
      ]),
      Container(
        height: 30.0,
        child: Row(children: [
          const Expanded(child: SizedBox()),
          OutlineButton(
              shape: const RoundedRectangleBorder(side: BorderSide.none, borderRadius: BorderRadius.all(Radius.circular(50))),
              textColor: CoreColors.textColor,
              padding: EdgeInsets.zero,
              child: Row(children: const [
                Icon(
                  Icons.location_on_rounded,
                  size: 18,
                ),
                Text(
                  '导航',
                  style: TextStyle(fontSize: 16),
                )
              ]),
              onPressed: () {
                /// 直接唤起高德、百度 app
                showBottomSheetList(
                    context: context,
                    items: ['腾讯地图', '百度地图', '高德地图'],
                    onItemTap: (int index, String item) {
                      if (alarm.longitude.isEmpty || alarm.latitude.isEmpty) {
                        return null;
                      }
                      switch (index) {
                        case 0:
                          List<num> latlng = GISUtil.gps84_To_Gcj02(double.parse(alarm.latitude), double.parse(alarm.longitude));
                          CallMapUtil.callTencentMap(latlng[1], latlng[0]);
                          break;
                        case 1:
                          List<num> latlng = GISUtil.gps84_To_bd09(double.parse(alarm.latitude), double.parse(alarm.longitude));
                          CallMapUtil.callBaiduMap(latlng[1], latlng[0]);
                          break;
                        case 2:
                          List<num> latlng = GISUtil.gps84_To_Gcj02(double.parse(alarm.latitude), double.parse(alarm.longitude));
                          CallMapUtil.callAMap(latlng[1], latlng[0]);
                          break;
                        default:
                      }
                    });
              })
        ]),
      )
    ]));
  }

  ///灾情状态，已完成显示已完成，未完成显示任务反馈按钮，可进行任务反馈操作
  Widget _buildStatusButton() {
    // 登录人绑定了车辆且车辆加入了灾情，同时确保传入的alarmId等于车辆加入的灾情 才显示操作按钮
    if (bindingCarId.isNotEmpty && alertCallId.isNotEmpty && alertCallId == widget.alarmDisaster.sequenceNbr) {
      if (status == TaskFeedBack.finished) {
        return Container(
          height: 30,
          child: OutlineButton(
              shape: const RoundedRectangleBorder(side: BorderSide.none, borderRadius: BorderRadius.all(Radius.circular(50))),
              textColor: CoreColors.textColor,
              padding: EdgeInsets.zero,
              child: Row(children: const [
                Text(
                  '已完成',
                  style: TextStyle(fontSize: 16),
                )
              ]),
              onPressed: () {}),
        );
      } else {
        return ElevatedButton(
          style: ButtonStyle(
            shape: MaterialStateProperty.all(
                const RoundedRectangleBorder(side: BorderSide.none, borderRadius: BorderRadius.all(Radius.circular(50)))),
            backgroundColor: MaterialStateProperty.resolveWith((states) => Colors.blue),
          ),
          child: const Text(
            '任务反馈',
            style: TextStyle(color: Colors.white),
          ),
          onPressed: () async {
            await Get.to(TaskFeedBack(
              bindingCarId: bindingCarId,
              alertCallId: alertCallId,
            ));
            _getStatus();
          },
        );
      }
    } else {
      return Container();
    }
  }

  /// 灾情信息
  Widget buildInfo(BuildContext context) {
    AlarmDisaster alarm = widget.alarmDisaster ?? AlarmDisaster();
    Map<String, dynamic> data = alarm.alarmDetails ?? {};
    return CommonCard(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: [
            LabelValue(label: '发生时间', value: '${data['occurrenceTime'] ?? ''}'),
            const SizedBox(height: 5),
            LabelValue(label: '警情类型', value: '${data['alertType'] ?? ''}'),
            const SizedBox(height: 5),
            LabelValue(label: '警情位置', value: '${data['address'] ?? ''}')
          ],
        ),
      ),
    );
  }

  /// 灾情统计
  Widget buildStatistics(BuildContext context) {
    AlarmDisaster alarm = widget.alarmDisaster ?? AlarmDisaster();
    return CommonCard(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: [
            StatisticsCard(
              itemHeight: 80.0,
              itemWidth: 80.0,
              datas: [
                {
                  'label': '被困人数',
                  'value': alarm.trappedNum,
                  'valueStyle': const TextStyle(color: Colors.red, fontSize: 32.0),
                  'labelStyle': const TextStyle(color: Color(0xff666666), fontSize: 12.0),
                },
                {
                  'label': '伤亡人数',
                  'value': alarm.casualtiesNum,
                  'valueStyle': const TextStyle(color: Color(0xff333333), fontSize: 32.0),
                  'labelStyle': const TextStyle(color: Color(0xff666666), fontSize: 12.0),
                },
                // {
                //   'label': '过火面积',
                //   'value': 8,
                //   'valueStyle': TextStyle(color: Color(0xffff9839), fontSize: 32.0),
                //   'labelStyle': TextStyle(color: Color(0xff666666), fontSize: 12.0),
                // },
              ],
            )
          ],
        ),
      ),
    );
  }

  /// 报警信息
  Widget buildAlarmInfo(BuildContext context) {
    AlarmDisaster alarm = widget.alarmDisaster ?? AlarmDisaster();
    Map<String, dynamic> data = alarm.alarmDetails ?? {};
    return CommonCard(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            LabelValue(label: '报警人', value: '${data['contactUser'] ?? ''}'),
            const SizedBox(height: 5),
            LabelValue(label: '报警电话', value: '${data['contactPhone'] ?? ''}'),
            const SizedBox(height: 5),
            LabelValue(label: '报警时间', value: '${data['callTime'] ?? ''}'),
            const SizedBox(height: 5),
            const LabelValue(label: '报警录音', value: ''),
            const SizedBox(height: 10),
            (widget.alarmDisaster.alarmDetails ?? {})['voiceRecordFile'] != null
                ? Container(
                    padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                    decoration: const BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(6)),
                        gradient: LinearGradient(
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter,
                            colors: <Color>[Colors.lightBlueAccent, Colors.blue])),
                    child: Row(
                      children: [
                        Expanded(
                          child: Image.asset(
                            isPlaySound ? 'assets/audio_play.gif' : 'assets/audio_pause.png',
                          ),
                        ),
                        IconButton(
                            icon: Icon(
                              isPlaySound ? Icons.pause : Icons.volume_up,
                              color: Colors.white,
                            ),
                            onPressed: isPlaySound ? pause : play)
                      ],
                    ))
                : Container(),
            const SizedBox(height: 5),
          ],
        ),
      ),
    );
  }

  /// 救援对象
  Widget buildRescue(BuildContext context) {
    AlarmDisaster alarm = widget.alarmDisaster ?? AlarmDisaster();
    List<dynamic> rescueObject = alarm.rescueObject ?? [];
    return CommonCard(
      child: rescueObject.isEmpty
          ? Container(
              height: 100,
            )
          : Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                  children: rescueObject.map((ele) {
                return Column(children: [LabelValue(label: ele['name'], value: '${ele['value']}'), const SizedBox(height: 5)]);
              }).toList()),
            ),
    );
  }

  /// 救援对象（新）
  Widget buildHelpInfo() {
   
 AlarmDisaster alarm = widget.alarmDisaster ?? AlarmDisaster();
  if(alarm.alarmTypeCode == '230'){
 Map helpDetail = widget.helpInfo;
    String positionImages=  widget.helpInfo['positionImages']?? '';
    String planeImages=   widget.helpInfo['planeImages'] ??'';
     String rescueImages=   widget.helpInfo['rescueImages']??'';
  String appearanceImages=   widget.helpInfo['appearanceImages']??'';

return CommonCard(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(children: [
            const Text(
              '基本信息',
              style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),
            ),
          LabelValue(label: '飞机型号', value: '${helpDetail['aircraftModel'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '中文全称', value: '${helpDetail['fullName'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '飞机长度(m)', value: '${helpDetail['aircraftLength'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '机舱长度(m)', value: '${helpDetail['cabinLength'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '尾翼高度(m)', value: '${helpDetail['tailHeight'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '翼展(m)', value: '${helpDetail['wingspan'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '机身直径(m)', value: '${helpDetail['fuselageDiameter'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '翼展面积(m²)', value: '${helpDetail['wingspanArea'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '发动机类型', value: '${helpDetail['engineType'] ?? ''}'),
          const SizedBox(height: 5),
            LabelValue(label: '发动机数量(台)', value: '${helpDetail['enginesmNum'] ?? ''}'),
          const SizedBox(height: 5),
            LabelValue(label: '发动机型号', value: '${helpDetail['engineModel'] ?? ''}'),
          const SizedBox(height: 5),
            LabelValue(label: '燃油类型', value: '${helpDetail['fuelType'] ?? ''}'),
          const SizedBox(height: 5),
            LabelValue(label: '最大载油量(L)', value: '${helpDetail['oilLoadMax'] ?? ''}'),
          const SizedBox(height: 5),
            LabelValue(label: '标准燃油(KG)', value: '${helpDetail['standardFuel'] ?? ''}'),
          const SizedBox(height: 5),
            LabelValue(label: '空重(KG)', value: '${helpDetail['emptyWeight'] ?? ''}'),
          const SizedBox(height: 5),
            LabelValue(label: '飞机主要构造材料', value: '${helpDetail['structuralMaterial'] ?? ''}'),
          const SizedBox(height: 5),
             LabelValue(label: '氧气瓶数量(组)', value: '${helpDetail['oxygenCylinderNum'] ?? ''}'),
          const SizedBox(height: 5),
             LabelValue(label: '氧气瓶位置描述', value: '${helpDetail['oxygenCylinderLocation'] ?? ''}'),
          const SizedBox(height: 5),    
            const Text(
              '运载能力',
              style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),
            ),
           LabelValue(label: '标准坐席数', value: '${helpDetail['seatNum'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '商载', value: '${helpDetail['commercialLoad'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '货仓容积', value: '${helpDetail['warehouseVolume'] ?? ''}'),
          const SizedBox(height: 5),
           LabelValue(label: '最大起飞总重', value: '${helpDetail['takeoffWeightNum'] ?? ''}'),
          const SizedBox(height: 5),
           LabelValue(label: '最大巡航速度', value: '${helpDetail['cruiseSpeedNum'] ?? ''}'),
          const SizedBox(height: 5),
           LabelValue(label: '航程', value: '${helpDetail['voyage'] ?? ''}'),
          const SizedBox(height: 5),
           const Text(
              '安全措施',
              style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),
            ),
           LabelValue(label: '主要设施', value: '${helpDetail['facilitie'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '主要燃烧物质', value: '${helpDetail['combustionMaterial'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '疏散出口及安全通道', value: '${helpDetail['exitPassage'] ?? ''}'),
          const SizedBox(height: 5),
          Row(
            children: [
            buildImage('外观图', appearanceImages.split(',')),
          ]),
           Row(            
             children: [
            buildImage('平面图',planeImages.split(',')),
          ]),
           Row(
             children: [          
            buildImage('救援图', rescueImages.split(',')),
          ]),
           Row(            
             children: [
            buildImage('方位图',positionImages.split(',')),
          ])

          
        ]),
      ),
    );
  }else{
     Map helpDetail = widget.helpInfo['orgUsrzhDto']??{};
    return CommonCard(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(children: [
          LabelValue(label: '单位名称', value: '${helpDetail['bizOrgName'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '单位地址', value: '${helpDetail['companyLocation'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '所在建筑', value: '${helpDetail['buildName'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '单位性质', value: '${helpDetail['companyNature'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '管理类别', value: '${helpDetail['managementType'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '经营类别', value: '${helpDetail['businessCategory'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '归属机构', value: '${helpDetail['parentName'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '单位电话', value: '${helpDetail['companyPhone'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '女员工数量(人)', value: '${helpDetail['companyFemaleEmployees'] ?? ''}'),
          const SizedBox(height: 5),
          LabelValue(label: '男员工数量(人)', value: '${helpDetail['companyMaleEmployees'] ?? ''}'),
          const SizedBox(
            height: 5,
          ),
          Row(
            children: [
            buildImage('消防通道布置图', widget.helpInfo['scenePicture'] ?? []),
          ]),
           Row(            
             children: [
            buildImage('建筑立面图', widget.helpInfo['facadePicture'] ?? []),
          ]),

           Row(
             children: [          
            buildImage('建筑平面图', widget.helpInfo['planePicture'] ?? []),
          ])
        ]),
      ),
    );
  }


  }




 













  Expanded buildImage(String title, List images) {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.all(4.0),
        child: Column(
          children: [
            Text(title),
            const SizedBox(
              height: 5,
            ),
            images.isEmpty
                ? const Opacity(
                    opacity: 0.6,
                    child: Text(
                      '暂无',
                      style: TextStyle(fontSize: 12),
                    ),
                  )
                :     buildGridimg(images)          
                // FullScreenWidget(
                //     disposeLevel: DisposeLevel.Low,
                //     child:
                //     Image.network(
                //       imageUrl + images[0],
                //       width: 100,
                //     ),
                //   ),
                
          ],
        ),
      ),
    );
  }




  // Widget buildGrid(List formList) {
  //       List<Widget> tiles = [];//先建一个数组用于存放循环生成的widget
  //       Widget content; //单独一个widget组件，用于返回需要生成的内容widget
  //       for(var item in formList) {
  //           tiles.add(
  //            FullScreenWidget(
  //                   disposeLevel: DisposeLevel.Low,
  //                   child:
  //                   Image.network(
  //                     imageUrl + item,
  //                     width: 100,
  //                   ),
  //                 )
  //           );
  //       }
  //       content = Row(
  //           mainAxisAlignment: MainAxisAlignment.start,
  //           children:           
  //             tiles//重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
  //           //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
  //           );
  //       return content;
  //   }


Widget buildGridimg(List formList) {

    List<Widget> tiles = [];//先建一个数组用于存放循环生成的widget
        for(var item in formList) {
            tiles.add(
             FullScreenWidget(
                    disposeLevel: DisposeLevel.Low,
                    child:
                    Image.network(
                      imageUrl + item,
                      width: 100,
                    ),
                  )
            );
        }


    return Wrap(
      spacing: 2, //主轴上子控件的间距
      runSpacing: 5, //交叉轴上子控件之间的间距
      children: tiles, //要显示的子控件集合
    );
  }






  /// 重点部位
  Widget buildImportantPoint() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: widget.keySiteBuildTree
            .map(
              // (e) => Column(
              //   crossAxisAlignment: CrossAxisAlignment.start,
              //   children: [
              //     /*Text(
              //       '${e['name']}',
              //       style: const TextStyle(fontWeight: FontWeight.w700),
              //     ),*/
              //     ...e['children']
              //         .map((item) => InkWell(
              //               onTap: () => Get.to(ImportantPoint(sequenceNbr: item['key'] ?? '')),
              //               child: Padding(
              //                 padding: const EdgeInsets.only(top: 5.0),
              //                 child: Row(
              //                   children: [
              //                     Expanded(
              //                         child: Text(
              //                       item['name'] ?? '',
              //                       overflow: TextOverflow.ellipsis,
              //                       maxLines: 1,
              //                     )),
              //                     const Opacity(
              //                         opacity: 0.6,
              //                         child: Icon(
              //                           Icons.arrow_forward_ios,
              //                           size: 14,
              //                         ))
              //                   ],
              //                 ),
              //               ),
              //             ))
              //         .cast<Widget>()
              //         .toList(),
              //   ],
              // ),
              (e) => Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              InkWell(
                onTap: () => Get.to(ImportantPoint(sequenceNbr: e['key'] ?? '')),
                child: Padding(
                  padding: const EdgeInsets.only(top: 5.0),
                  child: Row(
                    children: [
                      Expanded(
                          child: Text(
                            e['name'] ?? '',
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                          )),
                      const Opacity(
                          opacity: 0.6,
                          child: Icon(
                            Icons.arrow_forward_ios,
                            size: 14,
                          ))
                    ],
                  ),
                ),
              )
            ],
          ),
            )
            .cast<Widget>()
            .toList(),
      ),
    );
  }

  ///力量信息
  Widget buildPowerInfo() {
    if (widget.powerInfo == null || widget.powerInfo.isEmpty) {
      return Container();
    }
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: widget.powerInfo
            .map(
              (e) => Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  /*Text(
                    '${e['companyName']}：出动${e['carNum']}辆车${e['userNum']}人',
                    style: const TextStyle(fontWeight: FontWeight.w700),
                  ),*/
                  ...e['powerCarCountDto']
                      .map((item) => Padding(
                          padding: const EdgeInsets.only(top: 3),
                          child: Text('${item['carName']}：${item['carNum']}辆 '
                              '${item['plateNumber']}')))
                      .cast<Widget>()
                      .toList(),
                ],
              ),
            )
            .cast<Widget>()
            .toList(),
      ),
    );
  }

  /// 战斗统计
  Widget buildFightingStatistics(BuildContext context) {
    AlarmDisaster alarm = widget.alarmDisaster ?? AlarmDisaster();
    Map<String, dynamic> strengthCount = alarm.strengthCount ?? {};
    List data = strengthCount.keys.toList();
    var config = {
      'person': {'backgroundColor': const Color(0xffebf7ee), 'valueColor': const Color(0xff2ec454), 'label': '到场人员'},
      'car': {'backgroundColor': const Color(0xfff7f0eb), 'valueColor': const Color(0xffff7803), 'label': '到场车辆'},
      'equip': {'backgroundColor': const Color(0xffebebf7), 'valueColor': const Color(0xff2580ec), 'label': '车载器材'},
      'medicament': {'backgroundColor': const Color(0xffe7ebf1), 'valueColor': const Color(0xfffc0a83), 'label': '车载药剂'},
      'water': {'backgroundColor': const Color(0xfff2ebf7), 'valueColor': const Color(0xff9d03ff), 'label': '车载水量'}
    };
    List datas = data.map((element) {
      Map<String, dynamic> map = {
        'backgroundColor': (config[element] ?? {})['backgroundColor'] ?? const Color(0xffebf7ee),
        'valueColor': (config[element] ?? {})['valueColor'] ?? const Color(0xff2ec454),
        'value': strengthCount[element]['count'],
        'total': strengthCount[element]['total'],
        'label': (config[element] ?? {})['label']
      };
      return map;
    }).toList();
    return CommonCard(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: StatisticsGridCard(
            itemHeight: 99.0,
            itemWidth: 99.0,
            rows: 4,
            datas: datas,
            itemBuilder: (item) {
              return buildCircle(
                  backgroundColor: item['backgroundColor'],
                  valueColor: item['valueColor'],
                  value: item['value'],
                  total: item['total'],
                  label: item['label']);
            }),
      ),
    );
  }

  Widget buildCircle({Color backgroundColor, Color valueColor, num total, String label, num value}) {
    int percent;
    if (total == 0 || total == 0.0) {
      percent = 0;
    } else {
      percent = ((value / total) * 100).toInt();
    }
    Logger.warn('$label:$percent');
    return SpinProgress(
      type: ProgressType.circle,
      percent: percent,
      showInfo: true,
      lineWidth: 6.0,
      radius: 60,
      backgroundColor: backgroundColor,
      valueColor: valueColor,
      format: (val) => '$val',
      buildInfo: (fmtValue) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '${value is double ? value.toInt() : value}',
              style: const TextStyle(color: Color(0xff121d3c), fontSize: 24.0),
            ),
            Text(
              label ?? '',
              style: const TextStyle(color: Color(0xff999999), fontSize: 9.0),
            )
          ],
        );
      },
    );
  }

  ///获取图标
  String _getTypeIcon(String typeCode) {
    switch (typeCode) {
      case '229':
        return 'assets/images/yi_ban_sub.png';
      case '230':
        return 'assets/images/hang_kong_qi_sub.png';
      case '235':
        return 'assets/images/tu_fa_shi_jian_sub.png';
      case '237':
        return 'assets/images/lou_you_sub.png';
      case '238':
        return 'assets/images/zhuan_ji_bao_zhang_sub.png';
      case '1214':
        return 'assets/images/120_ji_jiu_sub.png';
      case '242':
        return 'assets/images/other_sub.png';
      default:
        return 'assets/images/other_sub.png';
    }
  }

  ///获取灾情状态
  void _getStatus() {
    Future.wait(<Future>[API.getAlertCalledId(), API.getAlertCalledData()]).then((value) {
      if (value.first != null && value.last != null) {
        bindingCarId = value.first['carId'] ?? '';
        alertCallId = value.last['sequenceNbr'] ?? '';
        if (bindingCarId.isNotEmpty && alertCallId.isNotEmpty) {
          API.getCurrentCarOrTaskState(bindingCarId, alertCallId).then((value) {
            if (value != null) {
              setState(() {
                status = value['status'] ?? '';
                statusName = value['statusName'] ?? '';
              });
            }
          });
        }
      }
    });
  }

  ///获取救援预案
  void _getPlan(String sequenceNbr) {
    API.getSituation(sequenceNbr).then((value) {
      if (value != null) {
        setState(() {
          plans.addAll(value);
        });
      }
    });
  }

  ///获取力量信息
  void _getPowerInfo(String sequenceNbr) {
    API.getPowerInfo(sequenceNbr).then((value) {
      if (value != null) {
        setState(() {
          powerInfo.addAll(value);
        });
      }
    });
  }

  ///获取救援对象
  void _getOrgUsrzhDto(String sequenceNbr) {
    API.getOrgUsrzhDto(sequenceNbr).then((value) {
      if (value != null) {
        setState(() {
          helpInfo.addAll(value);
        });
      }
    });
  }

  ///获取重点部位树
  void _getKeySiteBuildTree(String sequenceNbr) {
    API.getKeySiteBuildTree(sequenceNbr).then((value) {
      if (value != null) {
        setState(() {
          keySiteBuildTree.addAll(value);
        });
      }
    });
  }
}


