
import 'dart:async';

import 'package:cpt_community/modules/community/community_vm.dart';
import 'package:cpt_community/modules/garage/garagesale_detail/garagesale_detail_vm.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:domain/entity/garage_sale_rent_detail_entity.dart';
import 'package:flutter/material.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:plugin_platform/engine/loading/loading_engine.dart';
import 'package:plugin_platform/engine/sp/sp_util.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/http_result.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:router/path/router_path.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:auto_route/auto_route.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/picker/option_pick_util.dart';


import '../../../respository/common_garage.dart';
import 'garagesale_post_page.dart';
import 'garagesale_post_state.dart';

part 'garagesale_post_vm.g.dart';


@riverpod
class GaragesalePostVm extends _$GaragesalePostVm {
  late CommonGarageRespository commonGarageRespositoryInstance;
  List _resCategoryOptionsList = [];
  int _initialSaleSelectIndex = 0;
  String _initialSaleSelectedItem = '';
  int _type = 1; // 类型(1=Sale,2=Rent, 3=mineForSale 4=mineForRent)
  late GarageSaleRentDetailEntity _detailData;

  GaragesalePostPageState initState() {
    return GaragesalePostPageState(
      titleErrorText: null,
      contactInfoErrorText: null,
      priceErrorText: null,
      descriptionErrorText: '',
      categoryOptionsList: [],
      formData: {
        'sale': {
          'value': '',
          'controller': TextEditingController(),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
        'category': {
          'value': '',
          'controller': TextEditingController(),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
        'title': {
          'value': '',
          'controller': TextEditingController(),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
        'contactInfoType': {
          'value': '',
          'controller': TextEditingController(),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
        'contactInfo': {
          'value': '',
          'controller': TextEditingController(),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
        'price': {
          'value': '',
          'controller': TextEditingController(),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
        'description': {
          'value': '',
          'controller': TextEditingController(),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
      },
    );
  }


  @override
  GaragesalePostPageState build() {
    commonGarageRespositoryInstance = ref.read(commonGarageRespositoryProvider);
    // 初始化状态
    GaragesalePostPageState state = initState();

    // 当前渲染完成后执行一次
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      initListener(state);
      ref.onDispose(() {
        onDispose(state);
      });
    });

    return state;
  }

  initData({int? type}){
    _type = type ?? 1;
    Log.d("当前的type $_type");
    // 初始化回显 sale 分类
    initSaleCategory();
    this.getGarageCategoryList();
    if(_type == 3 || _type == 4){
      // mypost 页面进来的 是编辑 需要回显
      this.initEchoData();
    }
  }

  initSaleCategory() {
    state.saleOptionsList.asMap().forEach((index, item) => {
      if(_type == 1 || _type == 3){
        if(item == 'For Sale'){
          _initialSaleSelectIndex = index,
          _initialSaleSelectedItem = item
        }
      }else if(_type == 2 || _type == 4){
        if(item == 'For Rent'){
          _initialSaleSelectIndex = index,
          _initialSaleSelectedItem = item
        }
      }
    });
  }

  // mypost页面通过详情然后编辑 进入的 需要初始化回显数据
  initEchoData() async{
    LoadingEngine.show();
    // 调取 详情接口
    final garagesaleDetailVm = ref.read(garagesaleDetailVmProvider.notifier);
    final _detailData = await garagesaleDetailVm.getDetailData();
    if(_detailData != null){
      // 回显 title
      String title = _detailData.title??'';
      String price = _detailData.price?.toString()??'0';
      String description = _detailData.description??'';
      String saleSelectedOption = _type==3? 'For Sale':'For Rent';
      String contact = _detailData.contact??'';
      String contactInformation = garagesaleDetailVm.getContactNumber(contact)??'';
      String contactType = ''; // 联系方式 类型 Mobile Phone   WhatsApp
      // final category_id = result.category_id??'';
      // final categorySelectedOption = result.category??'';
      String categorySelectedOption = 'Kids';
      // 根据 categorySelectedOption

      List<String> imgList = _detailData.resources??[];
      // Log.d("详情中获取的 imgList--------$imgList");

      if(contact.isNotEmpty){
        if(garagesaleDetailVm.isContactMobile(contact)){
          // 是mobile
         state.contactTypeSelectedOption = 'Mobile Phone';
          contactType = 'Mobile Phone';
        }else if(garagesaleDetailVm.isContactWhatsApp(contact)){
          // 是whatsapp
          state.contactTypeSelectedOption = 'WhatsApp';
          contactType = 'WhatsApp';
        }
      }

      // category_id

      final newFormdata = {
        'sale': {
          'value': saleSelectedOption,
          'controller': TextEditingController(text: saleSelectedOption ?? ''),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
        'category': {
          'value': categorySelectedOption??'',
          'controller': TextEditingController(text: categorySelectedOption??''),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
        'title': {
          'value': title ?? '',
          'controller': TextEditingController(text: title ?? ''),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
        'contactInfo': {
          'value': contactInformation ?? '',
          'controller': TextEditingController(text: contactInformation ?? ''),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
        'price': {
          'value': price ?? '',
          'controller': TextEditingController(text: price != null? price.toString():''),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
        'description': {
          'value': description??'',
          'controller': TextEditingController(text: description??''),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
      };

      state = state.copyWith(
        title: title,
        description: description,
        price: price,
        categorySelectedOption: categorySelectedOption,
        contactTypeSelectedOption: contactType,
        contactInformation: contactInformation,
          imgList: imgList,
        formData: {...state.formData, ...newFormdata}
      );
    }
    LoadingEngine.dismiss();
  }

  Future<List<String>> getGarageCategoryList() async{
    final communityVm = ref.read(communityVmProvider.notifier);
    List<Map<String, dynamic>> garageCategoryList = await communityVm.getGarageSaleCategoryOptions();

    // 获取分类列表
    List<String> catNameResult = [];

    _resCategoryOptionsList = garageCategoryList;

    // 将 listJson 转换为 List<String>
    catNameResult = (garageCategoryList as List)!.map((e) => (e['name'] as String)).toList()?? [];

    state = state.copyWith(
      saleSelectedOption:_initialSaleSelectedItem,
      categoryOptionsList: catNameResult,
    );

    return catNameResult;
  }

  //catogery 选择选项
  void pickCategoryCallback() {
    _dismissKeyboard(keyStr: 'title');
    _dismissKeyboard(keyStr: 'price');
    _dismissKeyboard(keyStr: 'contactInfo');
    _dismissKeyboard(keyStr: 'description');

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.categoryOptionsList,
      initialSelectIndex: 0,
      onPickerChanged: (_, index) {
        state = state.copyWith(categorySelectedOption: state.categoryOptionsList[index]);
      },
    );
  }

  //sale 选择选项
  void pickSaleCallback() {
    _dismissKeyboard(keyStr: 'title');
    _dismissKeyboard(keyStr: 'price');
    _dismissKeyboard(keyStr: 'contactInfo');
    _dismissKeyboard(keyStr: 'description');

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.saleOptionsList,
      initialSelectIndex: _initialSaleSelectIndex,
      onPickerChanged: (_, index) {
        _initialSaleSelectIndex = index;
        state = state.copyWith(
            saleSelectedOption: state.saleOptionsList[index]
        );
      },
    );
  }

  //concatType 选择选项
  void pickContactTypeCallback() {
    _dismissKeyboard(keyStr: 'title');
    _dismissKeyboard(keyStr: 'price');
    _dismissKeyboard(keyStr: 'contactInfo');
    _dismissKeyboard(keyStr: 'description');

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.contactTypeOptionsList,
      initialSelectIndex: 0,
      onPickerChanged: (_, index) {
        state = state.copyWith(contactTypeSelectedOption: state.contactTypeOptionsList[index]);
      },
    );
  }

  // 获取聚焦的node
  FocusNode getFocusNode(Map<String, dynamic> formData, String keyStr) {
    return formData![keyStr]!['focusNode'];
  }

  // 取消表单聚焦状态
  void _dismissKeyboard({String? keyStr}) {
    if(keyStr!.isNotEmpty){
      Log.d("FeedbackCreateViewModel 取消单个表单 $keyStr 聚焦状态");
      final FocusNode sigleItemFocusNode = state.formData[keyStr]!['focusNode'];
      sigleItemFocusNode!.unfocus();
    }else {
      Log.d("FeedbackCreateViewModel 取消所有表单聚焦状态");
      // 遍历 formData 的所有表单 然后逐一取消聚焦
      Map<String, dynamic> formData = state.formData;
      for(String key in formData.keys){
        final FocusNode sigleItemFocusNode = formData[key]['focusNode'];
        sigleItemFocusNode!.unfocus();
      }
    }
  }

  // 获取表单的值
  dynamic _getFormFieldValue({List<String>? keys, String? keyStr}) {
    if(keyStr!.isEmpty){
      Log.d("获取指定集合的表单值");
      if(keys!.isNotEmpty){
        // 遍历keys获取指定多个 keys 的表单value
        Map<String, dynamic> resultValueMap = {};
        for (String itemStr in keys!) {
          TextEditingController sigleItemController = state.formData[itemStr]!['controller'];
          resultValueMap[itemStr] = sigleItemController!.text;
        }
        return resultValueMap;
      }
    }else if(keyStr!.isNotEmpty){
      Log.d("获取单个表单值  ${keyStr}");
      // 获取单个表单的value
      final TextEditingController sigleItemController = state.formData[keyStr]!['controller'];
      return sigleItemController!.text;
    }
  }


  ///提交反馈
  Future submitGaragesalePost(BuildContext context, {VoidCallback? sCallback, VoidCallback? fCallback}) async{
    Log.d("GaragesalePostPageState 提交表单");

    state = state.copyWith(titleErrorText: null, descriptionErrorText: null);
    _dismissKeyboard(keyStr: "");

    // 获取表单的值
    String  saleValue= state.saleSelectedOption ?? "";
    String  categoryValue= state.categorySelectedOption ?? "";
    int categoryId;
    String  contactTypeValue= state.contactTypeSelectedOption ?? "";

    String  titleValue= _getFormFieldValue(keyStr: 'title');
    String  contactInfoValue= _getFormFieldValue(keyStr: 'contactInfo');
    String  priceValue= _getFormFieldValue(keyStr: 'price');
    String  descriptionValue= _getFormFieldValue(keyStr: 'description');

    Log.d('当前待提交的 sale:$saleValue category:$categoryValue contactTypeValue:$contactTypeValue title:$titleValue  contactInfoValue:$contactInfoValue  price:$priceValue  description:$descriptionValue  imgList:${state.imgList}');


    if (Utils.isEmpty(saleValue)) {
      ToastEngine.show('Sale is empty');
      return;
    }
    if (Utils.isEmpty(categoryValue)) {
      ToastEngine.show('Category is empty');
      return;
    }else {
      // 通过 categoryValue 值 来获取 categoryId
      Log.d("_resCategoryOptionsList  $_resCategoryOptionsList");
      try {
        Map<String, dynamic>? categoryItem = _resCategoryOptionsList.firstWhere((element) => element['name'] == categoryValue, orElse: () => {'id': -1});
        categoryId = categoryItem?['id'];
      } catch (e) {
        Log.d("未找到匹配的 categoryValue: $categoryValue");
        ToastEngine.show('Category is invalid');
        return;
      }
    }
    if (Utils.isEmpty(contactTypeValue)) {
      ToastEngine.show('ContactType is empty');
      return;
    }

    if (Utils.isEmpty(titleValue)) {
      state = state.copyWith(titleErrorText: 'Title is empty',);
      return;
    }else {
      state.titleErrorText = null;
      state = state.copyWith(titleErrorText: null);
    }

    if (Utils.isEmpty(contactInfoValue)) {
      state = state.copyWith(contactInfoErrorText: 'ContactInfo is empty',);
      return;
    }else {
      state.contactInfoErrorText = null;
      state = state.copyWith(contactInfoErrorText: null);
    }

    if (Utils.isEmpty(priceValue)) {
      state = state.copyWith(priceErrorText: 'Price is empty',);
      return;
    }else {
      // state.priceErrorText = null;
      state = state.copyWith(priceErrorText: null);
    }

    if (Utils.isEmpty(descriptionValue)) {
      state = state.copyWith(descriptionErrorText: 'Description is empty');
      return;
    }else {
      state = state.copyWith(descriptionErrorText: null);
    }

    String totalContactStr = '';
    if(contactTypeValue == 'Mobile Phone'){
      totalContactStr = 'mobile:$contactInfoValue';
    }else if(contactTypeValue == 'WhatsApp'){
      totalContactStr = 'whatsapp:$contactInfoValue';
    }else if(contactTypeValue == 'Email'){
      totalContactStr = 'email:$contactInfoValue';
    }


    if(_type == 1 || _type == 2){
      // 新增 提交数据
      final resResult = await handlerSubmitPost(
        type: saleValue == 'For Sale'? 1:2,
        titleValue: titleValue,
        categoryId: categoryId!,
        priceValue: priceValue,
        descriptionValue: descriptionValue,
        contactValue: totalContactStr,
        imgList: state.imgList??[],
      );

      if(resResult.isSuccess){
        // 更新用户信息
        UserConfigService.getInstance().refreshUserInfo();

        final communitVm = ref.read(communityVmProvider.notifier);
        communitVm.getCurrentPageViewVm(null).initPageData();
        // Navigator.pop(context);
        appRouter.maybePop();
      }
    }else if(_type == 3 || _type ==4){
      // 调用编辑提交的接口
      // mypost 入口进入的  编辑 提交数据
      final resResult = await handlerSubmitEdit(
        id: _detailData.id!,
        titleValue: titleValue,
        categoryId: categoryId!,
        priceValue: priceValue,
        descriptionValue: descriptionValue,
        contactValue: totalContactStr,
        imgList: state.imgList??[],
      );

      if(resResult.isSuccess){
        // 更新用户信息
        // UserConfigService.getInstance().refreshUserInfo();

        final garagesaleDetailVm = ref.read(garagesaleDetailVmProvider.notifier);
        final _detailData = await garagesaleDetailVm.getDetailData();
        // Navigator.pop(context);
        appRouter.maybePop();
      }
    }
  }

  // 编辑
  Future<HttpResult<Object>> handlerSubmitEdit({
    required int id,
    required String titleValue,
    required int categoryId,
    required String priceValue,
    required String contactValue,
    required String descriptionValue,
    required List imgList,
  }) async{
    final params = <String, dynamic>{
      "id": id,
      "category_id": categoryId,
      "title": titleValue,
      "price": priceValue,
      "description": descriptionValue,
      "contact": contactValue,  // string($例如：whatsapp:+8617671757687 或 mobile:+8617671757687)
      "resources": imgList,
    };
    final result =  await commonGarageRespositoryInstance.updateMyGarage(params);
    return result;
  }

  // 新增
  Future<HttpResult<Object>> handlerSubmitPost({
    required int type,
    required String titleValue,
    required int categoryId,
    required String priceValue,
    required String contactValue,
    required String descriptionValue,
    required List imgList,
  }) async{
      final params = <String, dynamic>{
        "type": type, // 1 = For Sale  2 = For Rent
        "category_id": categoryId,
        "title": titleValue,
        "price": priceValue,
        "description": descriptionValue,
        "contact": contactValue,  // string($例如：whatsapp:+8617671757687 或 mobile:+8617671757687)
        "resources": imgList,
      };
      final result =  await commonGarageRespositoryInstance.fetchPublishGarage(params);
      return result;
  }


  //选中图片
  void setImgList(List<String> list) {
    state = state.copyWith(imgList: list);
  }

  //初始化监听
  void initListener(GaragesalePostPageState initState) {

    // 获取表单的焦点节点
    final FocusNode focusNode = getFocusNode(state.formData, 'title');
    final FocusNode focusNodeContactInfo = getFocusNode(state.formData, 'contactInfo');
    final FocusNode focusNodePrice = getFocusNode(state.formData, 'price');

    focusNode.addListener(() {
      // 获取焦点的时候清空错误文本
      if (focusNode.hasFocus) {
        state = state.copyWith(contactInfoErrorText: null, titleErrorText: null, priceErrorText:null, descriptionErrorText: null);
      }
    });
    focusNodeContactInfo.addListener(() {
      // 获取焦点的时候清空错误文本
      if (focusNodeContactInfo.hasFocus) {
        state = state.copyWith(contactInfoErrorText: null, titleErrorText: null, priceErrorText:null, descriptionErrorText: null);
      }
    });
    focusNodePrice.addListener(() {
      // 获取焦点的时候清空错误文本
      if(focusNodePrice.hasFocus){
        state = state.copyWith(contactInfoErrorText: null, titleErrorText: null, priceErrorText:null, descriptionErrorText: null);
      }
    });
  }

  //销毁资源
  void onDispose(GaragesalePostPageState initState) {
    // 获取表单的焦点节点
    final FocusNode focusNode = getFocusNode(state.formData, 'title');
    final FocusNode focusNodePrice = getFocusNode(state.formData, 'price');
    focusNode.dispose();
    focusNodePrice.dispose();

    Log.d("GaragesalePostPageState 销毁 onDispose");
  }
}
