import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:amos_iot_login_tpl/mine/offline/color.dart';
import 'package:path_provider/path_provider.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter/services.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:base/utils/http.dart';
import 'package:flutter/src/widgets/navigator.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:webview_flutter/platform_interface.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';
import 'package:base/view/ImageViewPage.dart';
import 'dialogUp.dart';
import 'handItem.dart';
import 'DottedLine.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import './pin_text_dialog.dart';
import 'dart:math';

class HandleEemergenry extends StatefulWidget {
  final String expand;
  final String batchNo;
  const HandleEemergenry( this.expand , {this.batchNo});

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

class _HandleEemergenryState extends State<HandleEemergenry> {
  final List<Tab> myTabs = <Tab>[
    const Tab(child: Text('处置动态',style: TextStyle(color: Colors.black))),
    const Tab(child: Text('处置事项',style: TextStyle(color: Colors.black))),
  ];

  bool isAnimating = false;
  WebViewController webViewController;
  String h5Url = 'packages/jcs_airport/assets/html/index.html';
  String jsPath = 'packages/jcs_airport/assets/html/js/vue.min.js';
  String methodPath = 'packages/jcs_airport/assets/html/method.js';
  String mqttPath = 'packages/jcs_airport/assets/html/mqtt.min.js';
  ProgressDialog pr;
  bool _isPanelOpen = true;
  dynamic data;

  List dataList = [];

  // 当前页码
  int pageIndex = 1;

  // 每页条数
  int pageSize=100;

  /// 滑动控制器
  ScrollController scrollController = ScrollController();

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

  EasyRefreshController _controllers = EasyRefreshController();

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

  String roleCode = "";

  String dataType='1';

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

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

    client = MqttServerClient(server,'mqttjsc_${getRandomString()}');
    client.useWebSocket = true;
    client.port = int.parse(port);
    client.onConnected = onConnected; //连接成功回调
    client.onDisconnected = onDisConnected; //连接断开回调
    client.onSubscribed = onSubscribed; //订阅成功回调
    client.connect();
    getData();
    getDataMessage();
    //监听消息
    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"] == 'replayMessage' ) {
        getDataMessage();
      } else if(msg["msgType"] == 'refreshTaskRecord' ){
        getDataMessage();
      } else if(msg["msgContext"] != null && msg["msgContext"]['content'] == 'stopPlan'){
        getDataMessage();
      } else if(msg["msgType"] == 'getStepList'){
        getMessageTaskData(msg["planTask"]);
      }
    });
  }

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

  //页面销毁时关闭连接
  @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;
      });
    }
  }

  getDataMessage() async {
    final prefs = await SharedPreferences.getInstance();
    API.getPlaneRecordByNew(widget.batchNo).then((value) {
      data = [];
      for (dynamic p in value["records"]) {
        if(p["personImg"] != null) {
          p["personImg"] = prefs.getString("imageUrl") + p["personImg"];
        }
        if(p["filePath"] != null) {
          p["filePath"] = prefs.getString("imageUrl") + p["filePath"];
        }
        if(p["playImg"] != null) {
          p["playImg"] = prefs.getString("imageUrl") + p["playImg"];
        }
        data.add(p);
      }
      // batchNo = result['batchNo'];
      initVueInstence();
    });
  }

  getData() async {
    var result = await API.getUserOperateCountAndPlanName();
    if(result == null) {
    } else if (result.length == 0 || result["result"] == 'FAILURE') {
    } else {
      var result1 = await API.selectTaskActionPage(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'];
          if (result1['current'] < result1['pages']) {
            hasNext = true;
          } else {
            hasNext = false;
          }
        });
      }
    }
  }

  // @override
  // void didChangeDependencies() {
  //   super.didChangeDependencies();
  //   initVueInstence();
  // }
  // @override
  // void didUpdateWidget(covariant HandleEemergenry oldWidget) {
  //   super.didUpdateWidget(oldWidget);
  //   initVueInstence();
  // }

  Future<void> initVueInstence()async{

    if(webViewController==null){return;}
    await _loadHtmlFromAssets();
    await _loadJsFromAssets();
  }
  /// 加载js资源
  Future<void> _loadJsFromAssets() async {
    String jsContents = await rootBundle.loadString(jsPath);
    String jsContents1 = await rootBundle.loadString(methodPath);
    String jsContents2 = await rootBundle.loadString(mqttPath);
    //加载Vue
    webViewController.evaluateJavascript(jsContents2);
    webViewController.evaluateJavascript(jsContents);
    webViewController.evaluateJavascript(jsContents1);

    String jsonResult = json.encode(data);

    // //传递参数，初始化Vue
    webViewController.evaluateJavascript('init($jsonResult)');
  }

  /// 加载HTML资源
  Future<void> _loadHtmlFromAssets() async {
    String fileHtmlContents = await rootBundle.loadString(h5Url);
    String result=Uri.dataFromString(fileHtmlContents, mimeType: 'text/html', encoding: Encoding.getByName('utf-8')).toString();
    webViewController.loadUrl(result);
  }

  /// JS和Flutter通信的Channel
  JavascriptChannel _alertJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'communicationUrl',
        onMessageReceived: (JavascriptMessage message) {
          print(message.message);
          print('聊天室窗口=======>');
          dynamic jsons = json.decode(message.message);
          print(jsons["msgType"]);
          if(jsons["type"] == 'img') {
            List<String> imgList = [];
            imgList.add(jsons["imgUrl"]);
            Navigator.push(context, MaterialPageRoute(builder: (context) {
              return PhotoViewPage(imgList);
            }));
          } else if (jsons["type"] == 'video') {
              String videoUrl = jsons["videoUrl"];
              getDownload(videoUrl);
          } else {
            // if( jsons["msgType"] == 'initOperate'  || jsons["msgType"] == 'replayMessage' || jsons["msgType"] == "operateConfirmMessage" ) {
            //   getData();
            // } else if(jsons["msgType"] == 'stopOperate'){
            //   getData();
            // } else if(jsons["msgType"] == 'refreshRecord'){
            //   getData();
            // }else if(jsons["msgType"] == 'message' && jsons["msgContext"] != null && jsons["msgContext"]['type'] == 'event'){
            //   getData();
            // } else if(jsons["msgContext"] != null && jsons["msgContext"]['content'] == 'stopPlan'){
            //   getData();
            // }
          }
        });
  }



  //存储路径
  Future<String> get _apkLocalPath async {
    final directory = await getExternalStorageDirectories(type: StorageDirectory.downloads);
    return directory[0].path;
  }

  void getDownload(String url) async {
    //存放路径
    final path = await _apkLocalPath;
    File file = File(path + '/' + new DateTime.now().millisecondsSinceEpoch.toString() + '.mp4');
    if (await file.exists()) await file.delete();

    HttpManager().download(
        url: url,
        savePath: file.path,
        onReceiveProgress: (int count, int total) {
          // pr.update(progress: num.parse(NumberUtil.formatNum(count / total * 100)), message: '文件下载中，请稍后…');
        },
        successCallback: (data) => {
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return VideoViewPage(file);
          }))
        },
        errorCallback: (data) => { });
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
          length: myTabs.length,
      child: Scaffold(
        appBar: AppBar(
                title:  const Text(
                '任务详情',
                style:  TextStyle(
                  color: Colors.black,
          //              fontWeight: FontWeight.bold,
                ),
              ),
              centerTitle: true,
              elevation: 0.2,
              brightness: Brightness.light,
              backgroundColor: KColorConstant.topBarColor,
              leading: Container(
                child: GestureDetector(
                  onTap: () => Navigator.pop(context),
                  child:const Icon(Icons.keyboard_arrow_left, color: Colors.black, size: 32),
                ),
              ),
              bottom: TabBar(tabs: myTabs,)),
        body: Stack(
                    children: <Widget>[
                      /// ... ... 页面中其他的视图
                      TabBarView(physics: const NeverScrollableScrollPhysics(),children: <Widget>[ buildWid(), HandItem(widget.batchNo)],),
                      // MapPageBody(),
                      ///抽屉视图
                      buildDrawerWidget(),
                    ],
                  ),
        ),
    );
  }


  ///构建底部对齐的抽屉效果视图
  Widget buildDrawerWidget() {
    ///层叠布局中的底部对齐
    return Align(
      alignment: Alignment.topCenter,
      child: Column(children: [AmosDrawer(
        maxHeight: 240,
        minHeight: 0.0,
        enabledParallax: true,
        isDraggable: false,
        padding: EdgeInsets.all(0.0),
        margin: EdgeInsets.all(0.0),
        direction: SlidingDirection.DOWN,
        panelSnapping: false,
        controller: _drawerController,

        enabledMask: false,
        hidePanel: false,
        parallaxOffset: 0.5,
        defaultDrawerState: widget.expand == 'false' ? AmosDrawerState.CLOSED : AmosDrawerState.OPEN  ,
        showCrossBar: false,

        panelBuilder: (sc) => _panel(sc),
      ),buildCrossBar()],),
    );
  }

  /// 标题横线
  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: Icon(
              //src: 'assets/icon/icon_close.svg',
              Icons.unfold_more,
              //imageSize: 12.px,
            ),
            // child: Container(
            //   margin: EdgeInsets.all(0),
            //   height: 8,
            //   width: 30,
            //   decoration: BoxDecoration(
            //       color: color,
            //       borderRadius: BorderRadius.all(Radius.circular(6)),
            //       border: Border.all(color: color, width: 1.0)),
            // ),
          )
        ],
      );
  }

  Widget _panel(ScrollController sc) {
    return MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: ModalProgressHUD(
          child: buildInnerList(),
          inAsyncCall: isAnimating,
          opacity: 0.7,
          progressIndicator: const CircularProgressIndicator(),
        )

    );
  }

  /// 可滑动布局构建 这里是一个列表ListView
  ListView buildListView(ScrollController sc) {
    return ListView.builder(
      /// 设置 physics 的值为 ClampingScrollPhysics，使其能监听 ScrollEndNotification
      /// 详见 `package:flutter/lib/src/widgets/scroll_configuration.dart`
      physics: const ClampingScrollPhysics(),
      controller: sc,
      itemCount: 20,
      itemBuilder: (BuildContext context, int index) {
        return InkWell(
            onTap: () {
              print('点击事件 $index');
              /// 关闭抽屉
              // _drawerController.close();
            },
            child: ListTile(title: Text('想去的地方 $index')));
      },
    );
  }

  Widget buildInnerList() {
    return  Stack(
      children: <Widget>[
        // CustomScrollView(
        //     controller: scrollController,
        //     slivers: <Widget>[
        //       SliverList(
        //           delegate:  SliverChildBuilderDelegate(
        //                   (BuildContext context, int index) {
        //               }, childCount: 0)),
        //
        //     ]),
        Padding(
            padding:  const EdgeInsets.only(top: 10.0),
            child:  Stack(children: <Widget>[
              Column(
                children: <Widget>[
                  Expanded(child:  Container(
                    child: GestureDetector(
                      child: Center(
                        child: EasyRefresh(
                          enableControlFinishRefresh: false,
                          enableControlFinishLoad: true,
                          controller: _controllers,
                          footer: MaterialFooter(),
                          child:
                          ListView.builder(
                            //ListView的Item
                            itemCount: dataList.length,
                            itemBuilder: (BuildContext context, int index) {
                              return Container(
                                margin: const EdgeInsets.only(left: 0,right: 0),
                                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),
                                            ),
                                            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]),
                                              ],
                                            )
                                          ],
                                        ),

                                        onTap: () {
                                          // Navigator.push(context,
                                          //     MaterialPageRoute(
                                          //         builder: (context) {
                                          //           return  HandleEemergenry(
                                          //               dataList[index]['id'],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();
                                getData();
                              }
                            });
                          } : null,
                        ),
                      ),
                    ),
                  ))
                ],
              ),
            ])),
      ],
    );
  }

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

  Widget buildBtn(indexData){
    Map data = json.decode(indexData['content']);
    return Row(
      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),),

                          )))))
      ],
    );
  }

  Widget buildWid() {
    return Column(
      children: [
        Expanded(child: WebView(
          initialUrl: '',
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController wvc) {
            webViewController = wvc;
            _loadHtmlFromAssets();
          },
          onPageStarted: (String url) {
            print(url);
          },
          onPageFinished: (String url) {
            print(url);
            _loadJsFromAssets();
          },
          onWebResourceError: (WebResourceError error) {
            print(error);
          },
          // JS和Flutter通信的Channel
          javascriptChannels: Set.from([
            _alertJavascriptChannel(context)
           ]) ,
        )),
        Row(
          children: [
            Expanded(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                  child: DialogUp(widget.batchNo,"false",""),
                )),
          ],
        )
      ],
    );
  }

}