
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:ln_jq_app/common/model/base_model.dart';
import 'package:ln_jq_app/pages/c_page/mall/detail/view.dart';
import 'package:ln_jq_app/pages/c_page/mall/orders/view.dart';
import 'package:ln_jq_app/pages/c_page/mall/rule/view.dart';

class GoodsModel {
  final int id;
  final String categoryId;
  final String goodsName;
  final String? goodsImage;
  final int originalScore;
  final int score;
  final int stock;
  final int status;

  GoodsModel({
    required this.id,
    required this.categoryId,
    required this.goodsName,
    this.goodsImage,
    required this.originalScore,
    required this.score,
    required this.stock,
    required this.status,
  });

  factory GoodsModel.fromJson(Map<String, dynamic> json) {
    return GoodsModel(
      id: json['id'] as int,
      categoryId: json['categoryId']?.toString() ?? '',
      goodsName: json['goodsName']?.toString() ?? '',
      goodsImage: json['goodsImage'],
      originalScore: json['originalScore'] as int? ?? 0,
      score: json['score'] as int? ?? 0,
      stock: json['stock'] as int? ?? 0,
      status: json['status'] as int? ?? 1,
    );
  }
}

class UserScore {
  final int score;
  final int todaySign;

  UserScore({required this.score, required this.todaySign});

  factory UserScore.fromJson(Map<String, dynamic> json) {
    return UserScore(
      score: json['score'] as int? ?? 0,
      todaySign: json['todaySign'] as int? ?? 1,
    );
  }
}

class MallController extends GetxController with BaseControllerMixin {
  @override
  String get builderId => 'mall';

  final RxInt userScore = 0.obs;
  final RxInt todaySign = 1.obs; // 0可签到，1已签到
  final RxList<GoodsModel> goodsList = <GoodsModel>[].obs;
  final RxBool isLoading = true.obs;

  @override
  void onInit() {
    super.onInit();
    refreshData();
  }

  Future<void> refreshData() async {
    isLoading.value = true;
    await Future.wait([getUserScore(), getGoodsList()]);
    isLoading.value = false;
    updateUi();
  }

  /// 获取用户积分和签到状态
  Future<void> getUserScore() async {
    try {
      var response = await HttpService.to.post('appointment/score/getUserScore');
      if (response != null && response.data != null) {
        var result = BaseModel<UserScore>.fromJson(
          response.data,
          dataBuilder: (dataJson) => UserScore.fromJson(dataJson),
        );
        if (result.code == 0 && result.data != null) {
          userScore.value = result.data!.score;
          todaySign.value = result.data!.todaySign;
        }
      }
    } catch (e) {
      log('获取积分失败: $e');
    }
  }

  /// 签到逻辑
  Future<void> signAction() async {
    if (todaySign.value == 1) return;

    showLoading('签到中...');
    try {
      var response = await HttpService.to.post('appointment/score/sign');
      dismissLoading();
      if (response != null && response.data != null) {
        var result = BaseModel.fromJson(response.data);
        if (result.code == 0) {
          showSuccessToast('签到成功');
          getUserScore(); // 签到成功后刷新积分
        } else {
          showErrorToast(result.message);
        }
      }
    } catch (e) {
      dismissLoading();
      showErrorToast('签到异常');
    }
  }

  /// 获取商品列表
  Future<void> getGoodsList() async {
    try {
      var response = await HttpService.to.post(
        'appointment/score/getScoreGoodsList',
        data: {'categoryId': 0},
      );
      if (response != null && response.data != null) {
        var result = BaseModel<List<GoodsModel>>.fromJson(
          response.data,
          dataBuilder: (dataJson) {
            var list = dataJson as List;
            return list.map((e) => GoodsModel.fromJson(e)).toList();
          },
        );
        if (result.code == 0 && result.data != null) {
          goodsList.assignAll(result.data!);
        }
      }
    } catch (e) {
      log('获取商品列表失败: $e');
    }
  }

  /// 兑换商品
  void exchangeGoods(GoodsModel goods) {
    Get.to(() => const MallDetailPage(), arguments: {'goodsId': goods.id})
        ?.then((_) => refreshData());
  }

  ///规则说明
  void toRuleDes() {
    Get.to(() => const MallRulePage());
  }

  ///历史订单
  void toOrders() {
    Get.to(() => const MallOrdersPage());
  }
}
