import 'dart:convert';
import 'dart:ui';

import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:flutter/material.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/common/no_data.dart';

import './../native_bridge.dart';
import './alarm_set_position.dart';
import './assembly_point.dart';
import './select_car_status.dart';
import './select_resource_type.dart';
import 'commandStream.dart';
import 'dart:async';
import 'package:amos_iot_login_tpl/const/global_config.dart';

/// 图标按钮宽度
const double _iconSize = 40.0;

/// 确保size大小在 40~80 之间
double _getIconSize(double value) {
  if (value.px < 40.0) {
    return 40.0;
  } else if (value.px > 80.0) {
    return 80.0;
  }
  return value.px;
}

/// 地图工具
/// 定位
/// 右侧  消防资源、集结点、警情定位、消防车辆、回到灾点、清除
class MapTools extends StatefulWidget {
  const MapTools({
    Key key,
    this.callJSMethod,
    this.currentLngLat,
    this.alarmId,
    this.h5Url,
    this.token,
  }) : super(key: key);
  final ExecuteJSMethod callJSMethod;
  final String alarmId;
  final String token;
  final String h5Url;
  final Map currentLngLat;

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

class MapToolsState extends State<MapTools> {
  List<String> _selectKeys = [];
  List<Map<String, String>> carStatus = [];
  List commandFlows = []; //指令流
  String bindingCarId = ''; //绑定的车辆ID
  String alertCallId = ''; //加入的灾情ID
  String selectKey = ''; //车辆状态
  String selectKeyName = ''; //车辆状态名称
  String imageUrl = '';
  bool commandFlowShow = false;
  Timer timer;
  @override
  void initState() {
    super.initState();
    getCurrentStatus();
    getAllStatus();
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imageUrl = value;
      });
    });
  }

  @override
  void didUpdateWidget(covariant MapTools oldWidget) {
    super.didUpdateWidget(oldWidget);
    getCommandFlow();
  }

  @override
  void dispose() {
    super.dispose();
    // 清除定时器
    timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    Function callback = widget.callJSMethod;
    double size = _getIconSize(_iconSize);
    return Stack(
      children: [
        // 登录人绑定了车辆且车辆加入了灾情，同时确保传入的alarmId等于车辆加入的灾情 才显示操作按钮
        (bindingCarId.isNotEmpty && alertCallId.isNotEmpty && alertCallId == widget.alarmId)
            ? Positioned(
          top: 10,
          right: 5.0,
          child: IconBtnGroup(
            vertical: true,
            enableFeedback: true,
            children: [
              IconBtnGroup.customBtn(
                padding: const EdgeInsets.symmetric(vertical: 6.0),
                onPressed: () {
                  /// do nothing
                },
                child: PopoverButton(
                    direction: PopoverDirection.bottom,
                    popWidth: 300,
                    popHeight: 275,
                    barrierColor: Colors.black26,
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 13.0, vertical: 3),
                      child: Row(children: [
                        Image.asset(
                          'assets/images/car_status.png',
                          width: 20,
                        ),
                        const SizedBox(
                          width: 5,
                        ),
                        Text(
                          selectKeyName ?? '',
                          style: const TextStyle(fontSize: 15),
                        ),
                      ]),
                    ),
                    builder: (context) {
                      return StatefulBuilder(builder: (BuildContext context, StateSetter ss) {
                        return CarStatusSelect(
                          bindingCarId: bindingCarId ?? '',
                          alertCallId: alertCallId ?? '',
                          selectKey: selectKey ?? '',
                          carStatus: carStatus,
                          ok: () {
                            getCurrentStatus();
                          },
                        );
                      });
                    }),
              )
            ],
          ),
        )
            : Container(),
        Positioned(
          top: 90,
          right: 5.0,
          child: IconBtnGroup(
            width: size,
            vertical: true,
            enableFeedback: true,
            children: [
              /// 消防资源
              // buildBtn('资源', 'assets/icon/resource.png', () {
              //   /// 显示选择
              //   // openSourceTypeDialog(context,);
              //   openSourceTypeSheet(context);
              // }),
              _buildPopSourceType(context),
              IconBtnGroup.divider(width: 16, height: 1),

              /// 集结点
              buildBtn('集结', 'assets/icon/assembly-point.png', () {
                Navigator.push(context, MaterialPageRoute(builder: (context) {
                  return AssemblyPointSet(callh5: callback, h5Url: widget.h5Url, alarmId: widget.alarmId, token: widget.token);
                })).then((value) {
                  if (value != null) {
                    /// 保存完集结点之后，执行刷新操作
                    /// 采用 callback 执行主地图消息
                    // callback('refreshAssemblyPoint()');
                    callback('$value()');
                  }
                });
              }),
              IconBtnGroup.divider(width: 16, height: 1),

              /// 警情定位
              buildBtn('定位', 'assets/icon/fire.png', () {
                Navigator.push(context, MaterialPageRoute(builder: (context) {
                  return AlarmPositionSet(callh5: callback, alarmId: widget.alarmId, h5Url: widget.h5Url, token: widget.token);
                })).then((value) {
                  if (value != null) {
                    /// 保存完集结点之后，执行刷新操作
                    /// 采用 callback 执行主地图消息
                    // callback('refreshAssemblyPoint()');
                    callback('$value()');
                  }
                });
              }),
              IconBtnGroup.divider(width: 16, height: 1),

              /// 消防车辆
              buildBtn('车辆', 'assets/icon/car.png', () {
                callback('fireCarPoint()');
              }),
              IconBtnGroup.divider(width: 16, height: 1),

              /// 回到灾点
              buildBtn('复位', 'assets/icon/shape.png', () {
                callback('locationAlarm()');
              }),
              IconBtnGroup.divider(width: 16, height: 1),

              /// 清除
              buildBtn('清除', 'assets/icon/clear.png', () {
                callback('mapClear()');
                setState(() {
                  _selectKeys = [];
                });
              }),
            ],
          ),
        ),
        Positioned(
          left: 5.0,
          bottom: 270.0,
          child: IconBtnGroup.iconBtnOne(
              width: size,
              height: size,
              icon: buildImage('assets/icon/poi.png'),
              onPressed: () {
                if (widget.currentLngLat.isEmpty) {
                  ToastUtils.showToast('经纬度信息获取失败');
                }
                String args = jsonEncode(widget.currentLngLat);

                /// 调用 js 端的 geoLocation
                callback('geoLocation($args)');
              }),
        ),
        Positioned(
          left: 5.0,
          top: 25.0,
          child: GestureDetector(
            child: Container(
              child: const Text('作战指令'),
              padding: const EdgeInsets.all(5),
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(2)),
                  color: Colors.white,
                  boxShadow: <BoxShadow>[CoreColors.boxShadow]),
            ),
            onTap: () {
              const timeout =  Duration(seconds: 10);
              timer?.cancel();
              timer=Timer.periodic(timeout, (timer) { //callback function
                //1s 回调一次
                getCommandFlow();
              });
              //判断清理定时器
              if(commandFlowShow){
                timer?.cancel();
              }
              setState(() {
                commandFlowShow = !commandFlowShow;
              });


            },
          ),
        ),
        Positioned(
          left: 5.0,
          top: 65.0,
          child: Container(
            width: commandFlowShow ? window.physicalSize.width/window.devicePixelRatio-10 : 0,
            height: commandFlowShow ? 550 : 0,
            padding: const EdgeInsets.all(8.0),
            decoration: BoxDecoration(
                borderRadius: const BorderRadius.all(Radius.circular(10)),
                color: Colors.white,
                boxShadow: <BoxShadow>[
                  CoreColors.boxShadow,
                ]),
            child: Column(
              children: [
                Row(
                  children: [
                    const Expanded(
                        child: Text(
                          '指令流',
                          style: TextStyle(fontWeight: FontWeight.w700, fontSize: 15),
                        )),
                    IconButton(
                        icon: const Icon(
                          Icons.close,
                          size: 18,
                        ),
                        onPressed: () {
                          setState(() {
                            commandFlowShow = false;
                          });
                        })
                  ],
                ),
                const SizedBox(
                  height: 5,
                ),
                commandFlows.isNotEmpty ? buildCommandStreamNew() : const NoData(),
                //buildCommandStreamNew(),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Expanded buildCommandStreamNew() {
    return Expanded(
      child: CommandStream(commandFlows: commandFlows),
    );
  }

  Expanded buildCommandStream() {
    return Expanded(
      child: ListView.separated(
          shrinkWrap: true,
          itemBuilder: (BuildContext context, int index) {
            return Column(
              children: [
                Row(
                  children: [
                    Expanded(
                        child: Text(
                          '${commandFlows[index]['type']}',
                          overflow: TextOverflow.ellipsis,
                        ))
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                        child: Text(
                          '${commandFlows[index]['submissionTime']}',
                          overflow: TextOverflow.ellipsis,
                        )),
                    Expanded(
                        child: Text(
                          '${commandFlows[index]['company']}',
                        )),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                        child: Text(
                          '${commandFlows[index]['content']}',
                          softWrap: true,
                          // overflow: TextOverflow.ellipsis,
                        ))
                  ],
                ),
              ],
            );
          },
          separatorBuilder: (BuildContext context, int index) {
            return const Divider(
              color: Colors.black,
              thickness: 0.5,
            );
          },
          itemCount: commandFlows.length),
    );
  }

  Widget buildBtn(String name, String imageAsset, Function onPressed) {
    double size = _getIconSize(_iconSize);
    return IconBtnGroup.customBtn(
        padding: const EdgeInsets.all(6.0),
        child: Column(children: [
          Image.asset(
            imageAsset,
            width: size * (2 / 3),
            height: size * (2 / 3),
          ),
          Text(
            name,
            style: const TextStyle(fontSize: 12),
          ),
        ]),
        onPressed: onPressed);
  }

  Widget buildImage(name) {
    double size = _getIconSize(_iconSize);
    return Image.asset(
      name,
      width: size * (2 / 3),
      height: size * (2 / 3),
    );
  }

  /// 顶部打开方式选择资源类型
  void openSourceTypeSheet(BuildContext context) {
    Function callback = widget.callJSMethod;
    TopSheetDialog.show(
        context: context,
        child: StatefulBuilder(builder: (BuildContext context, StateSetter ss) {
          return SelectResourceTypePanel(
            onChanged: (selectKeys) {
              _selectKeys = selectKeys;
            },
            selectKeys: _selectKeys,
            reset: () {
              setState(() {
                _selectKeys = [];
                ss(() {});
              });
            },
            ok: () {
              String args = jsonEncode(_selectKeys);
              callback('addResources($args)');
            },
          );
        }),
        backgroundColor: Colors.transparent,
        direction: TopSheetDialogDirection.TOP);
  }

  Widget _buildPopSourceType(BuildContext context) {
    double size = _getIconSize(_iconSize);
    Function callback = widget.callJSMethod;
    return IconBtnGroup.customBtn(
      padding: const EdgeInsets.symmetric(vertical: 6.0),
      onPressed: () {
        /// do nothing
      },
      child: PopoverButton(
          direction: PopoverDirection.left,
          popWidth: 300,
          popHeight: 216,
          barrierColor: Colors.black26,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 6.0),
            child: Column(children: [
              Image.asset(
                'assets/icon/resource.png',
                width: size * (2 / 3),
                height: size * (2 / 3),
              ),
              const Text(
                '资源',
                style: TextStyle(fontSize: 12),
              ),
            ]),
          ),
          builder: (context) {
            return StatefulBuilder(builder: (BuildContext context, StateSetter ss) {
              return SelectResourceTypePanel(
                onChanged: (selectKeys) {
                  _selectKeys = selectKeys;
                },
                selectKeys: _selectKeys,
                reset: () {
                  setState(() {
                    _selectKeys = [];
                    ss(() {});
                  });
                },
                ok: () {
                  String args = jsonEncode(_selectKeys);
                  callback('addResources($args)');
                },
              );
            });
          }),
    );
  }

  ///获取车辆当前状态
  void getCurrentStatus() {
    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(() {
                selectKey = value['carStatus'] ?? '';
                selectKeyName = value['carStatusName'] ?? '';
              });
            }
          });
        }
      }
    });
  }

  ///获取车辆所有状态
  void getAllStatus() {
    API.gwmcDataDictionaryCARSTATE().then((value) {
      if (value != null) {
        setState(() {
          value.forEach((item) {
            carStatus.add({'key': item['id'], 'label': item['name']});
          });
        });
      }
    });
  }

  ///获取指令流
  void getCommandFlow() {
    if (widget.alarmId == null || widget.alarmId == '') {
      return;
    }
    //'1530020836492886000'
    API.getCommandFlow(widget.alarmId).then((value) {
      if (value != null) {
        var list = value.map((v){
          // 指令流图片加上基地址
          v['content'] = v['content'].toString().replaceAll('src="','src="'+imageUrl);
          return v;
        }).toList();
        setState(() {
          commandFlows.clear();
          commandFlows.addAll(value);
        });
      }
    });
  }
}
