part of book_pay;

class BookPayController extends GetxController {
  // 购物车选中的书籍列表
  final List<CourseModel>? buy;
  BookPayController({this.buy});
  // 积分模型
  CreditPointModel creditPointModel = CreditPointModel();
  // 是否展示优惠券和积分模型
  ShowModel showModel = ShowModel();

  // 是否使用积分
  bool useCreditPoint = false;

  // 支付方式
  List<PayModel> pays =  Platform.isIOS ?[
    PayModel(type: 3, name: '紫荆币', icon: 'assets/images/pay_coin.png', selected: true),
  ]:[
    PayModel(type: 1, name: '微信', icon: 'assets/images/pay_wechat.png', selected: true),
    PayModel(type: 2, name: '支付宝', icon: 'assets/images/pay_ali.png', selected: false),
    PayModel(type: 3, name: '紫荆币', icon: 'assets/images/pay_coin.png', selected: false),
  ];

  // 时候展示底部视图
  bool showDetail = false;

  // 优惠前的原始价钱
  late double originalPrice = getOriginalPrice();
  late double finalPrice = 0.00;


  @override
  void onReady() {
    _getCreditPoints(price: '100');
    _getShow();
    computeFinalPrice();
    super.onReady();
  }

  // 支付方式
  late PayModel _payModel = pays.first;
  PayModel get payModel => _payModel;

  void show(){
    showDetail = !showDetail;
    update();
  }

  void setPayModel(PayModel payModel){
    for (PayModel model in pays) {
      if (model.type == payModel.type){
        model.selected = true;
        _payModel = model;
      }
      else{
        model.selected = false;
      }
    }
    update();
  }

  void setUse(){
    useCreditPoint = !useCreditPoint;
    // 计算
    computeFinalPrice();
    update();
  }


  /// 获取积分
  void _getCreditPoints({
    required String price
  }) async {
    creditPointModel = await ShopAPI.creditPoints(price: price);
    update();
  }

  void _getShow () async {
    showModel = await ShopAPI.show();
    update();
  }


  /// 获取优惠前的价钱
  /// 总价钱
  double  getOriginalPrice(){
    Decimal price = Decimal.zero;
    for (CourseModel model in buy!) {
      if (model.status == 1){
        if (model.selected == true){
          price = price + Decimal.parse(model.vipPrice??'0.00');
        }
      }
    }
    return price.toDouble();
  }

  /// 获取优惠后的价格
  void computeFinalPrice(){
    finalPrice = originalPrice;
    if (useCreditPoint){
      finalPrice = finalPrice - Decimal.parse(creditPointModel.deductibleAmount??'0.00').toDouble();
    }
    update();
  }



}