
import 'package:cpt_property/modules/property/page/property_page.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/color_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.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/my_text_view.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/property_page_router.dart';
import '../vm/property_news_vm.dart';

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

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

  static double cardHeight = 117.5 + 20;
  static double cardLeftWidth = 125;

  Widget _buildItemLeftSection(BuildContext context,WidgetRef ref, item, vm) {
    // final imageHeight = item['pic']!.isNotEmpty? cardHeight : cardHeight;
    return Container(
        height: cardHeight,
        width: cardLeftWidth,
        decoration: BoxDecoration(
          color: ColorUtils.string2Color('#F2F3F6'),
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(8),
            bottomLeft: Radius.circular(8),
          ),
        ),
        child: Center(
          child: MyLoadImage(
            item['cover_image'],
            placeholderPath: Assets.propertyNewsItemBg,
            height: item['cover_image']!.isNotEmpty? cardHeight : 60.5,
            width: item['cover_image']!.isNotEmpty? cardLeftWidth : 60.5,
            fit: BoxFit.cover,
            // fit: BoxFit.contain,
            cornerRadius: 8,
          ),
        )
    );
  }

  Widget _buildItemRightSection(BuildContext context,WidgetRef ref, item, vm) {
    // 使用 ref.select 监听 list 中 item 的 Map 对象中的 liked 字段
    final liked = ref.watch(propertyNewsVmProvider.select((state) {
      final curItem = state.list!.firstWhere(
            (valueItem) => valueItem['id'] == item['id'],
        orElse: () => {'liked': false},
      );
      return curItem['liked'] as bool;
    }));

    return Container(
      padding: const EdgeInsets.only(left:17.5,right: 17.5,top: 13, bottom: 13),
      decoration: BoxDecoration(
        color: context.appColors.backgroundWhite,
        borderRadius: const BorderRadius.only(
          topRight: Radius.circular(8),
          bottomRight: Radius.circular(8),
        ),
      ),
      child: Stack(
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(
                    child: MyTextView(
                      item['title'],
                      maxLines: 2, // 设置最大行数为2
                      isTextEllipsis: true, // 超出部分用省略号表示
                      fontSize: 16,
                      textColor: context.appColors.textBlack,
                      isFontMedium: true,
                    ),
                  )
                ],
              ),
              const SizedBox(height: 10.5),
              Row(
                children: [
                  Expanded(
                    child: MyTextView(
                      item['content'],
                      maxLines: 2, // 设置最大行数为2
                      isTextEllipsis: true, // 超出部分用省略号表示
                      fontSize: 12,
                      textColor: context.appColors.textBlack,
                      isFontRegular: true,
                    )
                  )
                ]
              ),
              const SizedBox(height: 12.5),
              Row(
                  children: [
                    Expanded(
                      child: MyTextView(
                        Utils.getTimeAgo(item['created_at'], format: "dd MMM yyyy 'at' hh:mm a"),
                        maxLines: 1, // 设置最大行数为1
                        isTextEllipsis: true, // 超出部分用省略号表示
                        fontSize: 12,
                        textColor: context.appColors.textBlack,
                        isFontRegular: true,
                      ),
                    )
                  ]
              ),
            ],
          ),
          Positioned(
            right: 5,
            bottom: 0,
            child: MyAssetImage(liked? Assets.propertyCollectionActive:Assets.propertyCollection,width:22.5,height: 21,).onTap((){
              Log.d("点击了收藏按钮");
              vm.handlerCollection(item, liked);
            }),
          ),
        ],
      ),
    ).constrained(
      minHeight: cardHeight
    );
  }

  // listitem
  Widget _buildNewsItem(BuildContext context,WidgetRef ref, item, vm) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisSize: MainAxisSize.max,
      children: [
        Container(
          width: MediaQuery.of(context).size.width - 30,
          margin: const EdgeInsets.only(left: 15,right: 15,top: 12.5),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            boxShadow: [
              BoxShadow(
                color: ColorUtils.string2Color('#000000').withOpacity(0.05),
                offset: const Offset(0, 0),
                blurRadius: 10,
                spreadRadius: 0,
              ),
            ]
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildItemLeftSection(context, ref, item, vm),
              Expanded(child: _buildItemRightSection(context, ref, item, vm)),
            ],
          ),
        ).constrained(
          minHeight: 117.5,
        ),
      ],
    );
  }


  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.read(propertyNewsVmProvider.notifier);
    final state = ref.watch(propertyNewsVmProvider);
    useEffect(() {
      // 组件挂载时执行 - 执行接口请求
      Future.microtask(() => vm.initPageData());
      return () {
        // 组件卸载时执行
        Log.d("property_news_page 组件卸载时执行");
      };
    }, []);

    return Scaffold(
      // appBar: AppBar(title: Text("资产")),
      backgroundColor: DarkThemeUtil.multiColors(context, ColorUtils.string2Color("#F2F3F6"), darkColor: Colors.black),
      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: LoadStateLayout(
            state: state.loadingState,
            errorMessage: state.errorMessage,
            errorRetry: () {
              vm.retryRequest();
            },
            successSliverWidget: [
                SliverList(
                  delegate: SliverChildBuilderDelegate(
                        (context, index){
                          return _buildNewsItem(context, ref, state.list![index], vm).onTap((){
                            Log.d("点击了item");
                            vm.goNewsDetailPage(context, state.list![index]['id']);
                          });
                        },
                    childCount: state.list!.length
                  )
                )
            ],
          ),
        ).marginOnly(top: 5, bottom: 5)
      ),
    );
  }
}
