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:safe_control/model/CheckPoint.dart';
import 'package:safe_control/model/name_value.dart';
import 'package:safe_control/services/check_point_service.dart';
import 'package:safe_control/services/route_list_services.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';
import 'package:jcs_airport/services/api.dart';
import './DottedLine.dart';
import './pin_text_dialog.dart';
import 'HandleEemergenry.dart';
import 'dart:math';
import 'dart:async';
import 'package:intl/intl.dart';

class HandItem extends StatefulWidget {
  final String batchNo;
  const HandItem(this.batchNo);
  @override
  _HandItemState createState() => _HandItemState();
}

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

  bool isAnimating = false;

  // 线路数据
  List<Map<String, dynamic>> routeList = [];

  // 预案信息
  Map headData = {
    'name':'',
    'startTime':'',
    'equipmentName':'',
    'position':''
  };
  // 当前选择的线路数据
  NameValue selectRoute;

  // 列表数据
  List dataList = [];

  // 当前页码
  int pageIndex = 1;

  String server ='';
  String port ='';

  int second = 0;
  String h = '0';
  String m = '0';
  String s = '0';

  // 每页条数
  int pageSize=100;

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

  final bool _isFooter = true;

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

  String theme='';
  final EasyRefreshController _controllers = EasyRefreshController();

  MqttServerClient client;


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

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

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

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

    setState(() {
      server = prefs.getString("server");
      port = prefs.getString("port");
    });

    client = MqttServerClient.withPort(server, 'mqttjs_${getRandomString()}', int.tryParse(port));

    client.onConnected = onConnected; //连接成功回调
    client.onSubscribed = onSubscribed; //订阅成功回调
    client.connect();
    initTime();
    initData();
    //监听消息
    client.updates.listen((List<MqttReceivedMessage<MqttMessage>> c) {
      final MqttPublishMessage message = c[0].payload;
      final payload = MqttPublishPayload.bytesToStringAsString(message.payload.message);
      print('消息:$payload,主题: <${c[0].topic}>');
      print('处置流程=======>');
      dynamic msg = json.decode(payload);
      print(msg["msgType"]);
      if(msg["msgType"] == 'initOperate' || msg["msgType"] == "operateConfirmMessage") {
        initData();
      } else if(msg["msgType"] == 'stopOperate'){
        initData();
      } else if(msg["msgContext"] != null && msg["msgContext"]['content'] == 'stopPlan'){
        initData();
      }
    });
  }

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


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

  List secondToDate (result) {
    // List res = [];
    const ten = 9;
    const timeCovert = 60;
    String h = result ~/ (timeCovert * timeCovert) > ten ? (result ~/ (timeCovert * timeCovert)).toString()
        : '0' + (result ~/ (timeCovert * timeCovert)).toString();
    String m = (result ~/ timeCovert) % timeCovert > ten ? ((result ~/ timeCovert) % timeCovert).toString()
        : '0' + ((result ~/ timeCovert) % timeCovert).toString();
    String s = result % timeCovert > ten ? (result % timeCovert).toString()
        : '0' + (result % timeCovert).toString();
    // res.add(h);
    // res.add(m);
    // res.add(s);
    return [h, m, s];
  }

  void initTime() async{
    Map result = await API.selectDisposalDetails(widget.batchNo);
    print(result);
    Duration difference = DateTime.now().difference(DateTime.parse(result["startTime"]));
    List secondToDate2 = secondToDate(difference.inSeconds);
    setState(() {
      second = difference.inSeconds;
      headData = result;
      h = secondToDate2[0];
      m = secondToDate2[1];
      s = secondToDate2[2];
    });

    runDate();
  }

  void initData() async{

   var result1 = await API.selectTaskActionPage(widget.batchNo,dataType,pageIndex,pageSize);
   setState(() {
    // dataList = [];
     for (dynamic p in result1['records']) {
       dataList.add(p);
     }
     pageIndex = result1['current'];
     isAnimating = false;
     if(result1['current'] < result1['pages']){
       hasNext =true;
     } else {
       hasNext = false;
     }
   });
  }

  void runDate() {
    Timer.periodic(Duration(milliseconds: 1000), (Timer t) {
      if (!mounted) {
        return;
      }
      this.setState(() { second= second + 1; });
      List secondToDate2 = secondToDate(second);
      setState(() {
        h = secondToDate2[0];
        m = secondToDate2[1];
        s = secondToDate2[2];
      });
    });
  }

  @override
  Widget build(BuildContext context) {
      return Scaffold(
        body: ModalProgressHUD(
          child:_getWidget(),
          inAsyncCall: isAnimating,
          opacity: 0.7,
          progressIndicator: const CircularProgressIndicator(),
        ),
        resizeToAvoidBottomPadding: false,
      );
  }



  Widget _getWidget() {
    return buildInnerList();
  }

  void entryCode(context,batchNo,category) {
    showDialog(
        context: context,
        builder: (ctx) {
          return PinTextDialog(
            theme: 'blue',
            batchNo:batchNo,
            category: category,
            callback: (value) {
            },
            cancel: () {
              // getRSCamera();
            },
          );
        });
  }


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

  Widget buildInnerList() {
    return  Stack(
      children: <Widget>[
         CustomScrollView(
            controller: scrollController,
            slivers: <Widget>[
               SliverList(
                  delegate:  SliverChildBuilderDelegate(
                          (BuildContext context, int index) {
                      }, childCount: routeList.length)),

            ]),
         Padding(
            padding:  EdgeInsets.only(top: 10.0),
            child:  Stack(children: <Widget>[
               Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  const Padding(
                          padding:  EdgeInsets.only(left: 20.0),
                           child:  Text('预案信息',style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600), textAlign: TextAlign.left,),
                          ),
                  Card(
                   elevation:0.2,
                   child: ListTile(
                       isThreeLine: true,
                       dense: false,
                       subtitle:  Column(
                         crossAxisAlignment:
                         CrossAxisAlignment.start,
                         children: <Widget>[
                             Text(
                               headData['name'],
                             style: const TextStyle(
                                 fontSize: 18.0,
                                 fontWeight:
                                 FontWeight.w600),
                           ),
                           const Padding(
                             padding:
                             EdgeInsets.only(top: 5),
                           ),
                            Text(
                             '启动时间: ' + headData['startTime']
                             ,
                             style: const TextStyle(
                                 fontSize: 14.0,
                                 color: Colors.grey),
                           ),
                           const Padding(
                             padding:
                             EdgeInsets.only(top: 5),
                           ),
                           Text(
                             "持续时间:" + ( null == headData['duration'] ? (h+'时'+m+'分'+s+'秒' ): headData['duration']),
                             style:  TextStyle(
                                 fontSize: 14.0,
                                 color: Colors.grey),
                           ),
                            Text(
                             '触发设备: ' + headData['equipmentName']
                             ,
                             style: const TextStyle(
                                 fontSize: 14.0,
                                 color: Colors.grey),
                           ),
                           Text(
                             '着火部位: ' + headData['position'].toString(),
                             style:  const TextStyle(
                                 fontSize: 14.0,
                                 color: Colors.grey),
                           ),
                           Text(
                             "结束时间:" + ( null == headData['endTime'] ? '' : headData['endTime'])
                             ,
                             style: new TextStyle(
                                 fontSize: 14.0,
                                 color: Colors.grey),
                           ),
                           const Padding(
                             padding:
                             EdgeInsets.only(top: 5),
                           ),
                           const DottedLine(
                             height: 1,
                           ),
                         ],
                       ),
                       onTap: () {
                         Navigator.push(context,
                             MaterialPageRoute(
                                 builder: (context) {
                                   return HandleEemergenry(
                                       '1');
                                 })).then((value) {
                           setState(() {
                             pageIndex = 1;
                             dataList = [];
                           });
                           initData();});
                       })
                 ),
                  const Padding(
                    padding:  EdgeInsets.only(left: 20.0),
                    child:  Text('处置任务',style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600), textAlign: TextAlign.left,),
                  ),
                  Expanded(child:  Container(
                    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(
                                                 // (index + 1).toString() +
                                                 //     '.' +
                                                     dataList[index]['category'],
                                               style: const TextStyle(
                                                   fontSize: 18.0,
                                                   fontWeight:
                                                   FontWeight.w600
                                               ),
                                             ),
                                            Align(
                                                   alignment: Alignment.bottomRight,
                                                   child: Text(
                                                     dataList[index]['runstate']==true?'已完成':'未执行',
                                                     style: TextStyle(
                                                         fontSize: 11.0,
                                                         fontWeight:
                                                         FontWeight.w500,
                                                         color: dataList[index]['runstate']==true ? Colors.green : Colors.red
                                                     ),
                                                   ),
                                                 ),
                                            const Padding(
                                              padding:
                                              EdgeInsets.only(top: 5),
                                            ),
                                            Text(
                                              '推送时间:' +
                                                  dataList[index]['createDate'],
                                              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.spaceAround,
                                              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']);
                                                      }
                                                  ),
                                                ),
                                              ],
                                            )
                                          ],
                                        ),
                                        // trailing: Padding(
                                        //   child: Icon(
                                        //     Icons.keyboard_arrow_right,color: GetConfig.getColor(theme),),
                                        //   padding: const EdgeInsets.only(top: 15),
                                        // ),
                                        onTap: () {
                                          // Navigator.push(context,
                                          //      MaterialPageRoute(
                                          //         builder: (context) {
                                          //           return  HandleEemergenry(
                                          //               dataList[index]['id']);
                                          //         })).then((value) {
                                          //   setState(() {
                                          //     pageIndex = 1;
                                          //     dataList = [];
                                          //   });
                                          //   initData();});
                                        })),
                              );
                            },
                          ),
                          onRefresh: () async {
                            // await  Future.delayed(
                            //     const Duration(seconds: 1), () {
                            //   setState(() {
                            //     pageIndex = 1;
                            //     dataList = [];
                            //   });
                            //   _controllers.resetLoadState();
                            //   initData();
                            // });
                          },
                          onLoad:  hasNext == true ? () async {
                            await  Future.delayed(
                                const Duration(seconds: 1), () {
                              if (hasNext) {
                                setState(() {
                                  pageIndex = pageIndex + 1;
                                });
                                initData();
                              }
                            });
                          } : null,
                        ),
                      ),
                    ),
                  ))
                ],
              ),
            ])),
      ],
    );
  }

  Widget buildBtn(indexData){
    Map data = json.decode(indexData['content']);
    return Row(
      children: <Widget>[
        for (int i = 0; i < (data['operate']?.length ?? 0); i++)
          FlatButton(
              color: Colors.indigo,
              minWidth:280,
              padding: const EdgeInsets.all(10),
              child: Text(data['operate'][i]['title'].toString(), style:  const TextStyle(fontWeight: FontWeight.w600, color: Colors.white, backgroundColor:  Colors.indigo ),),
              onPressed: () {
                if(indexData['runstate']==true){
                  return;
                }
                bool runStatus = true;
                String confirm = 'CONFIRM';
                if(data['operate'][i]['code'].toString().indexOf('_NOT') > -1) {
                  // confirm = 'CONFIRM_NOT';
                  runStatus = false;
                }
                Map query = {
                  'batchNo':widget.batchNo,
                  'stepCode':data['stepCode'],
                  'buttonCode':data['operate'][i]['code'],
                  'confirm':confirm,
                  'buttonJson': json.encode(data['operate'][i]),
                  'contingencyPlanId':indexData['id'],
                  'stepState':data['operate'][i]['stepState'],
                };
                print(query);
                API.updateStatusById(indexData['id'], runStatus).then((value){
                  // setState((){
                  //   dataList = [];
                  // });
                  // getData();
                  API.shareApi(data['operate'][i]['requestUrl'],data:query).then((value) => {
                      initData()
                  });
                });
              })
      ],
    );
  }
}
