import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';

import '../../../../common/routers/index.dart';
import '../../../../common/style/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/values/index.dart';
import 'index.dart';

class BbsSubjectPage extends GetView<BbsSubjectController> {
  const BbsSubjectPage({Key? key}) : super(key: key);

  static Future<void> open(String subjectId, {String title = ''}) async {
    await Get.toNamed(O2OARoutes.bbsSubject,
        arguments: {"subjectId": subjectId, "title": title});
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<BbsSubjectController>(
      builder: (_) {
        return Scaffold(
          appBar: AppBar(
            leading: IconButton(
              icon: const Icon(Icons.arrow_back),
              onPressed: () => {controller.tapBackBtn()},
            ),
            title: Obx(() => Text(controller.state.title)),
            actions: [
              Obx(()=>Visibility(
                  visible: controller.state.canWriteComment,
                  child: TextButton(
                      onPressed: controller.writecomments,
                      child: Text('bbs_subject_write_comments'.tr,
                          style: AppTheme.whitePrimaryTextStyle)))),
              Obx(()=>Visibility(
                  visible: controller.state.canDelete,
                  child: TextButton(
                      onPressed: controller.deleteSubject,
                      child: Text('delete'.tr,
                          style: AppTheme.whitePrimaryTextStyle))))
            ],
          ),
          body: SafeArea(
            child: Obx(() => controller.state.url.isEmpty
                ? const Center(child: CircularProgressIndicator())
                : _buildView()),
          ),
        );
      },
    );
  }

  // 主视图
  Widget _buildView() {
    return InAppWebView(
        key: controller.webViewKey,
        initialUrlRequest: URLRequest(url: Uri.parse(controller.state.url)),
        initialOptions: InAppWebViewGroupOptions(
            crossPlatform: InAppWebViewOptions(
              useShouldOverrideUrlLoading: true,
              useOnDownloadStart: true,
              javaScriptCanOpenWindowsAutomatically: true,
              mediaPlaybackRequiresUserGesture: false,
              applicationNameForUserAgent: O2.webviewUserAgent
            ),
            android: AndroidInAppWebViewOptions(
              useHybridComposition: true,
              supportMultipleWindows: true,
            ),
            ios: IOSInAppWebViewOptions(
              allowsInlineMediaPlayback: true,
            )),
        onWebViewCreated: (c) {
          controller.setupWebviewJsHandler(c);
        },
        shouldOverrideUrlLoading: (c, navigationAction) async {
          var uri = navigationAction.request.url!;
          OLogger.d("shouldOverrideUrlLoading uri: $uri");
          return NavigationActionPolicy.ALLOW;
        },
        onProgressChanged: (c, p) {
          OLogger.d("o2Webview portal progress: $p");
          if (p == 100 && !controller.isInstallJsName) {
            controller.isInstallJsName = true;
            var js = '''
                    if (window.flutter_inappwebview && window.flutter_inappwebview.callHandler) {
                      window.o2android = {};
                      window.o2android.postMessage = function(message){
                        window.flutter_inappwebview.callHandler('o2android', message);
                      }; 
                    }
                  ''';
            c.evaluateJavascript(source: js);
            OLogger.d("执行o2android转化js完成。。。");
          }
        },
        // h5下载文件
        onDownloadStartRequest: (c, request) async {
          controller.webviewHelper.onFileDownloadStart(request);
        },
        onTitleChanged: ((c, title) {
          OLogger.d('修改网页标题： $title');
        }),
        onConsoleMessage: (c, consoleMessage) {
          OLogger.i("console: $consoleMessage");
        });
  }

  // void showComment(BuildContext context) {
  //   showModalBottomSheet(
  //       context: context,
  //       elevation: 0,
  //       backgroundColor: Colors.transparent,
  //       barrierColor: Colors.black.withOpacity(0.25),
  //       isScrollControlled: true,
  //       constraints: BoxConstraints(
  //         maxHeight: MediaQuery.of(context).size.height -
  //             MediaQuery.of(context).viewPadding.top,
  //       ),
  //       builder: (context) {
  //         return AnimatedPadding(
  //         padding: EdgeInsets.only(
  //           // 下面是键盘弹出底部添加bottom
  //           bottom: MediaQuery.of(context).viewInsets.bottom,
  //         ),
  //         duration: Duration.zero,
  //         child:  Container(
  //               height: 250.w,
  //               padding: const EdgeInsets.all(20),
  //             decoration: const BoxDecoration(
  //               borderRadius: BorderRadius.only(topLeft: Radius.circular(16), topRight: Radius.circular(16)),
  //               color: Colors.white,
  //             ),
  //                 child: Column(
  //           children: [
  //             SizedBox(height: 10),
  //             Row(
  //               mainAxisAlignment: MainAxisAlignment.center,
  //               children: [
  //                 const SizedBox(width: 8),
  //                 Expanded(
  //                   flex: 1,
  //                   child: Padding(
  //                     padding: EdgeInsets.only(left: 5.w, right: 5.w),
  //                     child: TextField(
  //                       autofocus: false,
  //                       decoration: InputDecoration(
  //                         isDense: true,
  //                         hintText: '请输入回复',
  //                         hintStyle: Theme.of(context).textTheme.bodySmall,
  //                         filled: true,
  //                         fillColor: Theme.of(context).colorScheme.background,
  //                       ),
  //                       style: Theme.of(context).textTheme.bodyLarge,
  //                       textInputAction: TextInputAction.done,
  //                     ),
  //                   ),
  //                 ),
  //                 TextButton(
  //                     onPressed: () {},
  //                     child: Padding(
  //                         padding: EdgeInsets.only(
  //                             left: 10.w, right: 10.w, top: 5.w, bottom: 5.w),
  //                         child: Text('发送'))),
  //                 const SizedBox(width: 8),
  //               ],
  //             ),
  //             Padding(
  //                 padding: EdgeInsets.all(10),
  //                 child: IconButton(
  //                     onPressed: controller.clickCommentsImageBtn,
  //                     icon: Icon(Icons.image, size: 36.w))),
  //             const SizedBox(height: 5)
  //           ],
  //         )));
  //       });
  // }
}
