import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:huixiang/main.dart';
import 'package:huixiang/retrofit/data/activity.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:keframe/frame_separate_widget.dart';
import 'package:keframe/size_cache_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class ActivityListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ActivityListPage();
  }
}

class _ActivityListPage extends State<ActivityListPage>
    with AutomaticKeepAliveClientMixin {
  ApiService apiService;

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

    eventBus.on<EventType>().listen((event) {
      if (event.type < 3) {
        setState(() {});
      }
    });
  }

  List<Activity> activityList;

  queryActivity() async {
    final SharedPreferences value = await SharedPreferences.getInstance();
    apiService =
        ApiService(Dio(), context: context, token: value.getString('token'));
    BaseData<PageInfo<Activity>> baseData = await apiService.informationList({
      "pageNum": 1,
      "pageSize": 10,
      "searchKey": "",
      "type": 1,
      "state": 1
    }).catchError((error) {
      _refreshController.refreshFailed();
    });
    if (baseData != null && baseData.isSuccess) {
      _refreshController.refreshCompleted();
      activityList = baseData.data.list;
    }
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
  }

  RefreshController _refreshController = RefreshController();

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      child: FutureBuilder(
        future: queryActivity(),
        builder: (context, snapshot) {
          return SizeCacheWidget(
            child: SmartRefresher(
              controller: _refreshController,
              enablePullDown: true,
              enablePullUp: false,
              header: MyHeader(),
              physics: BouncingScrollPhysics(),
              onRefresh: () {
                setState(() {});
              },
              child: ListView.builder(
                itemCount: activityList == null ? 0 : activityList.length,
                physics: NeverScrollableScrollPhysics(),
                itemBuilder: (context, position) {
                  return InkWell(
                    onTap: () {
                      Navigator.of(context).pushNamed(
                          '/router/web_page',
                          arguments: {"activityId": activityList[position].id});
                    },
                    child: FrameSeparateWidget(
                      child: activityItem(activityList[position]),
                      placeHolder: AspectRatio(
                        aspectRatio: 1.34,
                        child: Container(
                          margin: EdgeInsets.symmetric(
                              horizontal: 16.w, vertical: 8.h),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withAlpha(12),
                                offset: Offset(0, 3),
                                blurRadius: 14,
                                spreadRadius: 0,
                              )
                            ],
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
          );
        },
      ),
    );
  }

  Widget activityItem(Activity activity) {
    return Container(
      margin: EdgeInsets.only(
        left: 16.w,
        right: 16.w,
        top: 8.h,
        bottom: 12.h,
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withAlpha(12),
            offset: Offset(0, 3),
            blurRadius: 14,
            spreadRadius: 0,
          )
        ],
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          MImage(
            activity.coverImg,
            aspectRatio: 2.1,
            radius: BorderRadius.only(
              topLeft: Radius.circular(8),
              topRight: Radius.circular(8),
            ),
            fit: BoxFit.cover,
            errorSrc: "assets/image/default_2_1.webp",
            fadeSrc: "assets/image/default_2_1.webp",
          ),
          Container(
            padding: EdgeInsets.only(
              left: 16.w,
              right: 16.w,
              top: 8.h,
              bottom: 12.h,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  activity.mainTitle,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontWeight: MyFontWeight.medium,
                    fontSize: 14.sp,
                    color: Colors.black,
                  ),
                ),
                SizedBox(
                  height: 4.h,
                ),
                Text(
                  activity.viceTitle ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 10.sp,
                    fontWeight: MyFontWeight.regular,
                    color: Color(0xFF4C4C4C),
                  ),
                ),
                SizedBox(
                  height: 12.h,
                ),
                ConstrainedBox(
                  constraints: BoxConstraints(
                    maxWidth: double.infinity,
                    minWidth: double.infinity,
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        activity.storeName == null ? "" : activity.storeName,
                        style: TextStyle(
                          color: Color(0xFF060606),
                          fontWeight: MyFontWeight.regular,
                          fontSize: 12.sp,
                        ),
                      ),
                      Row(
                        // crossAxisAlignment: CrossAxisAlignment.end,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            activity.startTime.split(" ")[0],
                            style: TextStyle(
                              color: Color(0xFFB5B5B5),
                              fontSize: 12.sp,
                              fontWeight: MyFontWeight.regular,
                            ),
                          ),
                          SizedBox(
                            width: 4.w,
                          ),
                          Text(
                            activity.startTime.split(" ")[1],
                            style: TextStyle(
                              color: Color(0xFFB5B5B5),
                              fontSize: 12.sp,
                              fontWeight: MyFontWeight.regular,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}