import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:fis_ui/widgets/webview/webview.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/interfaces/webview_controller.dart';
import 'package:flyinsono/pages/upgrade/upgrade_widgets/upgrade_center.dart';
import 'package:flyinsono/pages/upgrade/upgrade_wrapper.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/views/desktop/notification_list/index.dart';
import 'package:get/get.dart';
import 'package:webviewx/webviewx.dart';
import 'package:fis_common/logger/logger.dart';
import 'index.dart';

///主页页面
class HomePagePage extends FisView<HomePageController> implements FPage {
  @override
  final String pageName;
  HomePagePage({this.pageName = 'HomePagePage', Key? key}) : super(key: key);

  @override
  FWidget build(BuildContext context) {
    try {
      if (FPlatform.isWindows || FPlatform.isMacOS) {
        rpc.platform.setLoginUserInfoAsync(
          Store.user.account!,
        );
      }
    } catch (e) {
      print(e);
    }

    return FScaffold(
      appBar: kIsMobile ? _MobileAppbar() : null,
      body: FSafeArea(
        child: FCenter(
          child: _buildMockDashboard(context),
        ),
      ),
    );
  }

  FWidget _buildMockDashboard(BuildContext context) {
    var isMobile = (FPlatform.isAndroid || FPlatform.isIOS);
    logger.i("User - [${Store.user.account}] login finished ");
    return FObx(() {
      if (controller.state.cmsUrl.isEmpty) {
        if (isMobile) {
          UpgradeWrapper.invokeUpgradeDirectly(context, false);
        }
        return FCenter(
          child: QuickFWidget(
            ColorFiltered(
              colorFilter: ColorFilter.mode(Colors.grey[300]!, BlendMode.srcIn),
              child: Image.asset(
                i18nBook.isCurrentChinese
                    ? 'assets/images/splash/logo_zh.png'
                    : 'assets/images/splash/logo_en.png',
                width: 200,
                height: 200,
              ),
            ),
          ),
        );
      } else {
        final manager = Get.find<IWebviewControllerManager>();
        var lang = i18nBook.locale.toCodeString('-');
        var cmsUrl = controller.state.cmsUrl
            .replaceAll('{0}', Store.user.code)
            .replaceAll('{1}', lang);
        logger.i(
            "cmsUrl :$cmsUrl，lang:$lang,localLang:${i18nBook.locale.toCodeString('-')}");
        return FLayoutBuilder(
          builder: (context, constraints) {
            final webview = FWebViewX(
              height: MediaQuery.of(Get.context!).size.height,
              width: MediaQuery.of(Get.context!).size.width,
              initialContent: (kDebugMode && isMobile)
                  ? 'http://192.168.6.117:8000'
                  : cmsUrl,
              javascriptMode: JavascriptMode.unrestricted,
              ignoreAllGestures: isMobile ? false : manager.isDialogExist,
              onWebViewCreated: isMobile
                  ? null
                  : (c) async {
                      if (UpgradeCenter.isChecking) {
                        logger.i('set UpgradeCenter.isChecking false');
                        UpgradeCenter.isChecking = false;
                      }
                      await UpgradeWrapper.invokeUpgradeDirectly(
                          context, false);
                      manager.initWebviewController(c);
                    },
            );
            return FContainer(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: webview,
            );
          },
        );
      }
    });
  }
}

///移动端APPBar
class _MobileAppbar extends StatelessWidget
    implements PreferredSizeWidget, FInteractiveContainer {
  final HomePageController controller = Get.find<HomePageController>();

  @override
  Size get preferredSize => Size.fromHeight(kToolbarHeight);

  @override
  String get pageName => "mobile_calendar";

  @override
  FWidget build(BuildContext context) {
    return FObx(() => FAppBar(
          centerTitle: false,
          title: FGestureDetector(
            name: 'home_page_title',
            businessParent: this,
            // onTap: () {
            //   if (kDebugMode) {
            //     Get.toNamed(
            //       RouteNames.User.GroupChat,
            //       arguments: ChatPageArgs(
            //         groupName: "测试群聊",
            //         userGroupCode: "123456",
            //         placeHolderStr: "占位数据",
            //         totalMembers: 0
            //       ),
            //     );
            //   }
            // },
            child: FText(
              i18nBook.homePage.homePage.t +
                  (controller.state.showNetworkError
                      ? i18nBook.common.networkErrorMobile.t
                      : ""),
              textAlign: TextAlign.center,
            ),
          ),
          flexibleSpace: FContainer(
              child: FAlign(
            alignment: Alignment.bottomRight,
            child: FRow(
              mainAxisSize: MainAxisSize.min,
              children: [
                FContainer(
                  child: NotificationListButton4Mobile(),
                ),
                FInkWell(
                  onTap: () {
                    ///路由到日历页面
                    Get.toNamed("/calendar");
                  },
                  child: FContainer(
                    margin: const EdgeInsets.all(14),
                    child: FIcon(
                      Icons.date_range,
                      color: Colors.black,
                      size: 30,
                    ),
                  ),
                ),
              ],
            ),
          )),
          elevation: 0,
          automaticallyImplyLeading: false,
          backgroundColor: Colors.white,
          foregroundColor: Colors.black,
          titleSpacing: 24,
        ));
  }
}
