
import 'package:cpt_services/components/chooseAirConditionContent_vm.dart';
import 'package:cpt_services/components/chooseHouseCleanContent_vm.dart';
import 'package:cpt_services/components/chooseVisitTimeContent.dart';
import 'package:cpt_services/components/chooseVisitTimeContent_vm.dart';
import 'package:cpt_services/components/chooseVisitTimeTitle.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:domain/entity/garage_sale_rent_entity.dart';
import 'package:domain/entity/newsfeed_detail_entity.dart';
import 'package:domain/entity/paid_service_detail_entity.dart';
import 'package:domain/entity/paid_service_pay_success_info_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/loading/loading_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/componentRouter/component_service_manager.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/ext_dart.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/dialog/dialog_content_wrap.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import '../../../components/chooseAirConditionContent_state.dart';
import '../../../components/chooseHouseCleanContent.dart';
import '../../../components/chooseHouseCleanContent_state.dart';
import '../../../components/chooseHouseCleanTitle.dart';
import '../../../components/chooseVisitTimeBottomFooter.dart';
import '../../../constants_services.dart';
import '../../../respository/services_respository.dart';
import '../../../router/page/services_page_router.dart';
import '../clean_order_detail/clean_order_detail_page.dart';
import '../service_clean_detail/service_clean_detail_vm.dart';
import '../service_pay_success/service_pay_success_page.dart';
import 'service_order_confirm_state.dart';

part 'service_order_confirm_vm.g.dart';


final _chooseVisitTimeDialogGlobalKey = GlobalKey<DialogContentWrapState>();

@riverpod
class ServiceOrderConfirmVm extends _$ServiceOrderConfirmVm {
  late ServicesRespository servicesRespositoryInstance;
  bool _needShowPlaceholder = false; //是否展示LoadingView
  int _page = 1;  // 当前页
  int _limit = 10; // 每页数量
  int _count = 0; // 总条数

  int? _id;
  int? _cleanServiceTypeId;

  // Refresh 控制器
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true,  //允许刷新
    controlFinishLoad: true,   //允许加载
  );



  ServiceOrderConfirmState initState(PaidServiceDetailEntity detailEntity) {
    return ServiceOrderConfirmState(
      datas: detailEntity
    );
  }

  @override
  ServiceOrderConfirmState build(){
    // 引入数据仓库
    servicesRespositoryInstance = ref.read(servicesRespositoryProvider);
    final serviceDetailVm = ref.read(serviceCleanDetailVmProvider.notifier);
    PaidServiceDetailEntity detailEntity = serviceDetailVm.state.datas!;
    final state = initState(detailEntity);
    Log.d("--------------------------build---------------------");

    return state;
  }


  //刷新页面状态
  void changeLoadingState(LoadState loadState, String? errorMsg) {
    state = state.copyWith(
        loadingState: loadState,
        errorMessage: errorMsg
    );
  }


  setInitPageData({required int id, int? cleanServiceTypeId}){
    _id = id;
    _cleanServiceTypeId = cleanServiceTypeId;
  }
  // 初始化页面数据
  initPageData(BuildContext context) {
    Log.d("--------------------------initPageData---------------------");
    changeLoadingState(LoadState.State_Success, null);

    WidgetsBinding.instance.addPostFrameCallback((_){
      // 设置/更新 totalPrice
      setConfirmOrderTotalPrice(context);
    });
  }

  // 上拉加载 更多
  Future loadMore() async {
    _page++;
  }


  // 下拉刷新
  Future onRefresh() async {
    // 当前pageView 页面正处于显示状态
    // await Future.delayed(const Duration(seconds: 2));
    _page = 1;
  }


  // 手动进行刷新
  Future triggerRefresh() async {
    Log.d("trggerRefresh");
    refreshController.callRefresh();
  }

  // 手动进行刷新
  Future directRefresh() async {
    state = state.copyWith(datas:null);
    // 注意：由于 nestedscrollview 嵌套easyfresh 组件  refreshController.callRefresh() 自动刷新只能滚动顶部但是不会触发下拉刷新，这里调用是 用到了将其滚动到顶部的作用，进而刷新操作主动掉接口
    // https://github.com/xuelongqy/flutter_easy_refresh/issues/692
    refreshController.callRefresh();
    refreshController.resetFooter();
    _page = 1;
    _needShowPlaceholder = true;
  }


  // 重试请求
  Future retryRequest() async {
    _page = 1;
    _needShowPlaceholder = true;
  }



  handlerResultData(bool isList, {List<Map<String, dynamic>>? list, dynamic? data}){
    Future.delayed(const Duration(seconds: 1)).then((value) {
      if(isList){
        // list 数据模式
        // if(list != null && list.isNotEmpty){
        //   if(_page == 1){
        //     state.list.clear();
        //     state.list!.addAll(list);
        //     refreshController.finishRefresh();
        //     changeLoadingState(LoadState.State_Success, null);
        //   }else {
        //     final allList = state.list;
        //     allList!.addAll(list);
        //     state = state.copyWith(list: allList);
        //     refreshController.finishLoad();
        //   }
        // }else {
        //   if(_page == 1){
        //     state.list.clear();
        //     changeLoadingState(LoadState.State_Empty, null);
        //     refreshController.finishRefresh();
        //   }else {
        //     refreshController.finishLoad(IndicatorResult.noMore);
        //   }
        // }
      }else {
        // 单个数据模式
        if(data!=null){
          if(_page == 1){
            refreshController.finishRefresh();
          }else{
            refreshController.finishLoad();
          }
          changeLoadingState(LoadState.State_Success, null);
        }else {
          if(_page == 1){
            refreshController.finishRefresh();
          }else{
            refreshController.finishLoad();
          }
          changeLoadingState(LoadState.State_Empty, null);
        }
      }
    });
  }

  // 点击预约时间
  handlerClickVisitTime(BuildContext context){
    handlerShowChooseVisitTimeDialog(context);
  }

  // 显示 预约时间弹框
  handlerShowChooseVisitTimeDialog(BuildContext context) async{
    // 每次点击 预约时间按钮，需要 清空 confirm 页面的 extraCost
    // 定时器
    LoadState dialogState = LoadState.State_Success;
    DialogEngine.show(
        tag: "chooseVisitTimeDialog",
        position: DialogPosition.bottom,
        clickMaskDismiss:false,
        onDismiss: (){
          Log.d("--------------------------dismissDialog---------------------");
          // 弹框消失
          // _chooseVisitTimeDialogGlobalKey.currentState?.dismissDialog();
        },
        widget: DialogContentWrap(
          key: _chooseVisitTimeDialogGlobalKey,
          loadingState: dialogState,
          maxHeight: 450.0,
          dialogWidth: context.screenSize.width,
          isShowConfirmBtn: false,
          isShowCancelBtn: false,
          closeIconColor: context.appColors.textPrimary,
          title: "",
          bottomBtnRadius:0,
          bottomBtnSpace: 0,
          topLeftRadius: 20.0,
          topRightRadius: 20.0,
          // bottomBtnSectionPadding: EdgeInsets.only(left: 20, right: 20, bottom: 20,top: 20),
          yesBtnBg: context.appColors.redDefault,
          noBtnBg: context.appColors.grayBgE9,
          confirmTxt: S.current.confirm,
          cancelTxt: S.current.cancel,
          // yesBtnTextStyle: TextStyle(
          //   color: context.appColors.textWhite,
          //   fontSize: 17,
          //   fontWeight: FontWeight.w400
          // ),
          // noBtnTextStyle: TextStyle(
          //   color: context.appColors.textBlack,
          //   fontSize: 17,
          //   fontWeight: FontWeight.w400
          // ),
          confirmAction: chooseVisitTimeConfirmFn,
          cancelAction: chooseVisitTimeCancelFn,
            closeAction: chooseVisitTimeCloseFn,
          titleBuilder: (context) {
            return buildChooseVisitTimeTitle(context);
          },
          messageBuilder: (context) {
            return buildChooseVisitTimeContent(context);
          },
          bottomFooterBuilder: (context){
            return  buildChooseVisitTimeBottomFooter(context);
          },
        )
    );
  }

  // 修改 _chooseVisitTimeDialogGlobalKey 弹框的 loading状态
  changeDialogLoadingState(LoadState state){
    _chooseVisitTimeDialogGlobalKey.currentState?.changeDialogLoadingState(LoadState.State_Success);
  }

  chooseVisitTimeConfirmFn(){
    Log.d("预约时间 点击了确定");
    // 跳转到 订单确认页面
    // appRouter.push(ServiceOrderConfirmPageRoute(id: _id, cleanServiceTypeId: _cleanServiceTypeId));
  }

  chooseVisitTimeCancelFn(){
    Log.d("点击了取消");
  }

  chooseVisitTimeCloseFn(){
    Log.d("点击了右上方关闭");
  }

  Widget buildChooseVisitTimeTitle(BuildContext context){
    return ChooseVisitTimeTitle(id: 0, cleanServiceTypeId: _cleanServiceTypeId!);
  }

  Widget buildChooseVisitTimeContent(BuildContext context){
    return ChooseVisitTimeContent(id: _id!, cleanServiceTypeId: _cleanServiceTypeId!,);
  }

  Widget buildChooseVisitTimeBottomFooter(BuildContext context){
    return ChooseVisitTimeBottomFooter(id: _id!, cleanServiceTypeId: _cleanServiceTypeId!,);
  }

  // 更新visitTime
  handlerUpdateVisitTime(String visitTime){
    Log.d("选择的visitTime: $visitTime");
    state = state.copyWith(visitTime: visitTime);
  }

  // 关闭visitTime 选择的弹框
  handlerHideVisitTimeDialog(){
    DialogEngine.dismiss(tag: 'chooseVisitTimeDialog');
  }

  // 获取 当前 所选的服务
  Map<String, dynamic> getCurrentService(){
    final chooseHouseCleanServiceDetailVm = ref.watch(chooseHouseCleanContentVmProvider.notifier);
    List<HouseCleanContentItem> houseCleanCheckedServiceList = [];
    final chooseAirCleanServiceDetailVm = ref.watch(chooseAirConditionContentVmProvider.notifier);
    List<AirConditionContentItem> airCleancheckedServiceList = [];

    if (_cleanServiceTypeId == servicesConstants.paidServicesType['houseCleaning']!['id']) {
      houseCleanCheckedServiceList = chooseHouseCleanServiceDetailVm.state.checkedServiceList ?? [];
    } else if (_cleanServiceTypeId == servicesConstants.paidServicesType['airConditioner']!['id']) {
      airCleancheckedServiceList = chooseAirCleanServiceDetailVm.state.checkedServiceList ?? [];
    }

    return {
      "houseCleanCheckedServiceList": houseCleanCheckedServiceList,
      "airCleancheckedServiceList": airCleancheckedServiceList
    };
  }

  Map<String, dynamic> handlerFlattenArrayParams(List<Map<String, dynamic>> products, String productsKey, List<String> keys) {
    Map<String, dynamic> flattened = {};
    for (int i = 0; i < products.length; i++) {
      for (String key in keys) {
        if (products[i].containsKey(key)) {
          flattened['$productsKey[$i][$key]'] = products[i][key];
        }
      }
    }
    return flattened;
  }

  Map<String, dynamic> handlerSubmitParams(){
    Map<String, dynamic> resultParams = {};
    final result = getCurrentService();
    List<HouseCleanContentItem> houseCleanCheckedServiceList = result["houseCleanCheckedServiceList"] as List<HouseCleanContentItem>;
    List<AirConditionContentItem> airCleancheckedServiceList = result["airCleancheckedServiceList"] as List<AirConditionContentItem>;

    Log.d("houseCleanCheckedServiceList  $houseCleanCheckedServiceList");
    Log.d("airCleancheckedServiceList  $airCleancheckedServiceList");
    if(_cleanServiceTypeId == servicesConstants.paidServicesType['houseCleaning']!['id']){
      if(houseCleanCheckedServiceList != null && houseCleanCheckedServiceList.length > 0){
        resultParams['products'] = []; // 初始化 products 为一个 List
        houseCleanCheckedServiceList.asMap().forEach((idx, element) {
          resultParams['products'].add({
            'id': element.id,
            'quantity': element.num ?? 1,
          });
        });
      }
    }else if(_cleanServiceTypeId == servicesConstants.paidServicesType['airConditioner']!['id']){
      if(airCleancheckedServiceList != null && airCleancheckedServiceList.length > 0){
        resultParams['products'] = []; // 初始化 products 为一个 List
        airCleancheckedServiceList.asMap().forEach((idx, element) {
          resultParams['products'].add({
            'id': element.id,
            'quantity': element.num ?? 1,
          });
        });
      }
    }
    return resultParams;
  }
  // 获取订单备注
  String getRemarkInfo(){
    String remarkInfo = "";
    if(state.remarkInfo != null){
      remarkInfo = state.remarkInfo!["remark"]!['controller'].text;
    }
    Log.d("订单的备注信息: $remarkInfo");
    return remarkInfo;
  }
  // 设置订单相关数据    总价（包含购买的所有服务的价格 + 加急/节假日/夜间 等的价格总和）
  setConfirmOrderTotalPrice(BuildContext? context){
    Log.d("service_order_confirm_vm 设置订单页面的相关数据");
    double cleanServiceToTalPrice = 0.0;
    double extraCost = 0.0;  // 加急/节假日/夜间 等费用

    final chooseHouseCleanCotentVm = ref.read(chooseHouseCleanContentVmProvider.notifier);
    double houseCleanTotalPrice = 0.0;
    final chooseAirCleanContentVm = ref.read(chooseAirConditionContentVmProvider.notifier);
    double airCleanTotalPrice = 0.0;

    if (_cleanServiceTypeId == servicesConstants.paidServicesType['houseCleaning']!['id']) {
      houseCleanTotalPrice = (chooseHouseCleanCotentVm?.state.totalPrice ?? 0.0).toDouble();
      cleanServiceToTalPrice = houseCleanTotalPrice;
    } else if (_cleanServiceTypeId == servicesConstants.paidServicesType['airConditioner']!['id']) {
      airCleanTotalPrice = (chooseAirCleanContentVm?.state.totalPrice ?? 0.0).toDouble();
      cleanServiceToTalPrice = airCleanTotalPrice;
    }
    final chooseVisitTimeContentVm = ref.read(chooseVisitTimeContentVmProvider.notifier);
    extraCost = chooseVisitTimeContentVm?.state.extraTotalCost??0.0;
    Log.d("当前的 extraCost： $extraCost");

    final serviceDetailVm = ref.read(serviceCleanDetailVmProvider.notifier);

    state = state.copyWith(
        cleanServiceToTalCost: cleanServiceToTalPrice,
        extraCost: extraCost,
        datas: serviceDetailVm?.state.datas!
    );
  }

  // 点击去支付按钮
  handlerClickPayNow(BuildContext context, {int? id, int? cleanServiceTypeId}) async{
    // ToastEngine.show("Pay Now");
    if(state.visitTime == null || state.visitTime!.isEmpty){
      // 预约时间没有
      ToastEngine.show("Please select the visit time");
      return;
    }
    try {
      handlerExcutePay(
        false,
        asyncGetOrderIdFn: () async{
            Map<String, dynamic> params = {
              "planned_service_at": state.visitTime,
              "notes": getRemarkInfo(),
            };
            // params 添加 product 参数
            Map<String, dynamic> resultParams = handlerSubmitParams();
            // 数组参数扁平
            List<Map<String, dynamic>> products = resultParams['products'].cast<Map<String, dynamic>>();
            String productsKey = 'products';
            List<String> keys = ['id', 'quantity'];

            Map<String, dynamic> flattenedProducts = handlerFlattenArrayParams(products, productsKey, keys);
            // 合并参数
            params.addAll(flattenedProducts);
            Log.d("最终的参数params:  $params");
            String? orderDetailId;
            final result = await servicesRespositoryInstance.fetchPaidServiceBook(params);
            if(result.isSuccess){
            } else {
              String errorMessage = result.errorMsg!;
              // changeLoadingState(LoadState.State_Error, errorMessage);
              ToastEngine.show(errorMessage ?? "Network Load Error");
            }
            PaidServicePaySuccessInfoEntity paidServicePaySuccessInfo = result.data as PaidServicePaySuccessInfoEntity;
            orderDetailId = paidServicePaySuccessInfo?.id;
            int? orderId_int = paidServicePaySuccessInfo?.order?.id??null;
            String? orderId = orderId_int !=null? orderId_int.toString(): '';
            Log.d("当前生成的订单ID:$orderId");
            Log.d("当前订单的详情ID:$orderDetailId");
            return {
              'orderId': orderId,
              'orderDetailId': orderDetailId,
            };
        },
        orderId: '',
        scallback: (String? orderId, String? orderDetailId){
          Log.d("支付成功后获取的订单ID:orderId：$orderId  orderDetailId: $orderDetailId");
          int orderId_int = int.parse(orderDetailId!);
          // 成功后 去支付成功页面
          // ServicePaySuccessPage.startInstance();
          context.appRouter.pushAndPopUntil(
              ServicePaySuccessPageRoute(id: orderId_int),
              predicate: (Route<dynamic> route) {       // 根据具体条件返回 true 或 false
            return route.settings.name != 'ServiceOrderConfirmPageRoute';
          });
        },
        fcallback: (String? orderId, String? orderDetailId){
          // ToastEngine.show("Pay Failed");
          int? orderDetailId_int;
          int? cleanServiceTypeId = _cleanServiceTypeId!;
          // 待支付状态
          if(orderDetailId != null){
            orderDetailId_int = int.parse(orderDetailId!);
          }
          // 使用时判断是否为空
          if (orderDetailId_int == null) {
            ToastEngine.show("Order Detail ID is invalid");
            return;
          }
          //如果失败需要关闭当前页面，并且跳转到 该订单的详情页
          context.appRouter.pushAndPopUntil(
              CleanOrderDetailPageRoute(
                id: orderDetailId_int,
                cleanServiceTypeId: cleanServiceTypeId!,
              ),
              predicate: (Route<dynamic> route) {       // 根据具体条件返回 true 或 false
                // Log.d("888 ${route.settings}");
                return route.settings.name != 'ServiceOrderConfirmPageRoute';
              }
          );
        },
      );
    } catch (e) {
      // ToastEngine.show("Error: $e");
      Log.d("支付error, $e");
    }
  }

  // 调起支付组件进行支付流程
  void handlerExcutePay(bool hasOrderId, {Future<Map<String, dynamic>> Function()? asyncGetOrderIdFn, String? orderId, String? orderDetailId, Function? scallback, Function? fcallback}) async {
    //支付流程 Loading 开始
    LoadingEngine.show();
    String finnalOrderId = '';
    String? finnalOrderDetailId;

    if(!hasOrderId){
      if(asyncGetOrderIdFn != null){
        // 异步获取订单号
      final result = await asyncGetOrderIdFn();
      Log.d("当前异步获取的订单数据： result:$result");
      if (result is Map<String, dynamic>) {
        // final {'orderId': String? finnalOrderId, 'orderDetailId': String? orderDetailId} = result;
        finnalOrderId = result['orderId'];
        finnalOrderDetailId = result['orderDetailId'];
      } else {
        // 处理错误情况
        Log.d("获取订单号asyncGetOrderIdFn 返回值不是 Map<String, dynamic>");
      }
    }
    }else {
      finnalOrderId = orderId!;
      finnalOrderDetailId = orderDetailId!;
    }

    Log.d("当前支付的订单ID:$finnalOrderId");
    if(finnalOrderId.isEmpty){
      ToastEngine.show("Order ID is Empty");
      return;
    }
    //调用支付服务
    bool success = await ComponentServiceManager().paymentService.executePayment(orderId: finnalOrderId);
    //支付流程 Loading 结束
    LoadingEngine.dismiss();
    //如果支付成功，走下一步流程
    if (success) {
      scallback?.call(finnalOrderId, finnalOrderDetailId, );
    } else {
      fcallback?.call(finnalOrderId, finnalOrderDetailId, );
    }
  }
}