
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:yumi/ui_kit/components/sc_debounce_widget.dart';
import 'package:provider/provider.dart';

import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';
import 'package:yumi/ui_kit/components/sc_page_list.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/ui_kit/components/sc_tts.dart';
import 'package:yumi/ui_kit/theme/socialchat_theme.dart';
import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_store_repository_imp.dart';
import 'package:yumi/shared/business_logic/models/res/store_list_res.dart';
import 'package:yumi/services/auth/user_profile_manager.dart';
import 'package:yumi/ui_kit/widgets/store/props_store_theme_detail_dialog.dart';
import 'package:yumi/modules/store/headdress/store_headdress_page.dart';

import '../../../shared/data_sources/models/enum/sc_currency_type.dart';
import '../../../shared/data_sources/models/enum/sc_props_type.dart';

///房间主题
class StoreThemePage extends SCPageList {

  StoreThemePage();

  @override
  _StoreThemePagePageState createState() => _StoreThemePagePageState();
}

class _StoreThemePagePageState
    extends SCPageListState<StoreListResBean, StoreThemePage> {


  //折扣
  double disCount = 1;

  @override
  void initState() {
    super.initState();
    enablePullUp = false;
    isGridView = true;
    gridViewCount = 3;
    padding = EdgeInsets.symmetric(horizontal: 6.w);
    backgroundColor = Colors.transparent;
    gridDelegate = SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: gridViewCount,
      mainAxisSpacing: 12.w,
      crossAxisSpacing: 12.w,
      childAspectRatio: 0.78,
    );
    loadData(1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: buildList(context),
    );
  }

  @override
  Widget buildItem(StoreListResBean res) {
    return GestureDetector(
      child: Container(
        decoration: BoxDecoration(
          color:
          res.isSelecte
              ? Color(0xff18F2B1).withOpacity(0.1)
              : SCGlobalConfig.businessLogicStrategy
              .getStoreItemBackgroundColor(),
          border: Border.all(
            color:
            res.isSelecte
                ? SCGlobalConfig.businessLogicStrategy
                .getStoreItemSelectedBorderColor()
                : SCGlobalConfig.businessLogicStrategy
                .getStoreItemUnselectedBorderColor(),
            width: 1.w,
          ),
          borderRadius: BorderRadius.all(Radius.circular(8.w)),
        ),
        child: Stack(
          children: [
            Column(
              children: [
                SizedBox(height: 10.w),
                netImage(
                  url: res.res.propsResources?.cover ?? "",
                  width: 55.w,
                  height: 55.w,
                  borderRadius: BorderRadius.all(Radius.circular(8.w)),
                ),
                SizedBox(height: 3.w),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    text(
                      res.res.propsResources?.name ?? "",
                      textColor: Colors.white,
                      fontSize: 11.sp,
                    ),
                  ],
                ),
                SizedBox(height: 3.w),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SizedBox(width: 10.w),
                    Expanded(
                      child: Text.rich(
                        textAlign: TextAlign.center,
                        TextSpan(
                          children: [
                            WidgetSpan(
                              alignment: PlaceholderAlignment.middle,
                              child: Image.asset(
                                SCGlobalConfig.businessLogicStrategy.getStoreItemGoldIcon(),
                                width: 22.w,
                              ),
                            ),
                            TextSpan(text: "  "),
                            disCount < 1
                                ? TextSpan(
                                  text: "${res.res.propsPrices![0].amount}",
                                  style: TextStyle(
                                    fontSize: 12.sp,
                                    color: SCGlobalConfig.businessLogicStrategy.getStoreItemPriceTextColor(),
                                    fontWeight: FontWeight.w600,
                                    decoration: TextDecoration.lineThrough,
                                  ),
                                )
                                : TextSpan(),
                            disCount < 1 ? TextSpan(text: "  ") : TextSpan(),
                            TextSpan(
                              text:
                                  "${((res.res.propsPrices![0].amount ?? 0) * disCount).toInt()}/${res.res.propsPrices![0].days} ${SCAppLocalizations.of(context)!.day}",
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: SCGlobalConfig.businessLogicStrategy.getStoreItemPriceTextColor(),
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                        strutStyle: StrutStyle(
                          height: 1.3, // 行高倍数
                          fontWeight: FontWeight.w500,
                          forceStrutHeight: true, // 强制应用行高
                        ),
                      ),
                    ),
                    SizedBox(width: 10.w),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
      onTap: () {
        _selectItem(res);
        _showDetail(res.res);
      },
    );
  }

  void _showDetail(StoreListRes res) {
    SmartDialog.show(
      tag: "showPropsDetail",
      alignment: Alignment.bottomCenter,
      animationType: SmartAnimationType.fade,
      builder: (_) {
        return PropsStoreThemeDetailDialog(res, disCount);
      },
    );
  }


  ///加载数据
  @override
  loadPage({
    required int page,
    required Function(List<StoreListResBean>) onSuccess,
    Function? onErr,
  }) async {
    try {
      List<StoreListResBean> beans = [];
      var storeList = await SCStoreRepositoryImp().storeList(
        SCCurrencyType.GOLD.name,
        SCPropsType.THEME.name,
      );
      for (var value in storeList) {
        beans.add(StoreListResBean(value, false));
      }
      onSuccess(beans);
    } catch (e) {
      if (onErr != null) {
        onErr();
      }
    }
  }

  void _selectItem(StoreListResBean res) {
    for (var value in items) {
      value.isSelecte = false;
    }
    res.isSelecte = true;
    setState(() {});
  }

  void _buy(StoreListResBean res) {
    num days = 0;
    if (res.res.propsPrices!.length > 1) {
      days = res.res.propsPrices![1].days ?? 0;
    } else {
      days = res.res.propsPrices![0].days ?? 0;
    }
    SCStoreRepositoryImp()
        .storePurchasing(
          res.res.id ?? "",
          SCPropsType.THEME.name,
          SCCurrencyType.GOLD.name,
          "$days",
        )
        .then((value) {
          SCTts.show(SCAppLocalizations.of(context)!.purchaseIsSuccessful);
          Provider.of<SocialChatUserProfileManager>(
            context,
            listen: false,
          ).updateBalance(value);
        });
  }
}
