
import 'dart:developer';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:ln_jq_app/common/model/base_model.dart';

class OrderModel {
  final int id;
  final int scoreGoodsId;
  final String goodsName;
  final String? goodsImage;
  final String? goodsContent;
  final String address;
  final String createTime;
  final String score;

  OrderModel({
    required this.id,
    required this.scoreGoodsId,
    required this.goodsName,
    this.goodsImage,
    this.goodsContent,
    required this.address,
    required this.createTime,
    required this.score,
  });

  factory OrderModel.fromJson(Map<String, dynamic> json) {
    return OrderModel(
      id: json['id'] as int,
      scoreGoodsId: json['scoreGoodsId'] as int,
      goodsName: json['goodsName']?.toString() ?? '',
      goodsImage: json['goodsImage'],
      goodsContent: json['goodsContent'],
      address: json['address']?.toString() ?? '',
      createTime: json['createTime']?.toString() ?? '',
      score: json['score']?.toString() ?? '',
    );
  }
}

class MallOrdersController extends GetxController with BaseControllerMixin {
  @override
  String get builderId => 'mall_orders';

  final RxList<OrderModel> orderList = <OrderModel>[].obs;
  final RxBool isLoading = true.obs;
  int pageNum = 1;
  final int pageSize = 50;

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

  Future<void> getOrders({bool isRefresh = true}) async {
    if (isRefresh) {
      pageNum = 1;
      isLoading.value = true;
      updateUi();
    }

    try {
      var response = await HttpService.to.post(
        'appointment/score/getScoreExchangeList',
        data: {
          "status": "",
          "pageNum": pageNum.toString(),
          "pageSize": pageSize.toString()
        },
      );

      if (response != null && response.data != null) {
        var result = BaseModel<Map<String, dynamic>>.fromJson(response.data);
        if (result.code == 0 && result.data != null) {
          var records = result.data!['records'] as List;
          var list = records.map((e) => OrderModel.fromJson(e)).toList();
          if (isRefresh) {
            orderList.assignAll(list);
          } else {
            orderList.addAll(list);
          }
          pageNum++;
        }
      }
    } catch (e) {
      log('获取订单列表失败: $e');
    } finally {
      isLoading.value = false;
      updateUi();
    }
  }
}
