import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter/platform_interface.dart';
import 'package:flutter/src/widgets/navigator.dart';
import 'package:base/view/ImageViewPage.dart';

///@Description     富文本指令流
///@author          helinlin
///@create          2022-06-01 14:37
class CommandStream extends StatefulWidget {
  List commandFlows;
  
  CommandStream({Key key, this.commandFlows}) : super(key: key);

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

class _CommandStreamState extends State<CommandStream> {
  WebViewController webViewController;
  String path = 'assets/html/command_stream.html';
  String jsPath = 'assets/html/js/vue.min.js';
  
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    initVueInstence();
  }
  @override
  void didUpdateWidget(covariant CommandStream oldWidget) {
    super.didUpdateWidget(oldWidget);
    initVueInstence();
  }
  @override
  Widget build(BuildContext context) {
    return 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: <JavascriptChannel>{
        _alertJavascriptChannel(context),
      },
    );
  }
  Future<void> initVueInstence()async{
    if(webViewController==null){return;}
    await _loadHtmlFromAssets();
    await _loadJsFromAssets();
  }
  /// 加载js资源
  Future<void> _loadJsFromAssets() async {
    String jsContents = await rootBundle.loadString(jsPath);
    //加载Vue
    webViewController.evaluateJavascript(jsContents);
     String jsonResult = json.encode(widget.commandFlows);
    //传递参数，初始化Vue
    webViewController.evaluateJavascript('init($jsonResult)');  
  }

  /// 加载HTML资源
  Future<void> _loadHtmlFromAssets() async {
    String fileHtmlContents = await rootBundle.loadString(path);
    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: 'GetImgUrl',
        onMessageReceived: (JavascriptMessage message) {
          print(message.message);

          List<String> imgList = [];
          imgList.add(message.message);
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return PhotoViewPage(imgList);
          }));
        });
  }
}
