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:flutter_easyrefresh/easy_refresh.dart';
import 'package:safe_control/model/name_value.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';
import './pin_text_dialog.dart';
import './HandleEemergenryLog.dart';
import 'dart:math';
import 'dart:async';

class EmergenryLog extends StatefulWidget {
  @override
  _EmergenryLogState createState() => _EmergenryLogState();
}

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

  bool isAnimating = false;

  // 当前选择的线路数据
  NameValue selectRoute;

  // 应急记录数据
  List dataList = [];

  // 当前页码
  int pageIndex = 1;

  // 每页条数
  int pageSize=10;

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

  bool _isFooter = true;

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

  // 预案信息
  Map headData = {
    'name':'',
    'startTime':'',
    'equipmentName':'',
    'position':''
  };


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

  @override
  void initState() {
    super.initState();
    initTime();
    initConfig();
    getInitInfo();
  }

  initConfig() async{
    SharedPreferences.getInstance().then((preferences){
      setState(() {
        this.theme = preferences.getString("theme")??KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  void initTime() async{
    var result = await API.getUserOperateCountAndPlanName();

    if(result == null) {

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

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

      runDate();
    }
  }

  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 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];
      });
    });
  }

  void getInitInfo() async {
    // 获取线路数据
      var result = await API.selectDisposalListPage(pageIndex,pageSize);
      if(result == null) {
      } else if (result.length == 0 || result["result"] == 'FAILURE') {
      } else {
        setState(() {
          // dataList = [];
          for (dynamic p in result['records']) {
            dataList.add(p);
          }
          pageIndex = result['current'];
          // batchNo = '7d2bf640-06cd-4dcc-9333-7f2194d10cc8';
          isAnimating = false;
          if (result['current'] < result['pages']) {
            hasNext = true;
          } else {
            hasNext = false;
          }
        });
      }
  }

  void loadData() async {
    getInitInfo();
  }


  @override
  Widget build(BuildContext context) {
    if (null == dataList || dataList.length <= 0) {
      return Scaffold(
        appBar: AppBar(
          title: new Text(
            '应急记录',
            style: new TextStyle(
              color: Colors.black,
//              fontWeight: FontWeight.bold,
            ),
          ),
          centerTitle: true,
          actions: <Widget>[

          ],
          elevation: 0.2,
          brightness: Brightness.light,
          backgroundColor: KColorConstant.topBarColor,
          leading:new Container(
            child: GestureDetector(
              onTap: () => Navigator.pop(context),
              child:Icon(Icons.keyboard_arrow_left, color: GetConfig.getColor(theme), size: 32),
            ),
          ),
        ),
      );
    } else {
      return Scaffold(
        appBar: AppBar(
          title: new Text(
            '应急记录',
            style: new TextStyle(
              color: Colors.black,
//              fontWeight: FontWeight.bold,
            ),
          ),
          centerTitle: true,
          actions: <Widget>[

          ],
          elevation: 0.2,
          brightness: Brightness.light,
          backgroundColor: KColorConstant.topBarColor,
          leading:new Container(
            child: GestureDetector(
              onTap: () => Navigator.pop(context),
              child:Icon(Icons.keyboard_arrow_left, color: GetConfig.getColor(theme), size: 32),
            ),
          ),
        ),
        body: ModalProgressHUD(
          child:_getWidget(),
          inAsyncCall: isAnimating,
          opacity: 0.7,
          progressIndicator: CircularProgressIndicator(),
        ),
        resizeToAvoidBottomPadding: false,
      );
    }
  }

  Widget _getWidget() {
    return buildInnerList();
  }

  void entryCode(context) {
    showDialog(
        context: context,
        builder: (ctx) {
          return PinTextDialog(
            theme: theme,
            callback: (value) {

            },
            cancel: () {
              // getRSCamera();
            },
          );
        });
  }


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

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

            ]),
        new Padding(
            padding: new EdgeInsets.only(top: 10.0),
            child: new Stack(children: <Widget>[
              new Column(
                children: <Widget>[
                  new Expanded(child: new Container(
                    child: GestureDetector(
                      child: Center(
                        child: EasyRefresh(
                          enableControlFinishRefresh: false,
                          enableControlFinishLoad: false,
                          controller: _controllers,
                          footer: MaterialFooter(),
                          header: MaterialHeader(),
                          child:
                          new ListView.builder(
                            //ListView的Item
                            itemCount: dataList.length,
                            itemBuilder: (BuildContext context, int index) {
                              return Container(
                                margin: EdgeInsets.only(left: 15,right: 15),
                                child: Card(
                                    elevation:0.2,
                                    child: new ListTile(
                                        isThreeLine: true,
                                        dense: false,
                                        subtitle: new Column(
                                          crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                          children: <Widget>[
                                            new Text(
                                              (index + 1).toString() +
                                                  "." +
                                                  dataList[index]['name'],
                                              style: new TextStyle(
                                                  fontSize: 18.0,
                                                  fontWeight:
                                                  FontWeight.w600),
                                            ),
                                            Padding(
                                              padding:
                                              EdgeInsets.only(top: 5),
                                            ),
                                            Text(
                                              "启动时间:" +
                                                  dataList[index]['startTime'],
                                              style: new TextStyle(
                                                  fontSize: 14.0,
                                                  color: Colors.grey),
                                            ),
                                            Padding(
                                              padding:
                                              EdgeInsets.only(top: 5),
                                            ),
                                            Text(
                                              "结束时间:" + ( null == dataList[index]['endTime'] ? '' : dataList[index]['endTime'])
                                                  ,
                                              style: new TextStyle(
                                                  fontSize: 14.0,
                                                  color: Colors.grey),
                                            ),
                                            Padding(
                                              padding:
                                              EdgeInsets.only(top: 5),
                                            ),
                                            Text(
                                              "持续时间:" + ( null == dataList[index]['duration'] ? (h+'时'+m+'分'+s+'秒' ): dataList[index]['duration']),
                                              style: new TextStyle(
                                                  fontSize: 14.0,
                                                  color: Colors.grey),
                                            ),
                                          ],
                                        ),
                                        trailing: new Padding(
                                          child: dataList[index]['endTime'] == null ? new Text('进行中',
                                              style: new TextStyle(
                                                  fontSize: 14.0,
                                                  color: Colors.blue) ) : new Text('已完成', style: new TextStyle(
                                              fontSize: 14.0,
                                              color: Colors.green)),
                                          padding: EdgeInsets.only(top: 5),
                                        ),
                                        onTap: () {
                                          Navigator.push(context,
                                              new MaterialPageRoute(
                                                  builder: (context) {
                                                    return new HandleEemergenryLog('1',batchNo: dataList[index]['id'],);
                                                  })).then((value) {
                                            setState(() {
                                              pageIndex = 1;
                                              dataList = [];
                                            });
                                            loadData();});
                                        })),
                              );
                            },
                          ),
                          onRefresh: () async {
                            await new Future.delayed(
                                const Duration(seconds: 1), () {
                              setState(() {
                                pageIndex = 1;
                                dataList = [];
                              });
                              _controllers.resetLoadState();
                              loadData();
                            });
                          },
                          onLoad: hasNext == true ? () async {
                            await new Future.delayed(
                                const Duration(seconds: 1), () {
                              setState(() {
                                pageIndex = pageIndex + 1;
                              });
                              if (hasNext) {
                                _controllers.resetLoadState();
                                loadData();
                              }
                            });
                          } : null,
                        ),
                      ),
                    ),
                  ))
                ],
              ),
            ])),
      ],
    );
  }


}
