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:cpt_services/modules/services/service_order_confirm/service_order_confirm_vm.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:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:plugin_basic/basic_export.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/permission/permission_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/event_bus.dart';
import 'package:shared/utils/ext_dart.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/dialog/app_custom_dialog.dart';
import 'package:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/dialog/dialog_content_wrap.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';

import '../../../components/chooseHouseCleanContent.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_cancel_success/clean_order_cancel_success_page.dart';
import '../service_evaluate_create/service_evaluate_create_page.dart';
import '../service_pay_success/service_pay_success_page.dart';
import 'cancelOrderDialogContent.dart';
import 'clean_order_detail_state.dart';

part 'clean_order_detail_vm.g.dart';

@riverpod
class CleanOrderDetailVm extends _$CleanOrderDetailVm with DioCancelableMixin {
  late ServicesRespository servicesRespositoryInstance;
  bool _needShowPlaceholder = false; //是否展示LoadingView

  late int _detailId;
  late int? _cleanServiceTypeId;
  late String _orderId;

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

  CleanOrderDetailState initState() {
    return CleanOrderDetailState(
      datas: null,
    );
  }

  @override
  CleanOrderDetailState build() {
    servicesRespositoryInstance = ref.read(servicesRespositoryProvider);
    final state = initState();
    Log.d("--------------------------build---------------------");
    registerCancellation();
    this.onInit();
    return state;
  }

  onInit() {
    Log.d("--------------------------onInit---------------------");
  }

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

  setInitPageData({required int id, int? cleanServiceTypeId,}) {
    _detailId = id;
    _cleanServiceTypeId = cleanServiceTypeId;
  }

  // 初始化页面数据
  // initPageData({detailId, detailcleanServiceType, detailServiceStatusCode}) {
  //   _detailId = detailId??_detailId;
  //   _cleanServiceTypeId = detailcleanServiceType??_cleanServiceTypeId;
  //   _detailServiceStatusCode = detailServiceStatusCode??_detailServiceStatusCode;
  //   Log.d("--------------------------initPageData---------------------");
  //   changeLoadingState(LoadState.State_Success, null);
  // }

  // 重试请求
  Future retryRequest(int id) async {
    _needShowPlaceholder = true;
    fetchOrderDetailData(id);
  }

  void _callPhone(String? phone) {
    if(phone == null || phone.isEmpty){
      // appRouter.pushAndPopUntil(
      //   ServicePaySuccessPageRoute(id: _detailId!, cleanServiceTypeId: _cleanServiceTypeId),
      //   predicate: (Route<dynamic> route) {       // 根据具体条件返回 true 或 false
      //     return route.settings.name != 'CleanOrderDetailPageRoute';
      //   });

      return ToastEngine.show("Phone is null");
    }
    PermissionEngine().requestCallPhonePermission(() async {
      final Uri launchUri = Uri(scheme: 'tel', path: phone);
      if (await canLaunchUrl(launchUri)) {
        await launchUrl(launchUri);
      } else {
        ToastEngine.show("Can not Call Phone");
      }
    });
  }

  handlerClickActionBtn(BuildContext context, Map<String, dynamic> actionBtn) {
    final actionBtnCode = actionBtn['code']!.toString();
    final vm = ref.read(serviceOrderConfirmVmProvider.notifier);
    switch (actionBtnCode) {
      case '0':
        // proceedWidthPayment
        vm.handlerExcutePay(
            true,
            orderId: _orderId,
            orderDetailId: _detailId.toString(),
            scallback: (String? orderId, String? orderDetailId){
              Log.d("继续支付成功 orderId:$_orderId  orderId1:$orderId  orderDetailId：$orderDetailId");
              int orderDetailId_int = int.parse(orderDetailId!);
              // 跳入 支付成功页面
              // ServicePaySuccessPage.startInstance();
              context.appRouter.pushAndPopUntil(
                  ServicePaySuccessPageRoute(id: orderDetailId_int,),
                  predicate: (Route<dynamic> route) {       // 根据具体条件返回 true 或 false
                return route.settings.name != 'CleanOrderDetailPageRoute';
              });
            }, fcallback: (String? orderId, String? orderDetailId){
            Log.d("失败");
        });
        break;
      case '1':
      // cancel
        handlerCancelOrder(context);
        break;
      case '2':
        // Contact Merchant
      Log.d(state.datas?.merchant?.contactPhone);
        _callPhone(state.datas?.merchant?.contactPhone);
        break;
      case '3':
        // Contact Service Personnel
        if (Utils.isNotEmpty(state.datas?.staff?.phone)) {
          _callPhone(state.datas?.staff?.phone);
        } else {
          ToastEngine.show("Currently, no staffs have been assigned");
        }
        break;
      case '4':
        // Delete
        handlerDeleteOrder(context);
        break;
      case '5':
        // Evaluate 去评价
        ServiceEvaluateCreatePage.startInstance(
          id: _detailId,
          cleanServiceTypeId: _cleanServiceTypeId,
        );
        break;
      default:
        break;
    }
  }

  // 删除订单
  handlerDeleteOrder(BuildContext context) {
    DialogEngine.show(
        widget: AppCustomDialog(
      message: "Are you sure you want to delete?",
      confirmAction: () {},
    ));
  }

  // 取消订单
  handlerCancelOrder(BuildContext context) {
    DialogEngine.show(
        tag: "cancelOrder",
        position: DialogPosition.center,
        onDismiss: () {
          // 清空备注信息
          clearReasonInput();
        },
        widget: DialogContentWrap(
          loadingState: LoadState.State_Success,
          maxHeight: 460.0,
          dialogWidth: 340.0,
          showCloseIcon: true,
          isShowConfirmBtn: false,
          isShowCancelBtn: false,
          confirmTxt: S.current.confirm,
          title: S.current.cancellation_of_order,
          titleBackgroundColor: DarkThemeUtil.multiColors(context, context.appColors.textWhite, darkColor: AppColorsTheme.color666666),
          closeIconColor: DarkThemeUtil.multiColors(context, context.appColors.textWhite, darkColor: Colors.white),
          titleTextStyle: TextStyle(
            color: context.appColors.textWhite,
          ),
          messageBuilder: (context) {
            return const CancelOrderDialogContent();
          },
          bottomFooterBuilder: (context) {
            return Padding(
              padding: const EdgeInsets.only(bottom: 40),
              child: MyButton(
                onPressed: () {
                  // 提交取消订单
                  submitCancelOrder(context);
                },
                text: S.current.confirm,
                minWidth: 305,
                minHeight: 45,
                fontSize: 16,
                fontWeight: FontWeight.w500,
                backgroundColor: DarkThemeUtil.multiColors(context, context.appColors.textPrimary,darkColor: Colors.black.withOpacity(0.3)),
                textColor: context.appColors.textWhite,
              ),
            );
          },
          bottomBtnRadius: 10,
          bottomBtnSpace: 5,
          topLeftRadius: 10.0,
          topRightRadius: 10.0,
          bottomLeftRadius: 10.0,
          bottomRightRadius: 10.0,
          contentPadding: const EdgeInsets.only(left: 20, right: 20, bottom: 20, top: 20),
          bottomBtnSectionPadding: const EdgeInsets.only(left: 20, right: 20, bottom: 20, top: 20),
          cancelAction: () {
            DialogEngine.dismiss(tag: 'cancelOrder');
            clearReasonInput();
          },
          confirmAction: () {
            clearReasonInput();
          },
        ));
  }

  changeCancelFormData(BuildContext context, String cancelReason) {
    // state.cancelReason = cancelReason;
    state = state.copyWith(cancelReason: cancelReason);
  }

  // 取消订单
  submitCancelOrder(BuildContext context) async {
    Log.d("cancelReason: ${state.cancelReason}");
    String? cancelReason = state.cancelReason;
    if (Utils.isNotEmpty(state.cancelReason)) {
      //调用接口取消订单

      final result = await servicesRespositoryInstance.fetchCancelPaidServiceOrder(id: _detailId.toString(), cancel_reason: cancelReason);

      if (result.isSuccess) {
        bus.emit(AppConstant.eventServiceOrderRefresh, _detailId.toString());
        clearReasonInput();
        DialogEngine.dismiss(tag: 'cancelOrder');
        //去成功页面
        CleanOrderCancelSuccessPage.startInstance();
      } else {
        ToastEngine.show(result.errorMsg ?? "UnKnow Error");
      }
    } else {
      ToastEngine.show("Please enter the reason for cancellation");
    }
  }

  clearReasonInput() {
    state.cancelReason = "";
    state.cancelFormData!['reason']!["controller"].text = "";
    state = state.copyWith(cancelReason: "", cancelFormData: state.cancelFormData);
  }

  //获取订单详情数据
  fetchOrderDetailData(int id) async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading, null);
    }

    final result = await servicesRespositoryInstance.fetchPaidServiceCleanOrderDetail(id: id.toString(), cancelToken: cancelToken);

    if (result.isSuccess) {
      List<Map<String, dynamic>>? actionBtnList = handlerGetActionBtnList(orderStatus: result.data?.orderStatus, cancelStatus: result.data?.cancelStatus);
      Log.d("当前页面的 actionBtnList： $actionBtnList");
      _orderId = result.data?.order!.id.toString()??"";
      state = state.copyWith(datas: result.data, actionBtnList: actionBtnList);
      changeLoadingState(LoadState.State_Success, null);
    } else {
      changeLoadingState(LoadState.State_Error, result.errorMsg ?? "UnKnow Error");
    }
  }

  // 获取 当前页面对应 操作按钮
  List<Map<String, dynamic>>? handlerGetActionBtnList({int? orderStatus, String? cancelStatus}){
    //orderStatus 订单状态(0=待支付，1=已支付待服务，2=已服务完结)
    // cancelStatus 取消状态(0=未取消，1=自己主动取消，2=商家取消，3=平台取消)
    String? serviceStatus;
    switch (cancelStatus) {
      case '0':
        // 未取消
        if(orderStatus != null){
          serviceStatus = orderStatus!.toString();
        }
        break;
      case '1':
      // 自己主动取消
        serviceStatus = '3';
        break;
      case '2':
      // 商家取消
        serviceStatus = '3';
        break;
      case '3':
        //平台取消
        serviceStatus = '3';
        break;
      default:
        break;
    }
    Log.d("当前页面最终的 serviceStatus： $serviceStatus");
    if(serviceStatus != null){
      return servicesConstants.servicesStatusActionBtnList[serviceStatus];
    }
  }
}
