
import 'package:cpt_services/modules/services/service_order_confirm/service_order_confirm_vm.dart';
import 'package:domain/entity/service_time_period_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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/log_utils.dart';

import 'package:widgets/dialog/dialog_content_wrap.dart';
import 'package:widgets/load_state_layout.dart';

import '../../../respository/services_respository.dart';
import '../modules/services/service_clean_detail/service_clean_detail_vm.dart';
import 'chooseVisitTimeContent_state.dart';

part 'chooseVisitTimeContent_vm.g.dart';


List<Map<String, dynamic>> visitTimeList = [
  // {
  //   "time_text": "07:00 AM",
  //   "time": "2025-01-16 07:00:00",
  //   "urgent": false,
  //   "holiday": false,
  //   "night": false,
  //   "enable": false
  // },
];



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

  late BuildContext _context;
  late int _id;
  late int _cleanServiceTypeId;

  ChooseVisitTimeContentState initState(){
    Log.d("--------------------------initState---------------------");
    List<VisitTimeContentItem> visitTimeListNew = [];
    visitTimeList.forEach((item) {
      VisitTimeContentItem newItem = VisitTimeContentItem()
        ..id = null
        ..urgent = item['urgent']
        ..holiday = item['holiday']
        ..night = item['night']
        ..time = item['time']
        ..timeText = item['time_text']
        ..enable = item['enable']
        ..isChecked = false;
      visitTimeListNew.add(newItem);
    });

    return ChooseVisitTimeContentState(
      visitTimeList: visitTimeListNew,
      currentDate: DateTimeUtils.formatDate(DateTime.now(), format: "yyyy-MM-dd"),
    );
  }

  @override
  ChooseVisitTimeContentState build(){
    // 引入数据仓库
    serviceRespositoryInstance = ref.read(servicesRespositoryProvider);
    state = initState();
    return state;
  }

  void changeLoadingState(LoadState loadState, String? errorMsg) {
    state = state.copyWith(
        loadingState: loadState,
        errorMessage: errorMsg
    );
    // Log.d("87338  ${state.currentDate}");
    Log.d("87338  ${state.visitTimeList}");
  }

  setInitPageData(BuildContext context, int id, int? cleanServiceTypeId){
    _context = context;
    _id = id;
    _cleanServiceTypeId = cleanServiceTypeId!;
  }

  initPageData(BuildContext context){
    // changeLoadingState(LoadState.State_Success, null);
    getVisitTimeList(context, DateTimeUtils.formatDate(DateTime.now(), format: "yyyy-MM-dd"));
  }

  // 获取指定 日期下面的所有 时间段
  Future getVisitTimeList(BuildContext context, String date) async{
    Log.d("--------------------------getVisitTimeList---------------------");
    // 获取数据
    changeLoadingState(LoadState.State_Loading, null);
    try {
      //请求网络
      Map<String, dynamic>  params = {
        "id": _id,
        "date": date,
      };
      Log.d("请求参数------$params");
      final result = await serviceRespositoryInstance.fetchPaidServiceTimePeriod(params);
      //校验成功失败
      if (result.isSuccess) {
        List<ServiceTimePeriodEntity>? resultEntityList = result.list as List<ServiceTimePeriodEntity>;
        handlerResultList(resultEntityList);
      } else {
        String errorMessage = result.errorMsg!;
        changeLoadingState(LoadState.State_Error, errorMessage);
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      ToastEngine.show("Error: $e");
    }

  }


  void handlerResultList(List<ServiceTimePeriodEntity>? list) {
    if(list != null && list.isNotEmpty){
      // 需要模型转换 将 ServiceTimePeriodEntity 转换为 VisitTimeContentItem
      List<VisitTimeContentItem> newList = [];
      list.asMap().forEach((index,item) {
        VisitTimeContentItem newVisitTimeContentItem = VisitTimeContentItem()
          ..id = index
          ..urgent = item.urgent
          ..holiday = item.holiday
          ..night = item.night
          ..time = item.time
          ..timeText = item.timeText
          ..enable = item.enable
          ..isChecked = false;
        newList.add(newVisitTimeContentItem);
      });

      state.visitTimeList!.clear();
      state.visitTimeList!.addAll(newList);
      //更新展示的状态
      changeLoadingState(LoadState.State_Success, null);
    }
  }


  handlerChangeNum(BuildContext context, int num, int index){
    // state.visitTimeList[index].tu = num;
    // state = state.copyWith(
    //   visitTimeList: state.visitTimeList,
    // );
  }

  // 点击 时间段
  handlerTimeItemClick(BuildContext context, int index, bool changetoValue){
    Log.d("index：${index} 的 isChecked属性  变换成： $changetoValue");
    // 修改 状态
    if(state.isMultiSelect??false){
      // 可多选
      state.visitTimeList[index].isChecked = changetoValue;
    }else {
      // 不可多选
      state.visitTimeList.asMap().forEach((i,item) {
        if(i == index){
          item.isChecked = changetoValue;
        }else {
          item.isChecked = false;
        }
      });
    }

    final cleanDetailVm = ref.read(serviceCleanDetailVmProvider.notifier);
    // 结算当前所 预约的价格 （加急/节假日/夜间 等）所有选中的时间段 如果有 紧急、节假日、夜间 则需要加上相应价格
    // 注意： 如果一个时间段同时设置了多种 预约类型（加急、节假日、夜间） 目前仅算了其中一个的费用 选择的顺序为 加急、节假日、夜间
    final extraCostItemList = state.allSelectedTimeList?.map((item) {
      if (item.urgent ?? false) {
        return cleanDetailVm?.state.urgentPrice ?? 0.0;
      } else if (item.holiday ?? false) {
        return cleanDetailVm?.state.holidayPrice ?? 0.0;
      } else if (item.night ?? false) {
        return cleanDetailVm?.state.nightPrice ?? 0.0;
      } else {
        return 0.0;
      }
    }).toList();

    state.extraCostList = extraCostItemList;
    Log.d("chooseVisitTimeContent中选择了预约的时间段后 state.extraCostList: ${state.extraCostList}");
    state = state.copyWith(
      visitTimeList: state.visitTimeList,
      extraCostList: extraCostItemList,
    );

    // 设置 订单确认页面的 总价格 (当点击了 Confirm 按钮后再去设置 订单页面的总价格)
    // final serviceOrderConfirmVm = ref.read(serviceOrderConfirmVmProvider.notifier);
    // serviceOrderConfirmVm?.setConfirmOrderTotalPrice(context);
  }
}
