import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/login.m.dart';
import 'package:fis_measure/utils/prompt_box.dart';
import 'package:fis_theme/theme.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/values/font_sizes.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/desktop/names.dart';
import 'package:flyinsono/architecture/router/desktop/routes.dart';
import 'package:flyinsono/architecture/router/mobile/names.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/values/features.dart';
import 'package:flyinsono/managers/interfaces/permission.dart';
import 'package:flyinsono/managers/interfaces/server_config.dart';
import 'package:flyinsono/pages/main/home/controller.dart';
import 'package:flyinsono/pages/third_party_page/feedback/view.dart';
import 'package:flyinsono/pages/upgrade/upgrade_widgets/upgrade_center.dart';
import 'package:flyinsono/pages/user/user_center/widgets/avatar_panel.dart';
import 'package:flyinsono/pages/user/user_center/widgets/desk_top_module_card.dart';
import 'package:flyinsono/pages/user/user_center/widgets/mobile_module_card.dart';
import 'package:flyinsono/pages/user/user_device/widgets/qr_view_example.dart';
import 'package:get/get.dart';

import 'index.dart';

///用户中心页面
class UserCenterPage extends FisView<UserCenterController> implements FPage {
  @override
  final String pageName;
  const UserCenterPage({this.pageName = 'UserCenterPage', Key? key})
      : super(key: key);
  @override
  FWidget build(BuildContext context) {
    return context.fResponsiveVoid(
      mobile: () => _MobileLayout(this),
      desktop: () => _DesktopLayout(this),
    );
  }
}

class _DesktopLayout extends FisView<UserCenterController>
    with _SignOutAlert
    implements FPage {
  @override
  String get pageName => 'UserCenterDesktopPage';
  static final _regionTitleStyle = const TextStyle(fontSize: 20);

  ///父级节点
  final FPage businessParent;
  final ScrollController _scrollController = ScrollController();
  late final double? moduleWidth;
  _DesktopLayout(this.businessParent) {
    /// TODO:[Gavin] 多语言-UI-整合
    moduleWidth = i18nBook.isCurrentChinese == true ? null : 300;
  }

  @override
  FWidget build(BuildContext context) {
    return FObx(() {
      final featuresLength = Store.user.featuresLength;
      return _buildFStack(featuresLength, context);
    });
  }

  FWidget _buildFStack(int featuresLength, BuildContext context) {
    return FStack(
      children: [
        FPositioned(
          top: 0,
          height: 140.sp,
          left: 0,
          right: 0,
          child: _buildUserCenterHeader(),
        ),
        FPositioned(
          top: (140 + 6).sp,
          left: 0,
          right: 0,
          bottom: 0,
          child: _buildUserCenterBody(context),
        ),
      ],
    );
  }

  ///用户所需个人模块
  List<DesktopModuleCard> _buildFuncModules() {
    final isCurrentRussian = Get.find<FI18n>().currentBook.isCurrentRussian;
    List<DesktopModuleCard> children = [
      if (Store.user.hasFeature(FeatureKeys.UserProfile))
        DesktopModuleCard(
          businessParent: businessParent,
          label: i18nBook.auth.account.t,
          iconData: FIcons.account,
          width: moduleWidth,
          onPressed: controller.editProfile,
        ),
      if (Store.user.hasFeature(FeatureKeys.Password))
        DesktopModuleCard(
          businessParent: businessParent,
          label: i18nBook.auth.password.t,
          iconData: Icons.lock_reset,
          width: moduleWidth,
          onPressed: () {
            controller.changePassword();
          },
        ),
      if (Store.user.hasFeature(FeatureKeys.UserEntry))
        DesktopModuleCard(
          businessParent: businessParent,
          width: moduleWidth,
          label: i18nBook.user.myEntry.t,
          iconData: FIcons.word_entry,
          onPressed: () async {
            controller.vocabularyEntry(false);
          },
        ),
      if (Store.user.hasFeature(FeatureKeys.UserDevices))
        DesktopModuleCard(
          businessParent: businessParent,
          label: i18nBook.user.myDevices.t,
          iconData: FIcons.device,
          width: moduleWidth,
          onPressed: () => controller.userDevice(),
        ),
      if (Store.user.hasFeature(FeatureKeys.UserReportTemplate))
        DesktopModuleCard(
          businessParent: businessParent,
          label: i18nBook.user.myTemplate.t,
          iconData: FIcons.report_template_org,
          width: moduleWidth,
          onPressed: () async {
            controller.userReporTemplate();
          },
        ),
      if (Store.user.hasFeature(FeatureKeys.UserGroups))
        DesktopModuleCard(
          businessParent: businessParent,
          label: i18nBook.user.myGroups.t,
          iconData: Icons.people,
          width: moduleWidth,
          onPressed: () async {
            router.to(RouteNames.User.GroupList, id: NavIds.HOME);
          },
        ),
      // if (!isCurrentRussian)
      //   DesktopModuleCard(
      //     businessParent: businessParent,
      //     label: i18nBook.college.pastVideo.t,
      //     iconData: Icons.video_library_outlined,
      //     width: moduleWidth,
      //     onPressed: () async {
      //       router.to(RouteNames.College.PastVideos, id: NavIds.HOME);
      //     },
      //   ),
    ];
    if (controller.state.hasAssociatedFeature) {
      children.addAll(_buildOtherModuleCard());
    }
    children.add(
      // if (Store.user.hasFeature(FeatureKeys.Setting))
      DesktopModuleCard(
        businessParent: businessParent,
        label: i18nBook.user.setting.t,
        iconData: FIcons.setting,
        width: moduleWidth,
        onPressed: () async {
          await UpgradeCenter.getCurrentFISVersion();
          await controller.userSetting();
        },
      ),
    );
    return children;
  }

  ///组织设备模块
  List<DesktopModuleCard> _buildOrgModules() {
    return [
      if (Store.user.hasFeature(FeatureKeys.OrgInfo))
        DesktopModuleCard(
          businessParent: businessParent,
          label: i18nBook.homePage.organizationInfo.t,
          iconData: FIcons.info_org,
          width: moduleWidth,
          onPressed: controller.orgInfo,
        ),
      if (Store.user.hasFeature(FeatureKeys.OrgPersonnel))
        DesktopModuleCard(
          businessParent: businessParent,
          label: i18nBook.organization.orgStructure.t,
          iconData: FIcons.org_structure,
          width: moduleWidth,
          onPressed: controller.orgComPany,
        ),
      if (Store.user.hasFeature(FeatureKeys.OrgDevices))
        DesktopModuleCard(
          businessParent: businessParent,
          label: i18nBook.homePage.organizationDevices.t,
          iconData: FIcons.device_org,
          width: moduleWidth,
          onPressed: controller.orgDevice,
        ),
      if (Store.user.hasFeature(FeatureKeys.OrgEntries))
        DesktopModuleCard(
          businessParent: businessParent,
          label: i18nBook.homePage.organizationEntries.t,
          iconData: FIcons.word_entry_org,
          width: moduleWidth,
          onPressed: () => controller.vocabularyEntry(true),
        ),
      if (Store.user.hasFeature(FeatureKeys.OrgReportTemplate))
        DesktopModuleCard(
          businessParent: businessParent,
          label: i18nBook.user.orgTemplate.t,
          iconData: FIcons.report_template_org,
          width: moduleWidth,
          onPressed: () {
            controller.userReporTemplate(isOrg: true);
          },
        ),
    ];
  }

  ///用户中心页面
  FWidget _buildUserCenterBody(BuildContext context) {
    return FObx(() {
      bool isPrincipal = Store.user.hasOrgFeature() ?? false;
      return FContainer(
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 48, vertical: 24),
        child: FAlwaysScrollListView(
          scrollController: _scrollController,
          child: QuickFWidget(ScrollConfiguration(
            behavior:
                ScrollConfiguration.of(context).copyWith(scrollbars: false),
            child: FListView(
              controller: _scrollController,
              children: [
                if (isPrincipal) ...[
                  FRow(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      FText(i18nBook.user.personalInfo.t,
                          style: _regionTitleStyle)
                    ],
                  ),
                  const FSizedBox(height: 8),
                ],
                FWrap(
                  direction: Axis.horizontal,
                  spacing: 20,
                  runSpacing: 20,
                  children: _buildFuncModules(),
                ),
                if (isPrincipal) ...[
                  const FSizedBox(height: 60),
                  FRow(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      FText(i18nBook.user.organizationManage.t,
                          style: _regionTitleStyle)
                    ],
                  ),
                  const FSizedBox(height: 8),
                  FWrap(
                    direction: Axis.horizontal,
                    spacing: 20,
                    runSpacing: 20,
                    children: _buildOrgModules(),
                  ),
                ],
              ],
            ),
          )),
        ),
      );
    });
  }

  ///用户中心页面头部
  FWidget _buildUserCenterHeader() {
    final body = FContainer(
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 12),
      child: FRow(
        mainAxisSize: MainAxisSize.min,
        children: [
          AvatarPanel(),
          FSizedBox(width: 12),
          FExpanded(child: FContainer()),
          FInkWell(
            onTap: () {
              onSignOut(businessParent);
            },
            child: FText(
              i18nBook.auth.signOut.t,
              style: TextStyle(color: Colors.black87),
            ),
          ),
          FIconButton(
            name: "exit",
            businessParent: businessParent,
            icon: FIcon(
              Icons.exit_to_app_sharp,
              color: Colors.black54,
            ),
            onPressed: () {
              onSignOut(businessParent);
            },
          ),
        ],
      ),
    );

    return body;
  }

  List<DesktopModuleCard> _buildOtherModuleCard() {
    List<DesktopModuleCard> result = [];
    for (var i in Store.user.associatedFeatures) {
      if (i.associatedPosition == PERSONCENTER) {
        result.add(
          DesktopModuleCard(
            businessParent: businessParent,
            label: i18nBook.isCurrentChinese ? i.cTitle ?? '' : i.eTitle ?? '',
            iconData: FIcons.account,
            width: moduleWidth,
            iconUrl: i.icon,
            onPressed: () async {
              router.to(
                RouteNames.Thirdparty.ThirdpartyPage,
                id: NavIds.HOME,
                parameters: {
                  "source": PERSONCENTER,
                  "url": i.url ?? '',
                  "index": i.index.toString(),
                  "name": i18nBook.isCurrentChinese
                      ? i.cTitle ?? ''
                      : i.eTitle ?? '',
                },
              );
            },
          ),
        );
      }
    }
    return result;
  }
}

class _MobileLayout extends FisView<UserCenterController>
    with _SignOutAlert
    implements FPage {
  @override
  String get pageName => 'UserCenterController _MobileLayout';
  static const _HeaderHeight = 110;
  final ScrollController _scrollController = ScrollController();
  final isCurrentRussian = Get.find<FI18n>().currentBook.isCurrentRussian;

  // 是否为测试账号
  final isTestAccount = Store.user.displayName == 'scantest';

  ///父级节点
  final FPage businessParent;
  _MobileLayout(this.businessParent);
  @override
  FWidget build(BuildContext context) {
    return FSafeArea(
      child: FContainer(
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 14.sp),
        child: FObx(
          () {
            final featuresLength = Store.user.featuresLength;
            return FColumn(
              mainAxisSize: MainAxisSize.max,
              children: [
                FExpanded(child: _buildMobileFStack(featuresLength, context)),
                FRow(
                  children: [
                    FExpanded(
                      child: FContainer(
                        margin: EdgeInsets.symmetric(
                          vertical: 15,
                        ),
                        child: _buildLogOutRow(),
                      ),
                    ),
                  ],
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  ///功能模块区域
  List<FWidget> _buildFucModules() {
    var otherNavNames = Store.user.associatedFeatures
        .where((element) => element.associatedPosition == PERSONCENTER)
        .toList();
    return [
      if (Store.user.hasFeature(FeatureKeys.UserProfile))
        MobileModuleCard(
          label: i18nBook.auth.account.t,
          iconData: FIcons.account,
          onPressed: controller.editProfile,
        ),
      if (Store.user.hasFeature(FeatureKeys.Password))
        MobileModuleCard(
          label: i18nBook.auth.password.t,
          iconData: Icons.lock_reset,
          onPressed: () {
            controller.changePassword();
          },
        ),
      if (Store.user.hasFeature(FeatureKeys.UserDevices) &&
          !isTestAccount) // 测试账号不显示
        MobileModuleCard(
          label: i18nBook.user.myDevices.t,
          iconData: FIcons.device,
          onPressed: () => controller.userDevice(),
        ),
      //TODO[melon]: 暂时放这里，后期迁移到合适的地方
      if (Store.user.hasFeature(FeatureKeys.UserDevices) &&
          !isTestAccount) // 测试账号不显示
        MobileModuleCard(
          label: i18nBook.live.deviceLive.t,
          iconData: Icons.live_tv,
          onPressed: () {
            router.to(RouteNames.Live.DeviceList);
          },
        ),
      if (!isCurrentRussian &&
          kIsMobile &&
          Store.user.hasFeature(FeatureKeys.FlyinsonoCollege)) // 俄语下不显示
        MobileModuleCard(
          label: i18nBook.common.flyinsonoCollege.t,
          iconData: Icons.school,
          onPressed: () {
            router.to(MobileRouteNames.College.FlyinsonoCollege);
          },
        ),
      if (Store.user.hasFeature(FeatureKeys.UserEntry))
        MobileModuleCard(
          label: i18nBook.user.entryLibrary.t,
          iconData: FIcons.word_entry,
          onPressed: () => controller.vocabularyEntry(false),
        ),
      if (otherNavNames.isNotEmpty) ...[
        ..._buildOtherModuleCard(otherNavNames),
      ],
      if (Store.user.hasFeature(FeatureKeys.UserGroups)) ...[
        MobileModuleCard(
          label: i18nBook.user.group.t,
          iconData: Icons.group,
          onPressed: () {
            router.to(RouteNames.User.GroupList);
          },
        ),
      ],

      MobileModuleCard(
        label: i18nBook.user.about.t,
        iconData: FIcons.logo,
        onPressed: () => controller.aboutFlyinsono(),
      ),
    ];
  }

  ///登出
  FWidget _buildLogOutRow() {
    return FOutlinedButton(
      businessParent: businessParent,
      name: "signOut",
      child: FText(i18nBook.auth.signOut.t),
      onPressed: () {
        onSignOut(businessParent);
      },
      style: OutlinedButton.styleFrom(
        fixedSize: Size.fromHeight(42.sp),
      ),
    );
  }

  FWidget _buildMobileFStack(int featuresLength, BuildContext context) {
    return FStack(
      children: [
        FPositioned(
          top: 0,
          height: _HeaderHeight.sp,
          left: 0,
          right: 0,
          child: AvatarPanel(),
        ),
        FPositioned(
          top: _HeaderHeight.sp,
          left: 4.sp,
          right: 4.sp,
          child: FDivider(
            thickness: 1,
            color: Colors.grey[350],
          ),
        ),
        FPositioned(
          top: (_HeaderHeight + 16).sp,
          left: 0,
          right: 0,
          bottom: 0,
          child: _buildUserCenterBody(context),
        ),
        FPositioned(
          top: 0,
          right: 0,
          child: _buildScanQrIcon(),
        ),
      ],
    );
  }

  ///组织相关区域
  List<FWidget> _buildOrgModules() {
    return [
      if (Store.user.hasFeature(FeatureKeys.OrgInfo))
        MobileModuleCard(
          label: i18nBook.homePage.organizationInfo.t,
          iconData: FIcons.info_org,
          onPressed: () {
            controller.orgInfo();
          },
        ),
      if (Store.user.hasFeature(FeatureKeys.OrgPersonnel))
        MobileModuleCard(
          label: i18nBook.organization.orgStructure.t,
          iconData: FIcons.org_structure,
          onPressed: () {
            controller.orgComPany();
          },
        ),
      if (Store.user.hasFeature(FeatureKeys.OrgDevices))
        MobileModuleCard(
          label: i18nBook.homePage.organizationDevices.t,
          iconData: FIcons.device_org,
          onPressed: () => controller.orgDevice(),
        ),
      if (Store.user.hasFeature(FeatureKeys.OrgEntries))
        MobileModuleCard(
          label: i18nBook.homePage.organizationEntries.t,
          iconData: FIcons.word_entry_org,
          onPressed: () => controller.vocabularyEntry(true),
        ),
    ];
  }

  FWidget _buildScanQrIcon() {
    return FGestureDetector(
      child: FIcon(
        FIcons.fis_scan,
        size: FFontSizes.H2,
        color: FTheme.ins.colorScheme.primary,
      ),
      onTap: () async {
        var checkNet = await Get.find<IServerConfigManager>().checkNetWork();
        if (!checkNet) {
          PromptBox.toast(i18nBook.common.networkError.t);
          return;
        }
        var permissionManager = Get.find<IPermissionManager>();
        bool hasPermission = await permissionManager.checkCameraPermission();
        if (hasPermission) {
          Get.to(
            () => QRViewExample(
              onPressed: controller.onScanData,
            ),
          );
        }
      },
      businessParent: businessParent,
      name: "Scan QR Icon",
    );
  }

  ///用户中心按钮区域
  FWidget _buildUserCenterBody(BuildContext context) {
    return FPadding(
      padding: EdgeInsets.only(top: 8.sp),
      child: FAlwaysScrollListView(
        scrollController: _scrollController,
        child: QuickFWidget(ScrollConfiguration(
          behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
          child: FListView(
            controller: _scrollController,
            children: [
              _createModuleZoneBox(_buildFucModules()),
              FSizedBox(height: 8.sp),
              FObx(() {
                if (Store.user.isPrincipal) {
                  return _createModuleZoneBox(_buildOrgModules());
                } else {
                  return FSizedBox();
                }
              }),
            ],
          ),
        )),
      ),
    );
  }

  ///模块化区域
  FWidget _createModuleZoneBox(List<FWidget> children) {
    return FContainer(
      padding: EdgeInsets.symmetric(vertical: FSpacings.XXL),
      alignment: Alignment.centerLeft,
      decoration: new BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(FSpacings.M)),
        border: new Border.all(width: 1, color: Colors.grey[350]!),
      ),
      child: FGridView(
        shrinkWrap: true,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
        ),
        children: children,
      ),
    );
  }

  List<FWidget> _buildOtherModuleCard(
      List<AssociatedFeatureInfoDTO> otherNavNames) {
    List<FWidget> result = [];
    result.addAll(otherNavNames
        .map(
          (e) => MobileCustomIconModuleCard(
            label: (i18nBook.isCurrentChinese ? e.cTitle : e.eTitle) ?? '',
            iconUrl: e.icon ?? '',
            onPressed: () {
              var routerName = RouteNames.Thirdparty.ThirdpartyPage;
              var parameters = {
                "source": PERSONCENTER,
                "url": e.url ?? '',
                "index": e.index.toString(),
                "name":
                    i18nBook.isCurrentChinese ? e.cTitle ?? '' : e.eTitle ?? '',
              };
              router.to(routerName, id: NavIds.HOME, parameters: parameters);
            },
          ),
        )
        .toList());
    return result;
  }
}

class _SignOutAlert {
  /// 登出
  void onSignOut(FInteractiveContainer paraent) {
    var controller = Get.find<HomeController>();
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.common.tip.t,
      subTitle: i18nBook.homePage.loginOutConfirm.t,
      confrimLabel: i18nBook.common.confirm.t,
      cancelLabel: i18nBook.common.cancel.t,
      businessParent: paraent,
      onConfirm: () async {
        await controller.busyHandle(
          () async {
            try {
              await Store.user.handelLogOut();
            } catch (e) {
              print(e);
            }
          },
          text: i18nBook.homePage.loginingOut.t,
        );
        router.offAll(RouteNames.Auth.AuthBoard);
      },
    );
  }
}
