import 'package:cpt_rewards/modules/rewards_confirm/dialog/account_deactivation_dialog.dart';
import 'package:cpt_rewards/modules/rewards_successful/rewards_successful_page.dart';
import 'package:domain/entity/rewards_buy_entity.dart';
import 'package:domain/entity/rewards_detail_entity.dart';
import 'package:flutter/material.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/http/http_result.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/picker/option_pick_util.dart';
import 'package:widgets/widget_export.dart';
import './rewards_confirm_state.dart';
import './rewards_confirm_repository.dart';
part 'rewards_confirm_vm.g.dart';

@riverpod
class RewardsConfirmVm extends _$RewardsConfirmVm {
  late RewardsConfirmRepository rewardsConfirmRepository;
  bool _needShowPlaceholder = false; //是否展示LoadingView
  late int detailId;
  // Refresh 控制器
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true, //允许刷新
    controlFinishLoad: true, //允许加载
  );
  RewardsConfirmState initState() {
    return RewardsConfirmState();
  }

  @override
  RewardsConfirmState build() {
    // 引入数据仓库
    rewardsConfirmRepository = ref.read(rewardsConfirmRepositoryProvider);
    // 初始化状态
    RewardsConfirmState state = initState();
    // 初始化列表数据
    return state;
  }

  // 初始化页面数据
  initPageData({int? id}) {
    Log.d("----property_news_vm-----initPageData");
    detailId = id!;
    getListData();
  }

  // 上拉加载
  Future onLoadData() async {
    Log.d("----property_news_vm-----initListData");
    getListData();
  }

// 去新闻详情页
  void goNewsDetail(String item) {
    Log.d(item);
    // PropertyPage.startInstance(context: context, item: item);
  }

// 重试请求
  Future retryRequest({int? id}) async {
    _needShowPlaceholder = true;
    getListData();
  }

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

  // 获取list 列表数据
  void getListData<T>() async {
    Log.d("加载listData数据---------------start-----");
    try {
      //请求网络
      Map<String, dynamic> params = {"id": detailId};
      Log.d("请求参数------$params");
      final result =
          await rewardsConfirmRepository.fetchPropertyNewsList(params);
      Log.d("请求完成结果------${result.data}");
      //校验成功失败
      if (result.isSuccess) {
        state = state.copyWith(
          detailInfo: result.data as RewardsDetailEntity,
        );
        state = state.copyWith(
          amount: state.detailInfo?.point,
        );
        Log.d("123------${state.detailInfo}");
        changeLoadingState(LoadState.State_Success, null);
      } else {
        String errorMessage = result.errorMsg!;
        changeLoadingState(LoadState.State_Error, errorMessage);
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      ToastEngine.show("Error: $e");
    }
  }

  void numberAdd() {
    int numNew = state.number! + 1;
    int amountNew = numNew * state.detailInfo!.point;
    state = state.copyWith(amount: amountNew, number: numNew);
  }

  void numberDec() {
    if (state.number! > 1) {
      int numNew = state.number! - 1;
      int amountNew = numNew * state.detailInfo!.point;
      state = state.copyWith(amount: amountNew, number: numNew);
    }
  }

  void rewardBuy<T>() async {
    Log.d("加载listData数据---------------start-----");
    try {
      //请求网络
      Map<String, dynamic> params = {"id": detailId, "number": state.number};
      Log.d("请求参数------$params");
      final result = await rewardsConfirmRepository.rewardBuy(params);
      Log.d("请求完成结果------${result.data}");
      //校验成功失败
      if (result.isSuccess) {
        Log.d("123------${result.list}");
        final data = result.list as List<RewardsBuyEntity>;
        Log.d("123------$data");
        // RewardsSuccessfulPage.startInstance(data: data);
        String title = data[0].reward.title;
        String resources = data[0].reward.resources[0];
        String redeemedStart = data[0].reward.redeemedStart;
        String redeemedEnd = data[0].reward.redeemedEnd;
        String redeemedDate = '$redeemedStart until $redeemedEnd';
        String createdAt = data[0].createdAt;
        RewardsSuccessfulPage.startInstance(
            amount: state.amount,
            title: title,
            resources: resources,
            redeemedDate: redeemedDate,
            createdAt: createdAt);
      } else {
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      ToastEngine.show("Error: $e");
    }
  }

  void doDeleteAccount() {
    DialogEngine.show(widget: AccountDeactivationDialog(
      confirmAction: () {
        ToastEngine.show("点击了确定");
      },
    ));
  }
}
