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:base/utils/http.dart';
import 'package:flutter/src/widgets/navigator.dart';
import 'package:webview_flutter/platform_interface.dart';
import 'handItemLog.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';
import 'package:base/view/ImageViewPage.dart';
import 'dart:math';

class HandleEemergenryLog extends StatefulWidget {
  final String pointId;
  final String batchNo;
  const HandleEemergenryLog( this.pointId , {this.batchNo});



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

class _HandleEemergenryStateLog extends State<HandleEemergenryLog> {
  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;
  dynamic data;

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

  String roleCode = "";

  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,'mqttjsca_${getRandomString()}');
    client.useWebSocket = true;
    client.port = int.parse(port);

    client.onConnected = onConnected; //连接成功回调
    client.onDisconnected = onDisConnected; //连接断开回调
    client.onSubscribed = onSubscribed; //订阅成功回调
    client.connect();
    getDataMessage();
    //监听消息
    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"] == 'replayMessage' ) {
        getDataMessage();
      } else if(msg["msgType"] == 'refreshTaskRecord' ){
        getDataMessage();
      } else if(msg["msgContext"] != null && msg["msgContext"]['content'] == 'stopPlan'){
        getDataMessage();
      }
    });
  }

  String getRandomString(){
    String str = '';
    for(int i=0 ;i<=5;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成功');
  }


  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'];
      isAnimating = false;
      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);
    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);
          dynamic jsons = json.decode(message.message);
          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"] == 'message' || jsons["msgType"] == 'replayMessage' || jsons["msgType"] == "operateConfirmMessage") {
            //   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: TabBarView(physics: const NeverScrollableScrollPhysics(),children: <Widget>[ buildWid(), HandItemLog(widget.batchNo)],),
      ),
    );
  }


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

}