import 'package:cpt_community/modules/garage/for_rent/for_rent_vm.dart';
import 'package:cpt_community/modules/garage/garagesale_post/garagesale_post_vm.dart';
import 'package:cpt_community/respository/common_garage.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/entity/garage_sale_rent_detail_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:plugin_basic/basic_export.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.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/log_utils.dart';
import 'package:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import '../../../router/page/community_page_router.dart';
// import 'garagesale_detail_respository.dart';
import '../for_sale/for_sale_vm.dart';
import '../garagesale_post/garagesale_post_page.dart';
import 'garagesale_detail_state.dart';

part 'garagesale_detail_vm.g.dart';

@riverpod
class GaragesaleDetailVm extends _$GaragesaleDetailVm {
  late CommonGarageRespository commonGarageRespositoryInstance;

  int _detailId = 0;
  String _detailType = "forSale"; // forSale  forRent

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

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

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

  @override
  GarageDetailState build(){
    // 引入数据仓库
    commonGarageRespositoryInstance = ref.read(commonGarageRespositoryProvider);
    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();
  }

  // 上拉加载 更多
  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, required String type}){
    _detailId = id;
    _detailType = type;
  }

  // 删除 garagesale 数据
  Future deleteMyGarageData(BuildContext? context, int id) async {
    DialogEngine.show(
      widget: AppDefaultDialog(
        message: S.current.sure_del,
        confirmAction: () async {
          try {
            Map<String, dynamic> params = {
              "id": _detailId,
            };
            final result = await commonGarageRespositoryInstance.deleteMyGarage(params);
            if(result.isSuccess){
              // 更新用户信息
              UserConfigService.getInstance().refreshUserInfo();
              // 返回上级
              appRouter.maybePop();
            } else {
              String errorMessage = result.errorMsg!;
              changeLoadingState(LoadState.State_Error, errorMessage);
              ToastEngine.show(result.errorMsg ?? "Network Load Error");
            }
          } catch (e) {
            ToastEngine.show("Error: $e");
          }
        },
      ));
  }

  // 获取 garagesage 详情数据
  Future<GarageSaleRentDetailEntity?> 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 commonGarageRespositoryInstance.fetchGarageDetailInfo(params);
      if(result.isSuccess){
        state = state.copyWith(datas: result.data as GarageSaleRentDetailEntity);
        changeLoadingState(LoadState.State_Success, null);
        refreshController.finishRefresh();
      } else {
        String errorMessage = result.errorMsg!;
        changeLoadingState(LoadState.State_Error, errorMessage);
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
      return result.data as GarageSaleRentDetailEntity;
    } catch (e) {
      ToastEngine.show("Error: $e");
    }

    // 最后赋值
    _needShowPlaceholder = false;
  }


  // 点击了底部的收藏按钮
  Future<bool?> handlerClickCollection(BuildContext? context, int id, bool isCollection) async{
    var vm;
    if(_detailType == "forSale"){
      vm = ref.read(forsaleVmProvider.notifier);
    }else if(_detailType == "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){
    // 获取 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 contactType){
    String mobileNumber = getContactNumber(contactType);
    // 拨打电话
    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';
      }
    });
  }

  // 去 garagesale_post 页面 进行编辑
  Future<void> goToEditPage(BuildContext context,String minetype, GarageSaleRentDetailEntity detailInfo) async {
    //  type 为  forSale forRent mineForSale mineForRent
    // 点击发布的按钮 跳转到garagesale 发布的页面
    int type = minetype == "mineForSale" ? 3 : 4;
    GaragesalePostPage.startInstance(type: type, );
  }
}