import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
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/exchange_success/view.dart';

import '../mall_controller.dart';

class MallDetailController extends GetxController with BaseControllerMixin {
  @override
  String get builderId => 'mall_detail';

  late final int goodsId;
  final Rx<GoodsModel?> goodsDetail = Rx<GoodsModel?>(null);

  final addressController = TextEditingController();
  final nameController = TextEditingController();
  final phoneController = TextEditingController();

  final formKey = GlobalKey<FormState>();

  @override
  void onInit() {
    super.onInit();
    goodsId = Get.arguments['goodsId'] as int;
    getGoodsDetail();
  }

  @override
  bool get listenLifecycleEvent => true;

  Future<void> getGoodsDetail() async {
    try {
      var response = await HttpService.to.post(
        'appointment/score/getScoreGoodsDetail',
        data: {'goodsId': goodsId},
      );
      if (response != null && response.data != null) {
        var result = BaseModel<GoodsModel>.fromJson(
          response.data,
          dataBuilder: (dataJson) => GoodsModel.fromJson(dataJson),
        );
        if (result.code == 0 && result.data != null) {
          goodsDetail.value = result.data;
        } else {
          showErrorToast('加载失败: ${result.message}');
          Get.back();
        }
      }
    } catch (e) {
      log('获取商品详情失败: $e');
      showErrorToast('网络异常，请稍后重试');
      Get.back();
    } finally {
      updateUi();
    }
  }

  /// 兑换商品
  void exchange() async {
    if (!formKey.currentState!.validate()) {
      return;
    }

    /*
    final mallController = Get.find<MallController>();
    if (mallController.userScore.value < (goodsDetail.value?.score ?? 0)) {
      showWarningToast('积分不足');
      return;
    }*/

    // 接口调用预留
    showLoading('兑换中...');

    final goods = goodsDetail.value;
    if (goods == null) {
      showErrorToast('兑换失败，请稍后重试');
      return;
    }
    try {
      var response = await HttpService.to.post(
        'appointment/score/scoreExchange',
        data: {
          "goodsId": goods.id,
          "address": addressController.text,
          "name": nameController.text,
          "phone": phoneController.text,
        },
      );
      if (response != null && response.data != null) {
        var result = BaseModel.fromJson(response.data);
        if (result.code == 0) {
          Get.off(() => MallExchangeSuccessPage());
        }
      }
    } catch (e) {
      log('兑换失败: $e');
      showErrorToast('兑换失败，请稍后重试');
    } finally {
      dismissLoading();
    }
  }

  @override
  void onClose() {
    addressController.dispose();
    nameController.dispose();
    phoneController.dispose();
    super.onClose();
  }
}
