import 'package:cpt_property/modules/property/page/property_page.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.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/util.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_load_image.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());
    }
  }

  Widget _buildItemLeftSection(BuildContext context,WidgetRef ref, item, _vm) {
    return Container(
      // color: Colors.blue,
      width: 100,
      // height: 117.5,
      child: Center(
        child: MyLoadImage(
          item['pic'],
          placeholderPath: Assets.propertyNewsItemBg,
          width: 60.5,
          height: 50.5,
        ),
      )
    ).marginOnly(right: 17.5).constrained(
      minHeight: 117.5,
    );
  }

  Widget _buildItemRightSection(BuildContext context,WidgetRef ref, item, _vm) {

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

    return Container(
      color: Colors.white,
      padding: const EdgeInsets.only(left:5, top: 10.5, bottom: 10.5),
      child: Container(
        child: Stack(
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        item['title'],
                        maxLines: 2, // 设置最大行数为2
                        overflow: TextOverflow.ellipsis, // 超出部分用省略号表示
                        style: const TextStyle(fontSize: 16.0, color: Colors.black, fontWeight: FontWeight.w400), // 设置字体大小
                      ),
                    )
                  ],
                ),
                const SizedBox(height: 10.5),
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        item['description'],
                        maxLines: 2, // 设置最大行数为2
                        overflow: TextOverflow.ellipsis, // 超出部分用省略号表示
                        style: const TextStyle(fontSize: 12.0, color: Colors.black), // 设置字体大小
                      ),
                    )
                  ]
                ),
                const SizedBox(height: 12.5),
                Row(
                    children: [
                      Expanded(
                        child: Text(
                          Utils.getTimeAgo(item['time']),
                          maxLines: 1, // 设置最大行数为2
                          overflow: TextOverflow.ellipsis, // 超出部分用省略号表示
                          style: const TextStyle(fontSize: 12.0, color: Colors.black), // 设置字体大小
                        ),
                      )
                    ]
                ),
              ],
            ),
            Positioned(
              right: 5,
              bottom: 0,
              child: MyAssetImage(isCollection? Assets.propertyCollectionActive:Assets.propertyCollection,width:22,height: 20.5,).onTap((){
                Log.d("点击了收藏按钮");
                _vm.handlerCollection(item, isCollection);
              }),
            ),
          ],
        ).constrained(
          minHeight: 96.5,
        ),
      ),
    );
  }

  // 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),
          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,
        ),
      ],
    ).onTap((){
      // 去详情
      _vm.goNewsDetail(item);
    });
  }

  // list
  Widget _buildNewsList(BuildContext context, WidgetRef ref, _vm) {
    // List items = List.generate(20, (index) => "Item $index");
    // List items = _vm.state.list.fromJson();
    List itemsList = _vm.state.list.toList();
    return ListView.builder(
      itemCount: itemsList.length,
      itemBuilder: (context, index) {
        return _buildNewsItem(context, ref, itemsList[index], _vm);
      },
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final _vm = ref.read(propertyNewsVmProvider.notifier);

    return Scaffold(
      // appBar: AppBar(title: Text("资产")),
      body: Container(
        child: EasyRefresh(
          // 上拉加载
          onLoad: () async{
            Log.d("----onLoad");
            _vm.onLoadData();
          },
          // 下拉刷新
          onRefresh: () async{
            Log.d("----onRefresh");
            _vm.refreshListData();
          },
          child: _buildNewsList(context, ref, _vm),
        )
      ),
    );
  }
}
