import 'package:cpt_community/modules/community/community_page.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:flutter/material.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/path/router_path.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:auto_route/auto_route.dart';
import 'package:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/dialog/app_custom_dialog.dart';
import 'package:widgets/app_check_box.dart';
import 'package:widgets/my_checkbox_group.dart';

import 'garage_page.dart';
import 'garage_state.dart';
import 'garage_repository.dart';

part 'garage_vm.g.dart';

@riverpod
class GarageVm extends _$GarageVm {
  late GarageRepository garageRepository;
  get topSectionsData => state.topSectionsData;
  GarageState initState() {
    return GarageState(
        activeIndex: 0,
        topSectionsData: [
          {
            "title": "News Feed",
            "icon": Assets.communityNesFeed,
            "pageStartInstanceFn": CommunityPage.startInstance,
            "page": const CommunityPage(),
          },
          {
            "title": "Garage Sale",
            "icon": Assets.communityGarageSale,
            "pageStartInstanceFn": GaragePage.startInstance,
            "page": const GaragePage(),
          },
        ],
        tabsList: [
          {
            'title': 'For Sale',
            'icon': null,
            'active': true,
            'activeTitleColor': Colors.white,
            'activeTitleFontSize': 16,
            'activeTitleBackgroundColor': ColorUtils.string2Color("#4161D0"),
          },
          {
            'title': 'For Rent',
            'icon': null,
            'active': false,
            'activeTitleColor': Colors.white,
            'activeTitleFontSize': 16,
            'activeTitleBackgroundColor': ColorUtils.string2Color("#4161D0"),
          },
        ],
        categoryList: [
          {
            'id': '1',
            'label': 'Kids',
          },
          {
            'id': '2',
            'label': 'Homeware',
          },
          {
            'id': '3',
            'label': 'Fashion',
          },
          {
            'id': '4',
            'label': 'Electronics',
          },
          {
            'id': '5',
            'label': 'Sports',
          },
          {
            'id': '6',
            'label': 'Furniture',
          },
          {
            'id': '7',
            'label': 'Others',
          },
        ],
        list: [
          {
            'id':1,
            'avator': Assets.communityCamera,
            'title': '发动机上课士大夫',
            'isFollow': false,
            'content': '经典福克斯附件是的开飞机迪斯科封禁端口是否建立四道口附近 ……[More]',
            'imageUrls': [],
            'time': 'June 17,2016 at 7:23 p.m.',
            'isLike': true,
            'likeno': 12
          },
          {
            'id':2,
            'avator': Assets.communityCamera,
            'title': '分等级付给的积分多少',
            'isFollow': true,
            'content': 'She said YES and our lives changed.Thank you all for coming to my propose today.We hope everyone can ……[More]',
            'imageUrls': ['https://img.alicdn.com/tfs/TB1h.o9O4MPMeJjy1XaXXcSsFXa-640-360.jpg','https://img.alicdn.com/tfs/TB1h.o9O4MPMeJjy1XaXXcSsFXa-640-360.jpg','https://img.alicdn.com/tfs/TB1h.o9O4MPMeJjy1XaXXcSsFXa-640-360.jpg'],
            'time': 'June 17,2016 at 7:23 p.m.',
            'isLike': true,
            'likeno': 12
          },
        ]
    );
  }
  @override
  GarageState build(){
    // 引入数据仓库
    garageRepository = ref.read(garageRepositoryProvider);
    // 初始化状态
    GarageState state = initState();
    return state;
  }

  // 上拉加载
  Future onLoadData() async {
    Log.d("----garage_vm-----initListData");
    // await Future.delayed(const Duration(seconds: 2));
    // if(state.list.length >= state.filterCount){
    //   return;
    // }else {
    //   int curPage = state.curPage + 1;
    //   state = state.copyWith(curPage: curPage,);
    //   getListData();
    // }
    // getListData();
  }

  // 获取list 列表数据
  void getListData<T>() async {
    Log.d("加载listData数据---------------start-----");
    try {
      //请求网络
      Map<String, dynamic>  params = {
        "curPage": state.curPage,
        "pageSize": state.pageSize,
      };
      Log.d("请求参数------$params");
      final result = await garageRepository.fetchGarageList(params);
      Log.d("请求完成结果------${result.data}");
      //校验成功失败
      if (result.isSuccess) {
        // state = state.copyWith(serverTime: result.data);
        state = state;
        ToastEngine.show("获取数据成功");
      } else {
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      ToastEngine.show("Error: $e");
    }
  }


  // 下拉刷新
  Future refreshListData() async {
    Log.d("----garage_vm-----refreshListData ");

    // await Future.delayed(const Duration(seconds: 2));

    state = state.copyWith(curPage: 1, pageSize: 10);
    // ref.invalidateSelf();
    // ref.invalidate(garageVmProvider);
    getListData();

  }

  // 选择 category
  handlerChooseCategory(BuildContext context) async {
    await DialogEngine.show(
      tag: "choosegaragesalecategory",
      position: DialogPosition.center,
      widget: AppCustomDialog(
        message: '',
        confirmTxt: "Ok",
        messageBuilder: (BuildContext context){
          return Container(
            // width: 500,
            height: 400,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                MyCheckboxGroup(
                  isSingleSelect: false,
                    labelStyle: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                  items: state.categoryList,
                  onChanged: (List<Map<String, dynamic>> selectedItems){
                    Log.d("----MyCheckboxGroup onChanged  $selectedItems");
                  }
                )
              ],
            ),
          );
        },
        isShowCancelBtn:false,
        confirmAction: (){

        },
      )
    );
  }

  // 切换tab
  handlerChangeTab(int index, tabsRouter) {
    tabsRouter.setActiveIndex(index);
    // state = state.copyWith(tabsRouter: tabsRouter ,activeTabIdx: index);
    Log.d("garage_vm handlerChangeTab--index:    $index");
  }


  // 点击发布的按钮 跳转到发布的页面
  void handlerGotoPost(context){
    // ComponentServiceManager().communityService.startCommunityPage();
    AutoRouter.of(context).pushNamed(RouterPath.garageSalePost);
  }


  handlerChangeCommunityType(context, int index){
    if(index == 0){
      // 返回到 newsfeed 页面
      Navigator.pop(context);
    }
  }

}