import 'package:cpt_services/components/chooseAirConditionContent.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_detail_entity.dart';
import 'package:domain/entity/service_repair_detail_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:plugin_basic/basic_export.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:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/dialog/app_custom_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/my_text_view.dart';
import 'package:widgets/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';
import 'package:flutter/src/widgets/framework.dart';

import '../../../respository/services_respository.dart';
import '../../../router/page/services_page_router.dart';
import 'getQuoteDialogContent.dart';
import 'service_repair_detail_state.dart';

part 'service_repair_detail_vm.g.dart';

@riverpod
class ServiceRepairDetailVm extends _$ServiceRepairDetailVm {
  late ServicesRespository serviceRespositoryInstance;

  late int _detailId;
  late int _cleanServiceTypeId;

  bool _needShowPlaceholder = false; //是否展示LoadingView
  int _page = 1; // 当前页
  int _limit = 10; // 每页数量
  int _count = 0; // 总条数

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

  ServiceRepairDetailState initState() {
    return ServiceRepairDetailState(
      datas: ServiceRepairDetailEntity(),
    );
  }

  @override
  ServiceRepairDetailState build() {
    // 引入数据仓库
    serviceRespositoryInstance = ref.read(servicesRespositoryProvider);
    final state = initState();
    Log.d("--------------------------build---------------------");

    return state;
  }

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

  // 初始化页面数据
  initPageData() {
    Log.d("----for_sale_vm-----initPageData   ${state.loadingState}");
    onRefresh();
    changeLoadingState(LoadState.State_Success, null);
  }

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

  // 下拉刷新
  Future onRefresh() async {
    _page = 1;
    getDetailData();
  }

  // 手动进行刷新
  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;
    getDetailData();
  }

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

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

  Future getDetailData<T>() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading, null);
    }

    // await Future.delayed(const Duration(milliseconds: 1500));
    //
    // final Map<String, dynamic> detailData = {
    //   'id':1,
    //   'goods_img': 'https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500',
    //   'title': 'Electronic keyboard',
    //   'price': '\$66',
    //   'description':'Electronic keyboards for sale. I will attend together with the booth.\$10 per day usage Negotiable usage',
    //   'isCollection': true,
    //   'contactType': 'WhatsApp',
    //   'contactInfo': '+1 123456789',
    //   'collection_num': 12,
    //   'publisher': 'William Jefferson',
    //   'publisher_avatar': 'https://img1.baidu.com/it/u=3890726495,1572750319&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
    //   'publisher_time': 'June 17,2024 at 7:23 PM'
    // };

    // state = state.copyWith(datas: GarageSaleRentDetailEntity(
    // ));
    //
    // changeLoadingState(LoadState.State_Success, null);
    //
    // refreshController.finishRefresh();
    //
    // // 最后赋值
    // _needShowPlaceholder = false;

    try {
      Map<String, dynamic> params = {
        "id": _detailId,
      };
      final result =
          await serviceRespositoryInstance.fetchServiceRepairDetailInfo(params);
      if (result.isSuccess) {
        state = state.copyWith(datas: result.data as ServiceRepairDetailEntity);
        changeLoadingState(LoadState.State_Success, null);
        refreshController.finishRefresh();
      } else {
        String errorMessage = result.errorMsg!;
        changeLoadingState(LoadState.State_Error, errorMessage);
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      ToastEngine.show("Error: $e");
    }

    // 最后赋值
    _needShowPlaceholder = false;
  }

  // 点击了底部的收藏按钮
  Future<bool?> handlerClickCollection(
      BuildContext? context, int id, bool isCollection) async {
    // var vm;
    // if(_cleanServiceTypeId == "forSale"){
    //   // vm = ref.read(forsaleVmProvider.notifier);
    // }else if(_cleanServiceTypeId == "forRent"){
    //   vm = ref.read(forrentVmProvider.notifier);
    // }
    // try {
    //   final isSuccess = await vm.handlerClickCollection(id, isCollection);
    //   return isSuccess;
    // }catch(e){
    //
    // }
  }

  // 判断是whatsapp 还是 mobile  (通过 contact: whatsapp:+8617671757687)
  String getContactType(String contactType) {
    // whatsapp:+8617671757687  截取：前面的字符串
    String type = contactType.split(":")[0];
    return type;
  }

  isContactWhatsApp(String contactType) {
    return contactType.contains("whatsapp");
  }

  isContactMobile(String contactType) {
    return contactType.contains("mobile");
  }

  String getContactNumber(String contactType) {
    // whatsapp:+8617671757687     mobile:+8617671757687  截取：后面的字符串
    String number = contactType.split(":")[1];
    return number;
  }

  // 点击 whatsapp
  handlerClickWhatsapp(
      BuildContext? context, String contactType, String title, int price) {
    String whatsappNumber = getContactNumber(contactType); // 你需要实现这个方法
    String message = Uri.encodeComponent(
        "Hello, I am interested in your listing: $title for $price.");
    openWhatsApp(whatsappNumber, message);
  }

  // 打开whatsapp
  openWhatsApp(String phoneNumber, String message) async {
    final url = "https://wa.me/$phoneNumber/?text=${Uri.parse(message)}";
    if (await canLaunchUrl(Uri.parse(url))) {
      await launchUrl(Uri.parse(url));
    } else {
      ToastEngine.show("Could not launch $url");
      throw 'Could not launch $url';
    }
  }

  // 点击 电话
  handlerClickMobile(BuildContext? context, String contactType) {
    String mobileNumber = getContactNumber(contactType);
    // 拨打电话
    PermissionEngine().requestCallPhonePermission(() async {
      // 拨打电话
      makePhoneCall(mobileNumber);
    });
  }

  // 拨打电话
  Future<void> makePhoneCall(String phoneNumber) async {
    PermissionEngine().requestCallPhonePermission(() async {
      final Uri launchUri = Uri(
        scheme: 'tel',
        path: phoneNumber,
      );

      if (await canLaunchUrl(launchUri)) {
        await launchUrl(launchUri);
      } else {
        ToastEngine.show("Could not launch $launchUri");
        throw 'Could not launch $launchUri';
      }
    });
  }

  changeGetQuoteFormData(BuildContext context,String userNotes){
    state = state.copyWith(
      userNotes: userNotes,
    );
  }

  // 获取 报价备注信息
  String getUserNotes(){
    String userNotes = "";
    if(state.getQuoteFormData != null){
      userNotes = state.getQuoteFormData!["userNotes"]!['controller'].text;
    }
    Log.d("报价备注信息: $userNotes");
    return userNotes;
  }

  // 提交 报价
  void handlerGetQuote(BuildContext context, int id) async {
    DialogEngine.show(
        tag: "getQuote",
        position: DialogPosition.center,
        onDismiss: () {
          // 清空报价备注信息
          clearUserNotesInput();
        },
        clickMaskDismiss: false,
        widget: DialogContentWrap(
          loadingState: LoadState.State_Success,
          maxHeight: 400.0,
          dialogWidth: 345.0,
          isShowConfirmBtn: false,
          isShowCancelBtn: false,
          confirmTxt: S.current.confirm,
          title: S.current.confirm_information,
          titleBackgroundColor:  DarkThemeUtil.multiColors(context, context.appColors.textPrimary, darkColor: AppColorsTheme.color666666),
          closeIconColor: DarkThemeUtil.multiColors(context, context.appColors.textWhite, darkColor: Colors.white),
          titleTextStyle: TextStyle(
            color: DarkThemeUtil.multiColors(context, context.appColors.textWhite, darkColor: Colors.white),
          ),
          messageBuilder: (context) {
            return const GetQuoteDialogContent();
          },
          bottomFooterBuilder: (context) {
            return Padding(
              padding: const EdgeInsets.only(bottom: 40),
              child: MyButton(
                onPressed: () {
                  // 提交取消订单
                  submitQuote(context, id);
                },
                text: S.current.confirm,
                minWidth: 305,
                minHeight: 45,
                fontSize: 16,
                fontWeight: FontWeight.w500,
                backgroundColor:  DarkThemeUtil.multiColors(context, context.appColors.textPrimary, darkColor: Colors.black),
                textColor: DarkThemeUtil.multiColors(context, context.appColors.textWhite, darkColor: Colors.white),
              ),
            );
          },
          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: 'getQuote');
            clearUserNotesInput();
          },
          confirmAction: () {
            clearUserNotesInput();
          },
        ));
  }

  clearUserNotesInput() {
    state = state.copyWith(
      userNotes: "",
      getQuoteFormData: {
        "userNotes": {
          'value': '',
          'controller': TextEditingController(),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        }
      },
    );
  }

  Future submitQuote<T>(
      BuildContext context, int id) async {
    try {
      Map<String, dynamic> params = {"service_id": id, "user_notes": getUserNotes()};
      final result =
          await serviceRespositoryInstance.fetchRepairServiceSubmit(params);
      if (result.isSuccess) {
        // 关闭 getQuote dialog
        DialogEngine.dismiss(tag: 'getQuote');
        // 弹出成功的提示dialog
        handlerClickQuoteBtn(context, id);
      } else {
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      ToastEngine.show("Error: $e");
    }
  }

  // 报价提交成功后的 提示dialog
  handlerClickQuoteBtn(
      BuildContext context, int id) async {
    await DialogEngine.show(
        tag: "gotoQuoteSuccess",
        position: DialogPosition.center,
        widget: AppCustomDialog(
          message: '',
          title: S.current.confirm,
          dialogWidth: MediaQuery.of(context).size.width * 0.8,
          // contentBoxMaxHeight: 350,
          // contentBoxMinHeight: 300,
          isShowConfirmBtn: true,
          confirmTxt: S.current.confirm,
          isShowCancelBtn: false,
          messageBuilder: (BuildContext context) {
            return Container(
                padding: EdgeInsets.symmetric(horizontal: 30),
                child: Column(children: [
                  MyTextView(
                    S.current.received_quotation_inquiry,
                    fontSize: 16,
                    isFontMedium: true,
                    textAlign: TextAlign.center,
                    textColor: AppColorsTheme.colorPrimary,
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  MyTextView(
                    S.current.contact_your_phone,
                    fontSize: 16,
                    isFontMedium: true,
                    textAlign: TextAlign.center,
                    textColor: DarkThemeUtil.multiColors(context, ColorUtils.string2Color("#000000"), darkColor: Colors.white),
                    // textColor: context.appColors.textPrimary,
                  ),
                ]));
          },
          confirmAction: () {
            // 点击了确定
            Log.d("----点击了确定按钮");
          },
        ));
  }
}
