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

import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/style/index.dart';
import '../../../common/utils/index.dart';
import '../../../common/widgets/index.dart';
import 'index.dart';

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

  @override
  Widget build(BuildContext context) {
    return GetBuilder<AppsController>(
      builder: (_) {
        return Scaffold(
          appBar:
              AppBar(title: Obx(() => Text(controller.state.title)), actions: [
            TextButton(
                onPressed: controller.clickEditMyAppTopBtn,
                child: Obx(() => Text(
                      controller.state.isEdit ? 'save'.tr : 'edit'.tr,
                      style: AppTheme.whitePrimaryTextStyle,
                    )))
          ]),
          body: SafeArea(
            child: Container(
                color: Theme.of(context).scaffoldBackgroundColor,
                child: ListView(
                  children: [
                    ProgramCenterService.to.appPageImageView(),
                    Obx(() => appBoxView(context, 'app_type_my'.tr, controller.state.myAppList, true)),
                    const SizedBox(height: 10),
                    Container(child: appListView(context))
                  ],
                )),
          ),
        );
      },
    );
  }

  Widget appListView(BuildContext context) {
    return Column(
      children: [
        Obx(() => appBoxView(
            context, 'app_type_native'.tr, controller.state.nativeList, false)),
        const SizedBox(height: 10),
        Obx(() => appBoxView(
            context, 'app_type_portal'.tr, controller.state.portalList, false))
      ],
    );
  }

  ///
  /// 应用列表方块
  ///
  Widget appBoxView(
      BuildContext context, String title, List<AppFrontData?> appList, bool isMyApp) {
    final screenWidth = MediaQuery.of(context).size.width;
    final itemAxisCount = screenWidth > 560 ? 6 : (screenWidth > 375 ? 5 : 4);
    final itemWidth = (screenWidth - 50 - (itemAxisCount - 1) * 5) / itemAxisCount;
    const itemHeight = 60;
    final ratio = itemWidth / itemHeight;
    OLogger.d('screenWidth:$screenWidth, itemWidth: $itemWidth, itemHeight: $itemHeight, ratio: $ratio');
    return Container(
      color: Theme.of(context).colorScheme.background,
      width: double.infinity,
      child: Padding(
          padding:
              const EdgeInsets.only(top: 10, bottom: 5, left: 15, right: 15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(title, style: Theme.of(context).textTheme.bodyLarge),
              const SizedBox(height: 5),
              Padding(
                  padding: const EdgeInsets.all(10),
                  child: GridView.count(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      crossAxisCount: itemAxisCount,
                      mainAxisSpacing: 10,
                      crossAxisSpacing: 5,
                      childAspectRatio: ratio,
                      children: appList.map((element) {
                        if (element == null) {
                          return Container();
                        }
                        return appItemView(context, element, false);
                      }).toList()))
            ],
          )),
    );
  }

  ///
  /// 我的应用列表方块
  ///
  // Widget myAppBoxView(BuildContext context) {
  //   final screenWidth = MediaQuery.of(context).size.width;
  //   final itemAxisCount = screenWidth > 560 ? 6 : (screenWidth > 375 ? 5 : 4);
  //   final itemWidth = (screenWidth - 50 - (itemAxisCount - 1) * 5) / itemAxisCount;
  //   const itemHeight = 60;
  //   final ratio = itemWidth / itemHeight;
  //   OLogger.d('screenWidth:$screenWidth, itemWidth: $itemWidth, itemHeight: $itemHeight, ratio: $ratio');
  //   return Obx(() => Container(
  //         color: Theme.of(context).colorScheme.background,
  //         width: double.infinity,
  //         child: Padding(
  //             padding: const EdgeInsets.only(
  //                 top: 10, bottom: 5, left: 15, right: 15),
  //             child: Column(
  //               crossAxisAlignment: CrossAxisAlignment.start,
  //               children: [
  //                 Text('app_type_my'.tr,
  //                     style: Theme.of(context).textTheme.bodyLarge),
  //                 const SizedBox(height: 5),
  //                 Padding(
  //                     padding: const EdgeInsets.all(10),
  //                     child: controller.state.myAppList.isEmpty
  //                         ? Container()
  //                         : GridView.count(
  //                             shrinkWrap: true,
  //                             crossAxisCount: itemAxisCount,
  //                             mainAxisSpacing: 10,
  //                             crossAxisSpacing: 5,
  //                             childAspectRatio: ratio,
  //                             children:
  //                                 controller.state.myAppList.map((element) {
  //                               if (element == null) {
  //                                 return Container();
  //                               }
  //                               return appItemView(context, element, true);
  //                             }).toList()))
  //               ],
  //             )),
  //       ));
  // }

  ///
  /// 单个应用View
  /// @param isMyApp 是否主页应用上显示，编辑的时候右上角小图标不一样
  ///
  Widget appItemView(BuildContext context, AppFrontData element, bool isMyApp) {
    return Obx(() => controller.state.isEdit
        ? GestureDetector(
            onTap: () => isMyApp
                ? controller.removeApp2MyList(element)
                : (controller.isInMyApp(element)
                    ? controller.removeApp2MyList(element)
                    : controller.addApp2MyList(element)),
            child: Stack(
              children: [
                _appItemView(context, element),
                Positioned(
                    right: 0,
                    top: 0,
                    child: AssetsImageView(
                      isMyApp
                          ? 'icon_app_del.png'
                          : (controller.isInMyApp(element)
                              ? 'icon_app_del.png'
                              : 'icon_app_add.png'),
                      width: 12,
                      height: 12,
                    )),
              ],
            ))
        : GestureDetector(
            onTap: () => controller.openApp(element),
            child: _appItemView(context, element),
          ));
  }

  /// 应用 Item
  Widget _appItemView(BuildContext context, AppFrontData element) {
    var showName = element.displayName ?? '';
    if (showName.trim().isEmpty) {
      showName = element.name ?? '';
    }
    return Column(children: [
      // Icon图标，原生应用是本地图标，门户应用是url
      _appItemImageWithBadges(element),
      Expanded(
          flex: 1,
          child: Center(
              child: Text(showName,
                  softWrap: true,
                  style: Theme.of(context).textTheme.bodyMedium)))
    ]);
  }

  /// 应用图标 加上角标
  /// 编辑的时候不显示角标
  Widget _appItemImageWithBadges(AppFrontData element) {
    return Obx(() => controller.state.isEdit
        ? _appItemImage(element)
        : O2UI.badgeView((element.showNumber ?? 0), _appItemImage(element)));
  }

  /// 应用图标
  Widget _appItemImage(AppFrontData element) {
    Map<String, String> headers = {};
    headers[O2ApiManager.instance.tokenName] =
        O2ApiManager.instance.o2User?.token ?? '';
    return (element.type == O2AppTypeEnum.native)
        ? AssetsImageView(
            element.nativeEnum?.assetPath ?? 'app_task.png',
            width: 36,
            height: 36,
          )
        : Image(
            image: NetworkImage(element.portalIconUrl!, headers: headers),
            alignment: Alignment.center,
            width: 36,
            height: 36,
            fit: BoxFit.fill);
  }
}
