
import 'dart:async';

import 'package:cpt_services/components/chooseAirConditionContent_vm.dart';
import 'package:cpt_services/components/chooseVisitTimeContent.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/paid_service_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/date_time_utils.dart';
import 'package:shared/utils/ext_dart.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';
import 'package:widgets/dialog/dialog_content_wrap.dart';

import '../../../components/chooseAirConditionContent.dart';
import '../../../components/chooseAirConditionTitle.dart';
import '../../../components/chooseHouseCleanContent.dart';
import '../../../components/chooseHouseCleanContent_vm.dart';
import '../../../components/chooseHouseCleanTitle.dart';
import '../../../constants_services.dart';
import '../../../respository/services_respository.dart';
import '../../../router/page/services_page_router.dart';
import '../service_evaluate_list/service_evaluate_list_page.dart';
import '../service_order_confirm/service_order_confirm_page.dart';
import 'service_clean_detail_state.dart';

part 'service_clean_detail_vm.g.dart';


final _chooseHouseCleanDialogGlobalKey = GlobalKey<DialogContentWrapState>();
final _chooseAirCleanDialogGlobalKey = GlobalKey<DialogContentWrapState>();


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

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

  int? _detailId;
  int? _cleanServiceTypeId;
  bool? _liked;
  num? _likesCount;


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

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

  @override
  ServiceCleanDetailState 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
    );
  }

  setInitPageData({required int id, int? cleanServiceTypeId, bool? liked, num? likesCount}){
    Log.d("service_clean_detail 设置 initpagedata ---  id:$id cleanServiceTypeId:$cleanServiceTypeId");
    _detailId = id;
    _cleanServiceTypeId = cleanServiceTypeId!;
    _liked = liked;
    _likesCount = likesCount;
  }
  
  // 初始化页面数据
  initPageData() {
    onRefresh();
  }

  // 上拉加载 更多
  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();
  }


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

    try {
      Map<String, dynamic> params = {
        "id": _detailId,
      };
      final result = await serviceRespositoryInstance.fetchPaidServiceCleanDetailInfo(params);
      if(result.isSuccess){
        state = state.copyWith(datas: result.data as PaidServiceDetailEntity);
        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?> handlerClickLikedBtn(BuildContext? context, int id, bool isLiked) async{
    try {
      Map<String, dynamic> params = {
        "id": id,
        "type": 'paid', // 类型(paid=付费服务,inquiry=询价服务)
      };
      final result = await serviceRespositoryInstance.fetchServiceLiked(params);
      if(result.isSuccess){
        return true;
      }else{
        return false;
      }
    }catch(e){
      return false;
    }
  }

  // 判断是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 contact){
    return contact.contains("mobile");
  }
  String getContactNumber(String contact){
    // whatsapp:+8617671757687     mobile:+8617671757687  截取：后面的字符串
    String number = contact.split(":")[1];
    return number;
  }

  // 点击 whatsapp
  handlerClickWhatsapp(BuildContext? context,String contactType, String title, int price){
    // 获取 WhatsApp 号码
    String whatsappNumber = getContactNumber(contactType); 
    // 构建消息并进行编码
    String message = Uri.encodeComponent("Hello, I am interested in your listing: $title for $price.");
    // 打开WhatsApp
    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 mobileNumber){
    if(mobileNumber.isEmpty){
      ToastEngine.show("No phone number found");
      return;
    }else {
      // 拨打电话
      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';
      }
    });
  }

  // 点击了 Book Now 按钮
  handlerClickBookNow(BuildContext context, {int? id, int? cleanServiceTypeId} ){
    final detailId = id ?? _detailId;
    final cleanTypeId = cleanServiceTypeId ?? _cleanServiceTypeId;   // 2 房屋清洁  3 空调清洁  5 咨询
    if(cleanTypeId == servicesConstants.paidServicesType['houseCleaning']!['id']){
      // 房屋清洁
      final chooseHouseCleanContentVm= ref.read(chooseHouseCleanContentVmProvider.notifier);
      if(!chooseHouseCleanContentVm.state.hasCheckdService){
        // 详情页面中没有选择 服务项目 此时需要弹出底部弹框供选择
        // handlerShowChooseCleanConditionerDialog(context);
        ToastEngine.show("Please select service");
      }else {
        // 详情页面中已经选择 服务项目 此时直接 跳转到 订单页面
        // 跳转到 订单确认页面
        gotoServiceOrderConfirmPage();
      }
    }else if(cleanTypeId == servicesConstants.paidServicesType['airConditioner']!['id']){
      // 空调清洁
      // 弹出选择 空调型号和数量的弹框
      handlerShowChooseAirConditionerDialog(context);
    }else if(cleanTypeId == servicesConstants.inquiryServicesType['repairAirConditioner']!['id']){
      // 咨询
    }
  }

  // 显示选择 房屋清洁的弹框
  handlerShowChooseCleanConditionerDialog(BuildContext context) async{
    // 定时器
    LoadState dialogState = LoadState.State_Success;
    DialogEngine.show(
        tag: "chooseHouseClean",
        position: DialogPosition.bottom,
        clickMaskDismiss:false,
        widget: DialogContentWrap(
          key: _chooseHouseCleanDialogGlobalKey,
          loadingState: dialogState,
          maxHeight: 315.5,
          dialogWidth: context.screenSize.width,
          isShowConfirmBtn: true,
          isShowCancelBtn: false,
          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,
          closeIconColor: context.appColors.textPrimary,
          confirmTxt: "Confirm Selection",
          cancelTxt: "Cancel",
          // yesBtnTextStyle: TextStyle(
          //   color: context.appColors.textWhite,
          //   fontSize: 17,
          //   fontWeight: FontWeight.w400
          // ),
          // noBtnTextStyle: TextStyle(
          //   color: context.appColors.textBlack,
          //   fontSize: 17,
          //   fontWeight: FontWeight.w400
          // ),
          closeAction: (){},
          confirmAction: chooseHouseCleanConfirmFn,
          cancelAction: chooseHouseCleanCancelFn,
          titleBuilder: (context) {
            return buildChooseHouseCleanTitle(context);
          },
          messageBuilder: (context) {
            return buildChooseHouseCleanContent(context);
          },
        )
    );
  }
  // 改变 _chooseHouseCleanDialogGlobalKey 的Loading状态
  changeHouseCleanDialogLoadingState(LoadState state){
    _chooseHouseCleanDialogGlobalKey.currentState?.changeDialogLoadingState(LoadState.State_Success);
  }

  // 显示 选择空调型号和数量的弹框
  handlerShowChooseAirConditionerDialog(BuildContext context, ) async{
    // 定时器
    LoadState dialogState = LoadState.State_Loading;
    DialogEngine.show(
      tag: "chooseAirConditionClean",
      position: DialogPosition.bottom,
        clickMaskDismiss:false ,
      widget: DialogContentWrap(
        key: _chooseAirCleanDialogGlobalKey,
        loadingState: dialogState,
        maxHeight: 450.0,
        dialogWidth: context.screenSize.width,
        isShowConfirmBtn: true,
        isShowCancelBtn: false,
        title: "",
        bottomBtnRadius:0,
        bottomBtnSpace: 0,
        topLeftRadius: 20.0,
        topRightRadius: 20.0,
        // bottomBtnSectionPadding: EdgeInsets.only(left: 20, right: 20, bottom: 20,top: 20),
        closeIconColor: context.appColors.textPrimary,
        yesBtnBg: context.appColors.redDefault,
        noBtnBg: context.appColors.grayBgE9,
        confirmTxt:S.current.confirm_selection,
        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
        // ),
        isConfirmAutoClose: false,
        closeAction: () {},
        confirmAction: chooseAirConditionConfirmFn,
        cancelAction: chooseAirConditionCancelFn,
        titleBuilder: (context) {
          return buildChooseAirConditionTitle(context);
        },
        messageBuilder: (context) {
          return buildChooseAirConditionContent(context);
        },
      )
    );

    await Future.delayed(Duration(milliseconds: 1000));

    _chooseAirCleanDialogGlobalKey.currentState?.changeDialogLoadingState(LoadState.State_Success);
  }

  chooseHouseCleanConfirmFn(){
    Log.d("点击了确定");
    DialogEngine.dismiss(tag: "chooseHouseClean");
    // 跳转到 订单确认页面
    gotoServiceOrderConfirmPage();
  }

  // 去订单确认页面
  gotoServiceOrderConfirmPage(){
    // appRouter.push(ServiceOrderConfirmPageRoute(id: _detailId, cleanServiceTypeId: _cleanServiceTypeId));
    ServiceOrderConfirmPage.startInstance(id: _detailId!, cleanServiceTypeId: _cleanServiceTypeId!);
  }

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

  chooseAirConditionConfirmFn(){
    Log.d("点击了确定");
    final chooseAirCleanContentVm= ref.watch(chooseAirConditionContentVmProvider.notifier);
    if(chooseAirCleanContentVm?.state.hasCheckdService??false){
      // 跳转到 订单确认页面
      // appRouter.push(ServiceOrderConfirmPageRoute(id: _detailId, cleanServiceTypeId: _cleanServiceTypeId));
      ServiceOrderConfirmPage.startInstance(id: _detailId!, cleanServiceTypeId: _cleanServiceTypeId!);
      DialogEngine.dismiss(tag: "chooseAirConditionClean");
    }else {
      // 一个数量也没选 则英文提示
      ToastEngine.show("Please Select Service");
    }
  }

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

  
  Widget buildChooseHouseCleanTitle(BuildContext context){
    return ChooseHouseCleanTitle(id: _detailId!, cleanServiceTypeId: _cleanServiceTypeId!);
  }

  Widget buildChooseHouseCleanContent(BuildContext context){
    Log.d("打开弹框 products: ${state.datas!.products!}");
    return ChooseHouseCleanContent(id: _detailId!, cleanServiceTypeId: _cleanServiceTypeId!, products: state.datas!.products!,);
  }

  Widget buildChooseAirConditionTitle(BuildContext context){
    return ChooseAirConditionTitle(id: _detailId!, cleanServiceTypeId: _cleanServiceTypeId!);
  }
  
  Widget buildChooseAirConditionContent(BuildContext context){
    return ChooseAirConditionContent(id: _detailId!, cleanServiceTypeId: _cleanServiceTypeId!,products: state.datas!.products!);
  }

  // 去 评价列表页面
  gotoUserReviewsPage(BuildContext context, int id, int? cleanServiceTypeId){
    ServiceEvaluateListPage.startInstance(id:id, cleanServiceTypeId: cleanServiceTypeId);
  }
}
