import 'package:cpt_services/modules/services/history/history_vm.dart';
import 'package:cpt_services/modules/services/homeService/home_service_vm.dart';
import 'package:cpt_services/modules/services/inProgress/in_progress_vm.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/sp/sp_util.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:auto_route/auto_route.dart';
import 'package:widgets/dialog/app_custom_dialog.dart';
import 'package:widgets/my_checkbox_group.dart';

import '../../respository/services_respository.dart';
import 'services_page.dart';
import 'services_pageview_idx_data.dart';
import 'services_state.dart';

part 'services_vm.g.dart';

@riverpod
class ServicesVm extends _$ServicesVm {

  late int _parentCategoryId;

  get topSectionsData => state.topSectionsData;
  late ServicesRespository servicesRespositoryInstance;
  late Map<int, dynamic> providerMap = {};

  bool _isSingleSelect = true;
  List<Map<String, dynamic>> _currentSelectedGarageCategory = [];

  Map<int, Map<String, dynamic>> _queryParams = {};

  // 获取当前的查询参数
  getCurrentQueryParams(String key) {
    return _queryParams[state.currentPageViewIdx]?[key];
  }

  // 根据索引获取 Provider
  ProviderBase getProvider(int index) {
    return providerMap[index]!;
  }

  // 初始化 _queryParams
  queryParamsInit(){
    List<MapEntry<int, String>> servicesEntriesList = ServicesPageviewIdxData.values.entries.toList();
    servicesEntriesList.asMap().forEach((index, value) {
      _queryParams[index] = {
        'keyword': null,
        'is_liked': null,
        'page_view_idx': index,
        'page_view_name': value,
      };
    });
  }

  ServicesVmState initState() {
    return ServicesVmState(
      currentPageViewIdx: 0,
    );
  }

  @override
  ServicesVmState build(){
    // 引入数据仓库
    servicesRespositoryInstance = ref.read(servicesRespositoryProvider);
    final state = initState();
    queryParamsInit();
    setCurrentPageViewIconStatus();
    getPageViewVm();

    Log.d("-------------services vm-------------build---------------------");
    ref.onDispose((){
      providerMap = {};
      Log.d("-------------services vm-------------dispose---------------------");
    });
    return state;
  }

  setInitPageData(BuildContext context, int parentCategoryId){
    _parentCategoryId = parentCategoryId;
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      state = state.copyWith(
        parentCategoryId: parentCategoryId,
      );
    });
  }

  // 搜集pageView 对应的vm
  void getPageViewVm(){
    // 每次切换后需要重新获取 一组 pageView的 vm
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      // 存入 一组 pageView的 vm
      ServicesPageviewIdxData.values.forEach((key, value) {
        switch(key){
          case 0:
            providerMap[key] = ref.read(homeServiceVmProvider.notifier);
          case 1:
            providerMap[key] = ref.read(inProgressVmProvider.notifier);
          case 2:
          providerMap[key] = ref.read(historyVmProvider.notifier);
        }
      });
    });
  }

  // 设置当前导航栏的 图标 等状态
  void setCurrentPageViewIconStatus(){
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      Log.d("获取当前的导航栏 相关状态resMap444 ${providerMap[state.currentPageViewIdx]} ");
      Map<String, dynamic> resMap = providerMap[state.currentPageViewIdx]?.getCurrentQueryParams(null)??{};
      Log.d("获取当前的导航栏 相关状态resMap $resMap ");
      _queryParams[state.currentPageViewIdx] = resMap;
    });
  }

  tabsRouterChange(){
    // 设置当前导航栏的 图标 等状态
    Log.d("----tabsRouterChange---${tabsRouterKey.currentState?.controller?.activeIndex}-");
    state = state.copyWith(currentPageViewIdx: tabsRouterKey.currentState?.controller?.activeIndex ?? 0);

    setCurrentPageViewIconStatus();
    getPageViewVm();
  }

  handlerSwitchPageView(BuildContext? context, int pageViewIdx){
    tabsRouterKey.currentState?.controller?.setActiveIndex(pageViewIdx);
  }


  // 获取当前pageView 的vm
  getCurrentPageViewVm(int? pageViewIdx){
    if(pageViewIdx !=null){
      return providerMap[pageViewIdx];
    }else {
      return getCurrentPageViewVm(state.currentPageViewIdx);
    }
  }

  // 返回当前 pageView 页面的 vm

  // 判断当前pageview 页面正处于显示状态
  Future isCurrentPageViewShowing(int pageViewIdx) async{
    // 延迟获取结果
    bool isShowing = await Future.delayed(const Duration(milliseconds: 500), (){
      return state.currentPageViewIdx == pageViewIdx;
    });
    return isShowing;
  }

  Future<void> handlerShowChooseGarageCategoryDialog(BuildContext context, List<Map<String, dynamic>> garageCategoryList) async{
    await DialogEngine.show(
        tag: "chooseGarageSaleCategory",
        position: DialogPosition.center,
        widget: AppCustomDialog(
          message: '',
          dialogWidth: MediaQuery.of(context).size.width * 0.8,
          // contentBoxMaxHeight: 350,
          // contentBoxMinHeight: 300,
          isShowConfirmBtn: garageCategoryList!.length > 0 ? true: false,
          confirmTxt: "Ok",
          messageBuilder: (BuildContext context){
            return Container(
              color: context.appColors.textWhite,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: garageCategoryList!.length > 0 ? [
                  MyCheckboxGroup(
                      isSingleSelect: _isSingleSelect,
                      labelStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                      items: garageCategoryList!,
                      defaultSelectedItems: [],
                      onChanged: (List<Map<String, dynamic>> selectedItems){
                        Log.d("----MyCheckboxGroup onChanged  $selectedItems");
                        _currentSelectedGarageCategory = selectedItems;
                      }
                  )
                ]: [
                  Container(
                    child: CircularProgressIndicator(
                      strokeWidth: 3,
                      valueColor: AlwaysStoppedAnimation(context.appColors.textDarkGray),
                    ),
                  )
                ],
              ),
            );
          },
          isShowCancelBtn:false,
          confirmAction: (){
            // 点击了确定
            Log.d("----点击了确定按钮");
            int? categoryId;
            if(_isSingleSelect){
              if(_currentSelectedGarageCategory.length > 0){
                categoryId = _currentSelectedGarageCategory[0]['id'];
              }
            }

            providerMap[state.currentPageViewIdx]
              ..setCurrentQueryParams({
                "category_id": _queryParams?[state.currentPageViewIdx]?['categoryId'],
              })
              ..directRefresh();
          },
        )
    );
  }

  // 搜索
  handlerSearch(String value){
    Log.d("services_vm 中 搜索 value: $value");
    _queryParams?[state.currentPageViewIdx]?['keyword'] = value;
    providerMap[state.currentPageViewIdx]
      ..setCurrentQueryParams({
        "keyword": _queryParams?[state.currentPageViewIdx]?['keyword'],
      })
      ..directRefresh();
  }

  // 点击了导航栏的 like btn
  handlerClickNavbarLikeBtn(BuildContext? context){
    _queryParams[state.currentPageViewIdx]?['is_liked'] = !(_queryParams?[state.currentPageViewIdx]?['is_liked']??false);
    // 控制外层滚动和内层滚动
    handlerNestedScrollViewScroll();

    // providerMap[state.currentPageViewIdx]
    //   ..setCurrentQueryParams({
    //     "is_liked": _queryParams?[state.currentPageViewIdx]?['is_liked'],
    //   })
    //   ..directRefresh();
  }

  handlerNestedScrollViewScroll({double? outerOffset, double? innerOffset=0.0, bool? isOuterScrollAnimated=false, bool? isInnerScrollAnimated=false}){
    if(outerOffset !=null){
      if(isOuterScrollAnimated!){
        extendedNestedScrollViewKey.currentState?.outerController.animateTo(
          outerOffset,
          duration: const Duration(seconds: 1),
          curve: Curves.easeIn,
        );
      }else {
        extendedNestedScrollViewKey.currentState?.outerController.jumpTo(
          outerOffset,
        );
      }
    }

    if(innerOffset !=null){
      extendedNestedScrollViewKey.currentState?.innerPositions.forEach((position) {
        if(isInnerScrollAnimated!){
          position.animateTo(innerOffset,
              duration: Duration(seconds: 1), curve: Curves.easeIn);
        }else {
          position.jumpTo(innerOffset);
        }
      });
    }
  }
}