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: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/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 '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 String _cleanServiceType;
  late int _detailServiceStatusCode;

  // 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, required String cleanServiceType, required int serviceStatusCode}) {
    _detailId = id;
    _cleanServiceType = cleanServiceType;
    _detailServiceStatusCode = serviceStatusCode;
  }

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

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

  void _callPhone(String? phone) {
    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();
    switch (actionBtnCode) {
      case '0':
        // Cancel
        handlerCancelOrder(context);
        break;
      case '1':
        // Contact Merchant
        _callPhone(state.datas?.merchant?.contactPhone);
        break;
      case '2':
        // 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 '3':
        // Delete
        handlerDeleteOrder(context);
        break;
      case '4':
        // Evaluate 去评价
        ServiceEvaluateCreatePage.startInstance(
          id: _detailId,
          cleanServiceType: _cleanServiceType,
        );
        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,
          isShowConfirmBtn: false,
          isShowCancelBtn: false,
          confirmTxt: S.current.confirm,
          title: S.current.cancellation_of_order,
          titleBackgroundColor: context.appColors.textPrimary,
          closeIconColor: context.appColors.textWhite,
          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: context.appColors.textPrimary,
                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}");

    if (Utils.isNotEmpty(state.cancelReason)) {
      //调用接口取消订单
      DialogEngine.dismiss(tag: 'cancelOrder');

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

      if (result.isSuccess) {
        bus.emit(AppConstant.eventServiceOrderRefresh, _detailId.toString());
        clearReasonInput();
        //去成功页面
        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) {
      state = state.copyWith(datas: result.data);
      changeLoadingState(LoadState.State_Success, null);
    } else {
      changeLoadingState(LoadState.State_Error, result.errorMsg ?? "UnKnow Error");
    }
  }
}
