import 'package:amos_iot_login_tpl/mine/offline/GetConfig.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/name_value.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'dart:convert';
import 'dart:async';

import 'package:jcs_airport/services/api.dart';
import './DottedLine.dart';
import './pin_text_dialog.dart';
import 'HandleEemergenry.dart';


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

class _HandItemStateLog extends State<HandItemLog>
    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;

  // 每页条数
  int pageSize=100;

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

  final bool _isFooter = true;

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

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


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

  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) {
    showDialog(
        context: context,
        builder: (ctx) {
          return PinTextDialog(
            theme: theme,
            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(),
                          bottomBouncing: true,
                          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.length - index ).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(
                                              '执行时间:' + ( null == dataList[index]['updateDate']  ? '' : dataList[index]['updateDate'] ),
                                              style: const TextStyle(
                                                  fontSize: 14.0,
                                                  color: Colors.grey),
                                            ),
                                            const Padding(
                                              padding:
                                              EdgeInsets.only(top: 5),
                                            ),
                                            Text(
                                              '执行人:' +
                                                  (dataList[index]['startUserName'] == null ? '' : dataList[index]['startUserName']) ,
                                              style: const TextStyle(
                                                  fontSize: 14.0,
                                                  color: Colors.grey),
                                            ),
                                            const Padding(
                                              padding:
                                              EdgeInsets.only(top: 5),
                                            ),
                                          ],
                                        ),
                                        // 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 new Future.delayed(
                            //     const Duration(seconds: 1), () {
                            //   setState(() {
                            //     pageIndex = 1;
                            //     dataList = [];
                            //   });
                            //   _controllers.resetLoadState();
                            //   initData(0);
                            // });
                          },
                          onLoad: hasNext == true ? () async {
                            await new Future.delayed(
                                const Duration(seconds: 1), () {
                              setState(() {
                                pageIndex = pageIndex + 1;
                              });
                              if (hasNext) {
                                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(
              minWidth:20,
              padding: const EdgeInsets.all(10),
              child: Text(data['operate'][i]['title'].toString(), style:  const TextStyle(fontWeight: FontWeight.w600, color: Colors.indigo ),),
              onPressed: () {
                // if(indexData['runstate']==true){
                //   return;
                // }
                // Map query = {
                //   'batchNo':widget.batchNo,
                //   'stepCode':data['stepCode'],
                //   'buttonCode':data['operate'][i]['code'],
                //   'confirm':'CONFIRM',
                //   'contingencyPlanId':indexData['id'],
                //   'stepState':data['operate'][i]['stepState'],
                // };
                // print(query);
                // API.shareApi(data['operate'][i]['requestUrl'],data:query).then((value) => {
                //   API.updateStatusById(indexData['id']).then((value){
                //     setState((){
                //       dataList = [];
                //     });
                //     initData();
                //   })
                // });
              })
      ],
    );
  }

}
