import 'package:amos_iot_login_tpl/mine/offline/GetConfig.dart';
import 'package:amos_iot_login_tpl/mine/offline/color.dart';
import 'package:flutter/material.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';
import 'package:safe_control/model/name_value.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'dart:convert';
import 'package:jcs_airport/services/api.dart';
import './DottedLine.dart';
import './pin_text_dialog.dart';
import 'HandleEemergenry.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../timeline/timeline.dart';
import '../timeline/timeline_entity.dart';
import '../sign/SearchWidget.dart';
import 'package:amos_flutter_utils/utils.dart';
import 'dart:math';

class MyEmergencyTask extends StatefulWidget {
  
  @override
  _MyEmergencyTaskState createState() => _MyEmergencyTaskState();
}

class _MyEmergencyTaskState extends State<MyEmergencyTask>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  bool isAnimating = false;

  bool isAnimatingN = true;

  bool _isPanelOpen = false;

  List<String> status = ['success',  'default'];

  /// 抽屉控制器
  final AmosDrawerController _drawerController = AmosDrawerController();

  // 线路数据
  List<Map<String, dynamic>> routeList = [];
  // 当前选择的线路数据
  NameValue selectRoute;

  List<TimelineEntity> timeList = [];

  List<TimelineEntity> oneTimeList = [];

  // 应急任务
  List dataList = [];

  // 应急任务
  List dataListAll = [];

  String batchNo = '';
  // 当前页码
  int pageIndex = 1;

  String roleCode = "";

  // 每页条数
  int pageSize=100;

  String dataType='1';
  
  String server ='';
  String port ='';

  String expand ='';
  
  // 是否有下一页
  bool hasNext = false;

  bool _isFooter = true;
  // 分页所需控件
  // GlobalKey<EasyRefreshState> _easyRefreshKey = new GlobalKey<EasyRefreshState>();
  // GlobalKey<RefreshHeaderState> _headerKey = new GlobalKey<RefreshHeaderState>();
  // GlobalKey<RefreshFooterState> _footerKey = new GlobalKey<RefreshFooterState>();

  String theme="";
  TextEditingController _controller = new TextEditingController();
  FocusNode _focusNode = new FocusNode();
  EasyRefreshController _controllers = EasyRefreshController();

  MqttServerClient client;

  @override
  void initState() {
    super.initState();
    initConfig();

  }

  initConfig() async {
    final prefs = await SharedPreferences.getInstance();

    setState(() {
      server = prefs.getString("mqttUrl");
       port = prefs.getString("port");
       roleCode = prefs.getString("roleCode");
       if(prefs.getString("taskNum") == 0) {
         expand = 'false';
       } else {
         expand = 'true';
       }
    });

    client = MqttServerClient(server,'mqttjsa_${getRandomString()}');
    client.useWebSocket = true;
    client.port = int.parse(port);

    client.onConnected = onConnected; //连接成功回调
    client.onDisconnected = onDisConnected; //连接断开回调
    client.onSubscribed = onSubscribed; //订阅成功回调
    client.connect();
    getData();
    //监听消息
    client.updates.listen((List<MqttReceivedMessage<MqttMessage>> c) {
      final MqttPublishMessage message = c[0].payload;
      final payload = Utf8Decoder().convert(message.payload.message);
      print('消息:$payload,主题: <${c[0].topic}>');
      print('我的任务=======>');
      dynamic msg = json.decode(payload);
      print(msg["msgType"]);
      if (msg["msgType"] == 'refreshTaskRecord'){
        // getData();
      } else if(msg["msgType"] == 'getStepList'){
        getMessageData(msg["planStep"]);
        getMessageTaskData(msg["planTask"]);
        // getData();
      } else if(msg["msgContext"] != null && msg["msgContext"]['content'] == 'stopPlan'){
        print('预案结束执行=======>');
       // getData();
      }
    });
  }

  String getRandomString(){
    String str = '';
    for(int i=0 ;i<=11;i++) {
      var rng = Random();
      str = '$str${rng.nextInt(100).toString()}';
    }
    return str;
  }

  List<TimelineEntity> getDatas(){
    bool open = this._isPanelOpen;
    if(open) {
      return timeList;
    } else {
      return oneTimeList;
    }
  }

  //页面销毁时关闭连接
  @override
  void dispose(){
    client.disconnect(); //断开连接
    super.dispose();
  }

  void onConnected() {
    print('连接成功');
    init();
  }

  void onDisConnected() {
    print('断开连接');
    client.connect();
  }

  void init() async {
      await client.subscribe("/AMOS-AUTOSYS/yinan/plan", MqttQos.atMostOnce);
  }

  // 订阅主题成功
  void onSubscribed(String topic) {
    print('订阅主题$topic成功');
  }

  void getMessageTaskData(dynamic result) async{
    var task = [];
    for (dynamic p in result) {
      if(roleCode.contains(p['roleCode'])) {
        if(!p['runstate']) {
          task.add(p);
        }
      }
    }
    if(dataList.length != task.length) {
      setState(() {
        dataList = task;
        dataListAll = task;
      });
    }
  }

  void getMessageData(dynamic result) async{
    var i = 0;
    timeList = [];
    oneTimeList = [];
    for (dynamic p in result) {
      if(i == 0) {
        if(p['time'] != null) {
          oneTimeList.add(TimelineEntity(
              id: '$i',
              status: status[0],
              statusStr: p['stepName'],
              title: p['time'],
              description: ''
          ));
        }
      }
      if(p['time'] != '') {
        timeList.add(TimelineEntity(
            id: '$i',
            status: status[0],
            statusStr: p['stepName'],
            title: p['time'],
            description: ''
        ));
      } else  {
        timeList.add(TimelineEntity(
            id: '$i',
            status: status[1],
            statusStr: p['stepName'],
            title: p['time'],
            description: ''
        ));
      }
      i++;
    }

    setState(() {
      timeList;
      oneTimeList;
    });
  }

  void getData() async{

    var result = await API.getUserOperateCountAndPlanName();
    if(result == null) {
      setState(() {
        dataList = [];
        isAnimatingN = false;
      });
    } else if (result.length == 0 || result.length == 1 || result["result"] == 'FAILURE') {
      setState(() {
        dataList = [];
        isAnimatingN = false;
      });
    } else {
      var result1 = await API.selectTaskActionPage(result['batchNo'], dataType, pageIndex, pageSize);

      var result2 = await API.getPlanStep(result['batchNo']);

      if(result2 == null) {

      } else if (result2.length == 0 || result2["result"] == 'FAILURE') {

      } else {
       //  var current = result2['msgContext']['currentStep'];
        var i = 0;
        timeList = [];
        oneTimeList = [];
        for (dynamic p in result2['msgContext']['step']) {
          if(i == 0) {
            if(p['time'] != '' && null != p['time'] ) {
              oneTimeList.add(TimelineEntity(
                  id: '$i',
                  status: status[0],
                  statusStr: p['stepName'],
                  title: null ==  p['time'] ? '' : p['time'],
                  description: ''
              ));
            } else  {
              oneTimeList.add(TimelineEntity(
                  id: '$i',
                  status: status[1],
                  statusStr: p['stepName'],
                  title: null ==  p['time'] ? '' : p['time'],
                  description: ''
              ));
            }
          }
          if(p['time'] != '' && null != p['time'] ) {
            timeList.add(TimelineEntity(
                id: '$i',
                status: status[0],
                statusStr: p['stepName'],
                title: null ==  p['time'] ? '' : p['time'],
                description: ''
            ));
          } else  {
            timeList.add(TimelineEntity(
                id: '$i',
                status: status[1],
                statusStr: p['stepName'],
                title: null ==  p['time'] ? '' : p['time'],
                description: ''
            ));
          }
          i++;
        }
      }

      if(result1 == null) {
      } else if (result1.length == 0 || result1["result"] == 'FAILURE') {
      } else {
        setState(() {
          dataList = [];
          for (dynamic p in result1['records']) {
            dataList.add(p);
            dataListAll.add(p);
          }
          pageIndex = result1['current'];
          batchNo = result['batchNo'];
          // batchNo = '7d2bf640-06cd-4dcc-9333-7f2194d10cc8';
          isAnimating = false;
          if (result1['current'] < result1['pages']) {
            hasNext = true;
          }
        });
      }

      setState(() {
        isAnimatingN = false;
      });
    }
  }

  void getDatNew()async{

    var result = await API.getUserOperateCountAndPlanName();
    if(result == null) {
    } else if (result.length == 0 || result["result"] == 'FAILURE') {
    } else {
      var result1 = await API.selectDisposalActionPage(result['batchNo'],dataType,pageIndex,pageSize);

      if(result1 == null) {
      } else if (result1.length == 0 || result1["result"] == 'FAILURE') {
      } else {
        setState(() {
          // dataList = [];
          for (dynamic p in result1['records']) {
            dataList.add(p);
          }
          pageIndex = result1['current'];
          batchNo = result['batchNo'];
          // batchNo = '7d2bf640-06cd-4dcc-9333-7f2194d10cc8';
          isAnimating = false;
          if (result1['current'] < result1['pages']) {
            hasNext = true;
          } else {
            hasNext = false;
          }
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
      return WillPopScope(
          onWillPop: () async {

        return true;
      },
    child: ModalProgressHUD( child: Scaffold(
                appBar: AppBar(
                  title:  const Text(
                    '待处置任务',
                    style:  TextStyle(
                      color: Colors.black,
          //              fontWeight: FontWeight.bold,
                    ),
                  ),
                  centerTitle: true,
                  actions: <Widget>[

                  ],
                  elevation: 0.2,
                  brightness: Brightness.light,
                  backgroundColor: KColorConstant.topBarColor,
                  leading: Container(
                    child: GestureDetector(
                      onTap: () => {
                        Navigator.pop(context)
                      },
                      child:Icon(Icons.keyboard_arrow_left, color: GetConfig.getColor(theme), size: 32),
                    ),
                  ),
                ),
                body: Stack(
                    children: <Widget>[
                      ModalProgressHUD(
                      child:_getWidget(),
                      inAsyncCall: isAnimating,
                      opacity: 0.7,
                      progressIndicator: const CircularProgressIndicator(),
                      ), buildDrawerWidget(),],
                  alignment: Alignment.bottomCenter,),
                resizeToAvoidBottomPadding: false,
              ),
            inAsyncCall: isAnimatingN,
            opacity: 1,
            progressIndicator: const CircularProgressIndicator(),
          )
      );

  }


  ///构建底部对齐的抽屉效果视图
  Widget buildDrawerWidget() {
    ///层叠布局中的底部对齐
    return Container(
      width: 380,
      height: 700,
      child:Align(
        alignment: Alignment.bottomCenter,
        child: AmosDrawer(
          maxHeight: 700,
          minHeight: 70.0,
          enabledParallax: true,
          isDraggable: false,
          padding: EdgeInsets.all(0.0),
          margin: EdgeInsets.all(0.0),
          direction: SlidingDirection.UP,
          panelSnapping: false,
          controller: _drawerController,
          enabledMask: false,
          hidePanel: false,
          parallaxOffset: 0.8,
          defaultDrawerState: AmosDrawerState.CLOSED ,
          showCrossBar: false,
          panelBuilder: (sc) => _panel(sc),
        ),
      ),
    );
  }

  Widget _getWidget() {
    return buildInnerList();
  }

  /// 标题横线
  Widget buildCrossBar() {
    Color color =
    _isPanelOpen ? CoreColors.primaryColor : CoreColors.borderColorBase;
    return  Row(
      ///居中
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        InkWell(
          onTap: () {
            if (_isPanelOpen) {
              setState(() {
                _isPanelOpen = false;
              });
              _drawerController.close();
            } else {
              setState(() {
                _isPanelOpen = true;
              });
              _drawerController.open();
            }
            setState(() {});
          },
          child:
            Container(
                margin: EdgeInsets.fromLTRB(10,0,30,10),
                child: Icon(
                  _isPanelOpen == true ? Icons.keyboard_arrow_down  : Icons.keyboard_arrow_up,
                  color: Colors.blue,
                  size: 28,
                ),
            ),
        )
      ],
    );
  }

  Widget _panel(ScrollController sc) {
    final List<TimelineEntity> list = getDatas();
    if(list.length != 0) {
      return MediaQuery.removePadding(
          context: context,
          removeTop: true,
          child: Stack(
              children: <Widget>[
                new Container(
                  constraints: BoxConstraints(minHeight: 30, maxHeight: 1000.0),
                  child:  Column(
                    children: <Widget>[
                      new Container(
                        alignment: Alignment.topLeft,
                        padding: EdgeInsets.fromLTRB(27, 0, 0, 0),
                        child: new Text(
                          '',
                          style: new TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 15,
                            color:  Colors.black,
                          ),
                        ),
                      ),
                      Expanded(
                        child: new Container(
                          child: TimelineNew(
                            timelineList: list,
                            lineColor: Colors.blue,
                            dotColor: Colors.blue,
                            backgroundColor: Colors.white,
                            textColor: Colors.grey,
                          ),
                        ),
                      )

                    ],
                  ),
                ), buildCrossBar(),]
          )
      );
    } else {
      return Container();
    }
  }

  void entryCode(context,batchNo,category) {
    // 销毁二维码识别
    showDialog(
        context: context,
        builder: (ctx) {
          return PinTextDialog(
            theme: theme,
            batchNo:batchNo,
            category: category,
            callback: (value) {
            },
            cancel: () {
              // getRSCamera();
            },
          );
        });
  }


  // ScrollController scrollController =  ScrollController();
  // GlobalKey globalKey2 =  GlobalKey();

  Widget buildInnerList() {
    if(dataListAll.length != 0) {
      return  Stack(
        children: <Widget>[
          // CustomScrollView(
          //     controller: scrollController,
          //     slivers: <Widget>[
          //       SliverList(
          //           delegate:  SliverChildBuilderDelegate(
          //                   (BuildContext context, int index) {
          //               }, childCount: routeList.length)),
          //
          //     ]),
          Padding(
              padding:  const EdgeInsets.only(top: 10.0),
              child:  Stack(children: <Widget>[
                Column(
                  children: <Widget>[
                    buildSearch(),
                    Expanded(child:  Container(
                      margin: const EdgeInsets.only(bottom: 100),
                      child: GestureDetector(
                        child: Center(
                          child: EasyRefresh(
                            enableControlFinishRefresh: false,
                            enableControlFinishLoad: true,
                            controller: _controllers,
                            footer: MaterialFooter(),
                            header: MaterialHeader(),
                            child:
                            ListView.builder(
                              //ListView的Item
                              itemCount: dataList.length,
                              itemBuilder: (BuildContext context, int index) {
                                return Container(
                                  margin: const EdgeInsets.only(left: 15,right: 15),
                                  child: Card(
                                      elevation:0.2,
                                      child:  ListTile(
                                          isThreeLine: true,
                                          dense: false,
                                          subtitle:  Column(
                                            crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                            children: <Widget>[
                                              Text(
                                                dataList[index]['category'],
                                                style:  const TextStyle(
                                                    fontSize: 18.0,
                                                    fontWeight:
                                                    FontWeight.w600),
                                              ),
                                              const Padding(
                                                padding:
                                                EdgeInsets.only(top: 5),
                                              ),
                                              Text(
                                                '推送时间:' +
                                                    ( dataList[index]['createTime'] == null ?  dataList[index]['createDate'] : dataList[index]['createTime']),
                                                style:  const TextStyle(
                                                    fontSize: 14.0,
                                                    color: Colors.grey),
                                              ),
                                              const Padding(
                                                padding:
                                                EdgeInsets.only(top: 5),
                                              ),
                                              Text(
                                                '事件名称:' +
                                                    dataList[index]['name'],
                                                style:  const TextStyle(
                                                    fontSize: 14.0,
                                                    color: Colors.grey),
                                              ),
                                              const Padding(
                                                padding:
                                                EdgeInsets.only(top: 5),
                                              ),
                                              const DottedLine(
                                                height: 1,
                                              ),
                                              Column(
                                                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                                crossAxisAlignment: CrossAxisAlignment.center,
                                                children: <Widget>[
                                                  buildBtn(dataList[index]),
                                                  Align(
                                                    alignment: Alignment.center,
                                                    child: FlatButton(
                                                        minWidth:20,
                                                        padding: const EdgeInsets.all(5),
                                                        child: const Text('@回复'),
                                                        onPressed: () {
                                                          entryCode(context,dataList[index]['batchNo'],dataList[index]['category']);
                                                        }
                                                    ),
                                                  ),

                                                  // buildBtn(dataList[index]),
                                                ],
                                              )
                                            ],
                                          ),
                                          // trailing:  Padding(
                                          //   child:  Icon(
                                          //     Icons.keyboard_arrow_right,color: GetConfig.getColor(theme),),
                                          //   padding: const EdgeInsets.only(top: 15),
                                          // ),
                                          onTap: () {
                                            // client.disconnect();
                                            Navigator.push(context,
                                                MaterialPageRoute(
                                                    builder: (context) {
                                                      return  HandleEemergenry(
                                                          expand,batchNo:dataList[index]['batchNo']);
                                                    })).then((value) {
                                              // setState(() {
                                              //   dataList = [];
                                              // });
                                              getData();});
                                          })),
                                );
                              },
                            ),
                            onRefresh: () async {
                              // await  new Future.delayed(
                              //     const Duration(seconds: 1), () {
                              //   setState(() {
                              //     dataList = [];
                              //     pageIndex = 1;
                              //   });
                              //   _controllers.resetLoadState();
                              //   // _controllers.resetLoadState();
                              //   getData();
                              // });
                            },
                            onLoad: hasNext == true ? () async {
                              await new Future.delayed(
                                  const Duration(seconds: 1), () {
                                setState(() {
                                  pageIndex = pageIndex + 1;
                                });
                                if (hasNext) {
                                  _controllers.resetLoadState();
                                  getDatNew();
                                }
                                // Future.delayed(Duration(milliseconds: 1000), () {
                                //   setState(() {
                                //     _isFooter = true;
                                //   });
                                // });
                              });
                            } : null,
                          ),
                        ),
                      ),
                    ))
                  ],
                ),
              ])),
        ],
      );
    } else {
      return Container( child: Column( children: [Text('', style: TextStyle(height: 10),),Image.asset('assets/images/zwrw.png', package: 'jcs_airport',), Text('暂无任务', style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1)),)],));
    }
  }

  Widget buildSearch() => SearchWidget(
      onEditingComplete: onchange
  );

  void onchange(key) {
    final res = this.dataListAll.where((element)  {
        final entry = element["category"];
        return entry.contains(key);
    }).toList();
    // final res = this.widget.persons.where((element) {
    //   final entry = element["name"];
    //   return entry.contains(key);
    // }).toList();
    //

    setState(() {
      this.dataList = res;
    });
  }


  Widget buildBtn(indexData){
    Map data = json.decode(indexData['content']);
    return Column(
            children: <Widget>[
              for (int i = 0; i < (data['operate']?.length ?? 0); i++)
                  Center(
                  child: Material(
                  //INK可以实现装饰容器
                  child: Ink(
                  decoration: BoxDecoration(
                  color: Colors.blue,
                          ),
                  child: InkWell(
                  //圆角设置,给水波纹也设置同样的圆角
                  //如果这里不设置就会出现矩形的水波纹效果
                  // borderRadius: borderRadius,
                  //设置点击事件回调
                  onTap: () {
                    if(data['operate'][i]['runstate']==true){
                      return;
                    }
                    setState(() {
                      isAnimating = true;
                    });
                    bool runStatus = true;
                    String confirm = 'CONFIRM';
                    if(data['operate'][i]['code'].toString().indexOf('_NOT') > -1) {
                      // confirm = 'CONFIRM_NOT';
                      runStatus = false;
                    }
                    Map query = {
                      'batchNo':batchNo,
                      'stepCode':data['stepCode'],
                      'buttonCode':data['operate'][i]['code'],
                      'buttonJson': json.encode(data['operate'][i]),
                      'confirm': confirm,
                      'contingencyPlanId':indexData['id'],
                      'stepState':data['operate'][i]['stepState'],
                    };
                    API.updateStatusById(indexData['id'], runStatus).then((value){
                      // setState((){
                      //   dataList = [];
                      // });
                      // getData();
                      API.shareApi(data['operate'][i]['requestUrl'],data:query).then((value) => {
                              setState(() {
                                isAnimating = false;
                              })
                      });
                    });
                  },
                  child: Container(
                  width: 300.0,
                  height: 40.0,

                  //设置child 居中
                  alignment: Alignment(0, 0),
                  child: Text(data['operate'][i]['title'].toString(), style:  const TextStyle(fontWeight: FontWeight.w600, color: Colors.white),),

                  )))))
            ],
          );
  }


}
