import 'package:cpt_rewards/modules/rewards_transaction/rewards_transaction_page.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';
import 'package:cs_resources/generated/assets.dart';

import '../../../router/page/rewards_page_router.dart';
import './rewards_my_used_vm.dart';

@RoutePage()
class RewardsMyUsedPage extends HookConsumerWidget {
  const RewardsMyUsedPage({Key? key}) : super(key: key);

  //启动当前页面
  static void startInstance({BuildContext? context}) {
    if (context != null) {
      context.router.push(const RewardsMyUsedPageRoute());
    } else {
      appRouter.push(const RewardsMyUsedPageRoute());
    }
  }

  Widget _buildItemLeftSection(BuildContext context, WidgetRef ref, item, _vm) {
    int point = item['reward']['point'] ?? 0;
    int originalPoint = item['reward']['original_point'] ?? 0;
    String title = item['reward']['title'] ?? '';
    String img = item['reward']['resources'][0] ?? '';
    int id = item['id'];
    String redeemedStart = item['reward']['redeemed_start'] ?? "";
    String redeemedEnd = item['reward']['redeemed_end'] ?? "";
    String redeemedDate = '$redeemedStart-$redeemedEnd';
    String usedAt = item['used_at'] ?? "";
    return Column(
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              maxLines: 1, // 设置最大行数为2
              overflow: TextOverflow.ellipsis, // 超出部分用省略号表示
              title,
              style: TextStyle(fontSize: 16.0, color: context.appColors.textBlack, fontWeight: FontWeight.w500),
            ),

            Row(
              children: [
                Text(
                  '$point',
                  style: TextStyle(fontSize: 19.0, color: context.appColors.textBlack, fontWeight: FontWeight.w500),
                ),
                Text(
                  '$originalPoint',
                  style: TextStyle(
                      decoration: TextDecoration.lineThrough,
                      decorationColor: context.appColors.textBlack,
                      decorationStyle: TextDecorationStyle.solid,
                      fontSize: 12.0,
                      color: context.appColors.textBlack,
                      fontWeight: FontWeight.w400),
                ).marginOnly(left: 5, right: 5),
                Text(
                  S.current.points,
                  style: TextStyle(fontSize: 13.0, color: context.appColors.textBlack, fontWeight: FontWeight.w400),
                ),
              ],
            ).marginOnly(top: 2),

            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                     MyAssetImage(
                      Assets.rewardsRewardsIconDatd,
                      width: 15,
                      height: 15,
                      color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
                    ),
                    Text(
                      '${S.current.redeem_from}:',
                      style: TextStyle(fontSize: 13.0, color: context.appColors.textBlack, fontWeight: FontWeight.w400),
                    ).marginOnly(left: 6)
                  ],
                ),
                Text(
                  '$redeemedDate',
                  style: TextStyle(fontSize: 13.0, color: context.appColors.textBlack, fontWeight: FontWeight.w400),
                )
              ],
            ).marginOnly(top: 6),

            Row(
              children: [
                 MyAssetImage(
                  Assets.rewardsRewardsIconDraw,
                  width: 15,
                  height: 15,
                  color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
                ),
                Text(
                  '${S.current.redeem_deal_at}: $usedAt',
                  style: TextStyle(fontSize: 13.0, color: context.appColors.textBlack, fontWeight: FontWeight.w400),
                ).marginOnly(left: 6)
              ],
            ).marginOnly(top: 6),

            Container(
                height: 43,
                decoration: BoxDecoration(
                  color: context.appColors.btnBgDefaultDark,
                  borderRadius: BorderRadius.circular(8), // 圆角
                ),
                child: Container(
                        alignment: Alignment.center,
                        child: Text(
                          S.current.view,
                          style: const TextStyle(fontSize: 15.0, color: Colors.white, fontWeight: FontWeight.w500),
                        ))).marginOnly(top: 10, bottom: 5).onTap(() {
              RewardsTransactionPage.startInstance(id: id);
            }),
          ],
        ),
        MyLoadImage(
          img,
          width: MediaQuery.of(context).size.width,
          height: 133,
        ),
      ],
    ).paddingOnly(top: 20).onTap(() {
      // 去详情
      RewardsTransactionPage.startInstance(id: id);
    });
  }

  // listitem
  Widget _buildSaleItem(BuildContext context, WidgetRef ref, item, _vm) {
    return Container(
      decoration: BoxDecoration(
        color: context.appColors.whiteBG,
        borderRadius: const BorderRadius.all(Radius.circular(6.0)),
        boxShadow: [BoxShadow(color: context.appColors.itemBGShadow)],
      ),
      child: Column(
        children: [
          SizedBox(
            width: MediaQuery.of(context).size.width - 30,
            height: 320,
            // margin: const EdgeInsets.only(left: 15, right: 15, top: 12.5),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                _buildItemLeftSection(context, ref, item, _vm)
                // .marginOnly(bottom: 5),
              ],
            ).paddingOnly(left: 20, right: 20),
          ).constrained(
            minHeight: 320,
          ),
        ],
      ),
    ).marginOnly(left: 15, bottom: 15, right: 15);
  }

  // list
  Widget _buildSaleList(BuildContext context, WidgetRef ref, _vm) {
    final state = ref.watch(rewardsMyUsedVmProvider);
    return SliverList(
        delegate: SliverChildBuilderDelegate((context, index) {
      return _buildSaleItem(context, ref, state.list![index], _vm);
    }, childCount: state.list!.length));
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.read(rewardsMyUsedVmProvider.notifier);
    final state = ref.watch(rewardsMyUsedVmProvider);
    useEffect(() {
      // 组件挂载时执行 - 执行接口请求
      Future.microtask(() => vm.initPageData());
      return () {
        // 组件卸载时执行
        Log.d("property_news_page 组件卸载时执行");
      };
    }, []);
    return Scaffold(
      // appBar: AppBar(title: Text("资产")),
      body: SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: EasyRefresh(
              controller: vm.refreshController,
              // 上拉加载
              onLoad: () async {
                Log.d("----onLoad");
                vm.loadMore();
              },
              // 下拉刷新
              onRefresh: () async {
                Log.d("----onRefresh");
                vm.onRefresh();
              },
              child: Container(
                color: context.appColors.backgroundDark,
                padding: const EdgeInsets.only(top: 15),
                child: LoadStateLayout(
                  state: state.loadingState,
                  errorMessage: state.errorMessage,
                  errorRetry: () {
                    vm.retryRequest();
                  },
                  successSliverWidget: [_buildSaleList(context, ref, vm)],
                ),
              ))),
    );
  }
}
