import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yumi/ui_kit/components/sc_debounce_widget.dart';
import 'package:marquee/marquee.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../../../app_localizations.dart';
import '../../../../app/constants/sc_global_config.dart';
import '../../../../app/routes/sc_fluro_navigator.dart';
import '../../../../shared/tools/sc_banner_utils.dart';
import '../../../../shared/data_sources/sources/repositories/sc_room_repository_imp.dart';
import '../../../../shared/business_logic/models/res/follow_room_res.dart';
import '../../../../shared/business_logic/models/res/room_res.dart';
import '../../../../services/general/sc_app_general_manager.dart';
import '../../../../services/audio/rtc_manager.dart';
import '../../../../ui_kit/components/sc_compontent.dart';
import '../../../../ui_kit/components/text/sc_text.dart';
import '../../../index/main_route.dart';

class SCHomePartyPage extends StatefulWidget {
  @override
  _HomePartyPageState createState() => _HomePartyPageState();
}

class _HomePartyPageState extends State<SCHomePartyPage>
    with SingleTickerProviderStateMixin {
  List<FollowRoomRes> historyRooms = [];
  String? lastId;
  bool isLoading = false;
  final RefreshController _refreshController = RefreshController(
    initialRefresh: false,
  );
  List<SocialChatRoomRes> rooms = [];
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.transparent,
      body: Stack(
        alignment: AlignmentDirectional.bottomCenter,
        children: [
          SmartRefresher(
            enablePullDown: true,
            enablePullUp: false,
            controller: _refreshController,
            onRefresh: () {
              loadData();
            },
            onLoading: () {},
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Stack(
                    alignment: AlignmentDirectional.center,
                    children: [
                      Consumer<SCAppGeneralManager>(
                        builder: (context, ref, child) {
                          return _banner(ref);
                        },
                      ),
                    ],
                  ),
                  Consumer<SCAppGeneralManager>(
                    builder: (context, ref, child) {
                      return _banner2(ref);
                    },
                  ),
                  rooms.isEmpty
                      ? GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          loadData();
                        },
                        child:
                            isLoading
                                ? Center(
                                  child: CupertinoActivityIndicator(
                                    color: Colors.white24,
                                  ),
                                )
                                : mainEmpty(
                                  msg: SCAppLocalizations.of(context)!.noData,
                                ),
                      )
                      : GridView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2, // 每行2个
                          childAspectRatio: 1, // 宽高比
                          mainAxisSpacing: 10,
                          crossAxisSpacing: 10,
                        ),
                        padding: EdgeInsets.all(10),
                        itemCount: rooms!.length,
                        itemBuilder: (context, index) {
                          return _buildItem(rooms[index], index);
                        },
                      ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  _banner(SCAppGeneralManager ref) {
    if (ref.exploreBanners.isEmpty) {
      return Container();
    }
    return Stack(
      alignment: AlignmentDirectional.bottomCenter,
      children: [
        CarouselSlider(
          options: CarouselOptions(
            height: 95.w,
            autoPlay: true,
            // 启用自动播放
            enlargeCenterPage: false,
            // 居中放大当前页面
            enableInfiniteScroll: true,
            // 启用无限循环
            autoPlayAnimationDuration: Duration(milliseconds: 800),
            // 自动播放动画时长
            viewportFraction: 1,
            // 视口分数
            onPageChanged: (index, reason) {
              _currentIndex = index;
              setState(() {});
            },
          ),
          items:
              ref.exploreBanners.map((item) {
                return GestureDetector(
                  child: netImage(
                    url: item.cover ?? "",
                    height: 95.w,
                    width: ScreenUtil().screenWidth * 0.9,
                    fit: BoxFit.fill,
                    borderRadius: BorderRadius.circular(12.w),
                  ),
                  onTap: () {
                    print('ads:${item.toJson()}');
                    SCBannerUtils.openBanner(item, context);
                  },
                );
              }).toList(),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children:
              ref.exploreBanners.asMap().entries.map((entry) {
                return Container(
                  width: 6.0,
                  height: 6.0,
                  margin: EdgeInsets.symmetric(vertical: 8.0, horizontal: 4.0),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color:
                        _currentIndex == entry.key ? Colors.blue : Colors.white,
                  ),
                );
              }).toList(),
        ),
      ],
    );
  }

  _banner2(SCAppGeneralManager ref) {
    String roomGiftOneAvatar = "";
    String roomGiftTwoAvatar = "";
    String roomGiftThreeAvatar = "";
    if (ref.appLeaderResult?.roomGiftsLeaderboard != null &&
        ref.appLeaderResult?.roomGiftsLeaderboard?.weekly != null) {
      if ((ref.appLeaderResult?.roomGiftsLeaderboard?.weekly?.isNotEmpty ??
              false) &&
          ref.appLeaderResult?.roomGiftsLeaderboard?.weekly?.first != null) {
        roomGiftOneAvatar =
            ref.appLeaderResult?.roomGiftsLeaderboard?.weekly?.first.avatar ??
            "";
      }

      if (ref.appLeaderResult!.roomGiftsLeaderboard!.weekly!.length > 1 &&
          ref.appLeaderResult?.roomGiftsLeaderboard?.weekly?[1] != null) {
        roomGiftTwoAvatar =
            ref.appLeaderResult?.roomGiftsLeaderboard?.weekly![1].avatar ?? "";
      }
      if (ref.appLeaderResult!.roomGiftsLeaderboard!.weekly!.length > 2 &&
          ref.appLeaderResult?.roomGiftsLeaderboard?.weekly?[2] != null) {
        roomGiftThreeAvatar =
            ref.appLeaderResult?.roomGiftsLeaderboard?.weekly![2].avatar ?? "";
      }
    }

    String wealthOneAvatar = "";
    String wealthTwoAvatar = "";
    String wealthThreeAvatar = "";

    if (ref.appLeaderResult?.giftsSendLeaderboard != null &&
        ref.appLeaderResult?.giftsSendLeaderboard?.weekly != null) {
      if ((ref.appLeaderResult?.giftsSendLeaderboard?.weekly?.isNotEmpty ??
              false) &&
          ref.appLeaderResult?.giftsSendLeaderboard?.weekly?.first != null) {
        wealthOneAvatar =
            ref.appLeaderResult?.giftsSendLeaderboard?.weekly?.first.avatar ??
            "";
      }

      if (ref.appLeaderResult!.giftsSendLeaderboard!.weekly!.length > 1 &&
          ref.appLeaderResult?.giftsSendLeaderboard?.weekly?[1] != null) {
        wealthTwoAvatar =
            ref.appLeaderResult?.giftsSendLeaderboard?.weekly![1].avatar ?? "";
      }
      if (ref.appLeaderResult!.giftsSendLeaderboard!.weekly!.length > 2 &&
          ref.appLeaderResult?.giftsSendLeaderboard?.weekly?[2] != null) {
        wealthThreeAvatar =
            ref.appLeaderResult?.giftsSendLeaderboard?.weekly![2].avatar ?? "";
      }
    }

    String charmOneAvatar = "";
    String charmTwoAvatar = "";
    String charmThreeAvatar = "";

    if (ref.appLeaderResult?.giftsReceivedLeaderboard != null &&
        ref.appLeaderResult?.giftsReceivedLeaderboard?.weekly != null) {
      if ((ref.appLeaderResult?.giftsReceivedLeaderboard?.weekly?.isNotEmpty ??
              false) &&
          ref.appLeaderResult?.giftsReceivedLeaderboard?.weekly?.first !=
              null) {
        charmOneAvatar =
            ref
                .appLeaderResult
                ?.giftsReceivedLeaderboard
                ?.weekly
                ?.first
                .avatar ??
            "";
      }

      if (ref.appLeaderResult!.giftsReceivedLeaderboard!.weekly!.length > 1 &&
          ref.appLeaderResult?.giftsReceivedLeaderboard?.weekly?[1] != null) {
        charmTwoAvatar =
            ref.appLeaderResult?.giftsReceivedLeaderboard?.weekly![1].avatar ??
            "";
      }
      if (ref.appLeaderResult!.giftsReceivedLeaderboard!.weekly!.length > 2 &&
          ref.appLeaderResult?.giftsReceivedLeaderboard?.weekly?[2] != null) {
        charmThreeAvatar =
            ref.appLeaderResult?.giftsReceivedLeaderboard?.weekly![2].avatar ??
            "";
      }
    }

    if (roomGiftOneAvatar.isEmpty &&
        wealthOneAvatar.isEmpty &&
        charmOneAvatar.isEmpty) {
      return Container();
    }
    return SizedBox(
      height: 130.w,
      child: Row(
        children: [
          Expanded(
            child: GestureDetector(
              child: Stack(
                alignment: AlignmentDirectional.center,
                children: [
                  PositionedDirectional(
                    start: 26.w,
                    top: 65.w,
                    child: head(url: wealthTwoAvatar, width: 30.w),
                  ),
                  Positioned(
                    top: 35.w,
                    child: head(url: wealthOneAvatar, width: 36.w),
                  ),
                  PositionedDirectional(
                    end: 24.w,
                    top: 65.w,
                    child: head(url: wealthThreeAvatar, width: 30.w),
                  ),
                  Image.asset(
                    SCGlobalConfig.businessLogicStrategy
                        .getPopularLeaderboardBackgroundImage('wealth'),
                    fit: BoxFit.fill,
                  ),
                ],
              ),
              onTap: () {
                SCNavigatorUtils.push(
                  context,
                  "${SCMainRoute.webViewPage}?url=${Uri.encodeComponent(SCGlobalConfig.wealthRankUrl)}&showTitle=false",
                  replace: false,
                );
              },
            ),
          ),
          Expanded(
            child: GestureDetector(
              child: Stack(
                alignment: AlignmentDirectional.center,
                children: [
                  PositionedDirectional(
                    start: 24.w,
                    top: 68.w,
                    child: head(url: roomGiftTwoAvatar, width: 30.w),
                  ),
                  Positioned(
                    top: 35.w,
                    child: head(url: roomGiftOneAvatar, width: 38.w),
                  ),
                  PositionedDirectional(
                    end: 25.w,
                    top: 69.w,
                    child: head(url: roomGiftThreeAvatar, width: 30.w),
                  ),
                  Image.asset(
                    SCGlobalConfig.businessLogicStrategy
                        .getPopularLeaderboardBackgroundImage('room'),
                    fit: BoxFit.fill,
                  ),
                ],
              ),
              onTap: () {
                SCNavigatorUtils.push(
                  context,
                  "${SCMainRoute.webViewPage}?url=${Uri.encodeComponent(SCGlobalConfig.roomRankUrl)}&showTitle=false",
                  replace: false,
                );
              },
            ),
          ),
          Expanded(
            child: GestureDetector(
              child: Stack(
                alignment: AlignmentDirectional.center,
                children: [
                  PositionedDirectional(
                    start: 26.w,
                    top: 66.w,
                    child: head(url: charmTwoAvatar, width: 30.w),
                  ),
                  Positioned(
                    top: 38.w,
                    child: head(url: charmOneAvatar, width: 37.w),
                  ),
                  PositionedDirectional(
                    end: 25.w,
                    top: 66.w,
                    child: head(url: charmThreeAvatar, width: 30.w),
                  ),
                  Image.asset(
                    SCGlobalConfig.businessLogicStrategy
                        .getPopularLeaderboardBackgroundImage('charm'),
                    fit: BoxFit.fill,
                  ),
                ],
              ),
              onTap: () {
                SCNavigatorUtils.push(
                  context,
                  "${SCMainRoute.webViewPage}?url=${Uri.encodeComponent(SCGlobalConfig.charmRankUrl)}&showTitle=false",
                  replace: false,
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  loadData() {
    setState(() {
      isLoading = true;
    });
    SCChatRoomRepository()
        .discovery(allRegion: true)
        .then((values) {
          rooms = values;
          isLoading = false;
          _refreshController.refreshCompleted();
          _refreshController.loadComplete();
          if (mounted) setState(() {});
        })
        .catchError((e) {
          _refreshController.loadNoData();
          _refreshController.refreshCompleted();
          isLoading = false;
          if (mounted) setState(() {});
        });
    Provider.of<SCAppGeneralManager>(context, listen: false).loadMainBanner();
    Provider.of<SCAppGeneralManager>(context, listen: false).appLeaderboard();
  }

  _buildItem(SocialChatRoomRes res, int index) {
    return SCDebounceWidget(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 5.w, vertical: 5.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.w),
          color: Colors.transparent,
        ),
        child: Stack(
          alignment: Alignment.bottomCenter,
          children: [
            Container(
              padding: EdgeInsets.all(3.w),
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage("sc_images/index/sc_icon_room_bord.png"),
                  fit: BoxFit.fill,
                ),
              ),
              child: netImage(
                url: res.roomCover ?? "",
                borderRadius: BorderRadius.circular(12.w),
                width: 200.w,
                height: 200.w,
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(vertical: 6.w),
              margin: EdgeInsets.symmetric(horizontal: 1.w),
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(
                    "sc_images/index/sc_icon_index_room_brd.png",
                  ),
                  fit: BoxFit.fill,
                ),
              ),
              child: Row(
                children: [
                  SizedBox(width: 10.w),
                  Consumer<SCAppGeneralManager>(
                    builder: (_, provider, __) {
                      return netImage(
                        url:
                        "${provider.findCountryByName(res.countryName ?? "")?.nationalFlag}",
                        width: 20.w,
                        height: 13.w,
                        borderRadius: BorderRadius.circular(2.w),
                      );
                    },
                  ),
                  SizedBox(width: 5.w),
                  Expanded(
                    child: SizedBox(
                      height: 21.w,
                      child: text(
                        res.roomName ?? "",
                        fontSize: 15.sp,
                        textColor: Color(0xffffffff),
                        fontWeight: FontWeight.w400,
                      ),
                      // (roomRes.roomProfile?.roomName?.length ?? 0) > 10
                      //     ? Marquee(
                      //       text: roomRes.roomProfile?.roomName ?? "",
                      //       style: TextStyle(
                      //         fontSize: 15.sp,
                      //         color: Color(0xffffffff),
                      //         fontWeight: FontWeight.w400,
                      //         decoration: TextDecoration.none,
                      //       ),
                      //       scrollAxis: Axis.horizontal,
                      //       crossAxisAlignment: CrossAxisAlignment.start,
                      //       blankSpace: 20.0,
                      //       velocity: 40.0,
                      //       pauseAfterRound: Duration(seconds: 1),
                      //       accelerationDuration: Duration(seconds: 1),
                      //       accelerationCurve: Curves.easeOut,
                      //       decelerationDuration: Duration(
                      //         milliseconds: 500,
                      //       ),
                      //       decelerationCurve: Curves.easeOut,
                      //     )
                      //     : Text(
                      //       roomRes.roomProfile?.roomName ?? "",
                      //       maxLines: 1,
                      //       overflow: TextOverflow.ellipsis,
                      //       style: TextStyle(
                      //         fontSize: 15.sp,
                      //         color: Color(0xffffffff),
                      //         fontWeight: FontWeight.w400,
                      //         decoration: TextDecoration.none,
                      //       ),
                      //     ),
                    ),
                  ),
                  SizedBox(width: 5.w),
                  (res.extValues
                      ?.roomSetting
                      ?.password
                      ?.isEmpty ??
                      false)
                      ? Image.asset(
                    "sc_images/general/sc_icon_online_user.png",
                    width: 14.w,
                    height: 14.w,
                  )
                      : Image.asset(
                    "sc_images/index/sc_icon_room_suo.png",
                    width: 20.w,
                    height: 20.w,
                  ),
                  (res.extValues
                      ?.roomSetting
                      ?.password
                      ?.isEmpty ??
                      false)
                      ? SizedBox(width: 3.w)
                      : Container(height: 10.w),
                  (res.extValues
                      ?.roomSetting
                      ?.password
                      ?.isEmpty ??
                      false)
                      ? text(
                    res.extValues?.memberQuantity ?? "0",
                    fontSize: 12.sp,
                  )
                      : Container(height: 10.w),
                  SizedBox(width: 10.w),
                ],
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        Provider.of<RtcProvider>(
          context,
          listen: false,
        ).joinVoiceRoomSession(context, res.id ?? "");
      },
    );
  }
}
