// ignore_for_file: prefer_const_constructors

import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:get/get.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 BannerAndAppsWidget extends GetView<DefaultIndexController> {
  const BannerAndAppsWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    return Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(10),
              bottomRight: Radius.circular(10)),
          color: Theme.of(context).colorScheme.background,
        ),
        child: Padding(
          padding: const EdgeInsets.only(
              left: 15.0, right: 15.0, top: 15.0, bottom: 10.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _bannerView(context),
              const SizedBox(height: 5),
              _appListView(screenWidth)
            ],
          ),
        ));
  }

  /// 应用快捷键列表
  Widget _appListView(double screenWidth) {
    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(() => GridView.builder(
        ///Container跟随GridView内容变化高度, shrinkWrap:true;
        shrinkWrap: true,
        ///取消滚动效果physics: NeverScrollableScrollPhysics();
        physics: const NeverScrollableScrollPhysics(),
        itemCount: controller.state.myAppList.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: itemAxisCount,
          mainAxisSpacing: 10,
          crossAxisSpacing: 0,
          childAspectRatio: ratio,
        ),
        itemBuilder: (context, index) {
          var app = controller.state.myAppList[index];
          return GestureDetector(
              onTap: () => controller.openApp(app),
              child: _appItemView(context, app!));
        }));
  }

  Widget _appItemView(BuildContext context, AppFrontData element) {
    Map<String, String> headers = {};
    headers[O2ApiManager.instance.tokenName] =
        O2ApiManager.instance.o2User?.token ?? '';
    var showName = element.displayName ?? '';
    if (showName.trim().isEmpty) {
      showName = element.name ?? '';
    }
    return Column(children: [
      // Icon图标，原生应用是本地图标，门户应用是url
      O2UI.badgeView(
          element.showNumber ?? 0,
          (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)),

      Expanded(
          flex: 1,
          child: Center(
              child: Text(showName,
                  softWrap: true,
                  style: Theme.of(context).textTheme.bodyMedium)))
    ]);
  }

  /// 滚动大图
  Widget _bannerView(BuildContext context) {
    return Obx(() => controller.state.hotpicList.isEmpty
        ? Container(height: 0)
        : CarouselSlider.builder(
            itemCount: controller.state.hotpicList.length,
            itemBuilder: (content, index, realIndex) {
              HotpicData data = controller.state.hotpicList[index];
              String? url = O2ApiManager.instance.getHotPictureUrl(data.picId!);
              if (url != null && url.isNotEmpty) {
                Map<String, String> headers = {};
                headers[O2ApiManager.instance.tokenName] =
                    O2ApiManager.instance.o2User?.token ?? '';
                return GestureDetector(
                    onTap: () => controller.openHotPic(data),
                    child: Container(
                        margin: const EdgeInsets.only(
                            left: 2, right: 2, bottom: 10),
                        child: ClipRRect(
                            borderRadius:
                                const BorderRadius.all(Radius.circular(5.0)),
                            child: Stack(
                              children: [
                                Positioned.fill(
                                    child: Image(
                                        image:
                                            NetworkImage(url, headers: headers),
                                        alignment: Alignment.center,
                                        height: double.infinity,
                                        width: double.infinity,
                                        fit: BoxFit.fill)),
                                Positioned(
                                    bottom: 0,
                                    left: 0,
                                    right: 0,
                                    child: Container(
                                      padding: const EdgeInsets.symmetric(
                                          vertical: 5.0, horizontal: 10.0),
                                      color:
                                          AppColor.blackTransparentBackground,
                                      child: Text(data.title ?? '',
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 16)),
                                    ))
                              ],
                            ))));
              }
              return const AssetsImageView('banner_default.png');
            },
            options: CarouselOptions(
              height: 175,
              autoPlay: true,
              viewportFraction: 1,
              aspectRatio: 16 / 9,
            )));
  }
}
