part of book_pay;

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

  // 是否使用积分
  bool useCreditPoint = false;
  // 优惠券可用不可用数量模型
  CouponNumModel couponNumModel = CouponNumModel();
  // 选择的优惠券模型
  late CouponModel useCouponModel =  CouponModel(couponId: 0,reducedPrice: '0.00',couponRecId: 0);
  // 创建订单模型
  late PayOrderModel payOrderModel;

  // 支付方式
  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: true),
    PayModel(type: 3, name: '紫荆币', icon: 'assets/images/pay_coin.png', selected: false),
  ];

  // 支付宝
  Tobias tobias = Tobias();
  // 微信
  Fluwx fluwx  = Fluwx();

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

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


  @override
  void onReady() {
    _getCreditPoints(price: originalPrice.toString());
    _getShow();
    computeFinalPrice();
    _getCouponNumber();
    super.onReady();
  }

  /// 使用优惠券
  void setUseCoupon(CouponModel model){
    useCouponModel = model;
    print('使用优惠券。。。。。。。。。。。。。。。。${model.couponRecId}');
    computeFinalPrice();
  }

  /// 支付方式 默认第一个
  late PayModel _payModel = pays.first;
  PayModel get payModel {
    _payModel.selected = true;
    return _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();
  }

  /// 获取优惠券可用数量与不可用数量模型
  void _getCouponNumber() async{
    couponNumModel = await ShopAPI.couponNum(price: originalPrice.toString());
    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');
          print('==============11111111111==================$price');
        }
      }
    }
    print('================================$price');
    return price.toDouble();
  }

  /// 获取优惠后的价格
  void computeFinalPrice(){
    finalPrice = Decimal.parse(originalPrice.toString());
    if (useCreditPoint){
      finalPrice = finalPrice - Decimal.parse(creditPointModel.deductibleAmount??'0.00');
    }
    // 不等0的时候证明使用了 优惠券
    if (useCouponModel.couponId !=0){
      finalPrice = finalPrice - Decimal.parse(useCouponModel.reducedPrice??'0.00');
    }
    update();
  }

  /// 创建订单
  void createOrder() async {

    fluwx.registerApi(appId: "wxd930ea5d5a228f5f",universalLink: "https://your.univerallink.com/link/");

    List<Map<String, dynamic>> bookIdsList = [];
    for (CourseModel model in buy){
      Map<String, dynamic> tempMap = {
        'book_id': model.bookId,
        'price': model.price,
        'cart_id': model.cartId,
      };
      bookIdsList.add(tempMap);
    }

    // 书豆支付的话先判断书豆数量
    if (payModel.type == 3){
      if (finalPrice.toDouble() > double.parse(showModel.membersBean.toString())){
        Toast.show('紫荆币不足，请先充值紫荆币');
        return;
      }
    }
    // 支付宝
    if (payModel.type == 2){
      final result = await tobias.isAliPayInstalled;
      if(!result){
        Toast.show('请先安装支付宝');
        return;
      }
    }
    // 微信
    if (payModel.type ==1){
      final result = await fluwx.isWeChatInstalled;
      if(!result){
        Toast.show('请先安装微信');
        return;
      }
    }

    final result = await ShopAPI.createOrder(
        bookIdsList:jsonEncode(bookIdsList) ,
        totalPrice: finalPrice.toString(),
        couponRecId: useCouponModel.couponRecId.toString(),
        integral: creditPointModel.deductibleIntegral.toString(),
        type: payModel.type.toString()
    );
    payOrderModel = result;

    // 微信
    if(payModel.type == 1){
      String orderNumber = payOrderModel.ordersnum.toString();
      if(payOrderModel.isMoneys == 0){
        requestOrderStatus();
      }else {
        requestWechat();
      }
    }
    // 支付宝
    else if(payModel.type == 2){
      String orderNumber = payOrderModel.ordersnum.toString();
      if(payOrderModel.isMoneys == 0){
        requestOrderStatus();
      }else {
        requestAliPay();
      }
    }
    // 书豆
    else if (payModel.type == 3){
      if(payOrderModel.code == -1){
        Toast.show('紫金币不足，请先充值紫荆币');
        return;
      }
      String orderNumber = payOrderModel.ordersnum.toString();
      //TODO: 拿到订单编号进行后续操作
    }
    

  }
  
  // 支付宝支付
  void requestAliPay(){

    print('================================================================${payOrderModel.encryptionOrder!}');
    tobias.pay(payOrderModel.encryptionOrder!).then((payResult){
      if (payResult['resultStatus'] == '9000') {
        requestOrderStatus();
      } else {
        Toast.show(payResult['memo'].toString());
      }
    });
  }
  
  // 微信支付
  void requestWechat(){
    Payment payment = Payment(
        appId: payOrderModel.appid??'',
        partnerId: payOrderModel.partnerid??'',
        prepayId: payOrderModel.prepayid??'',
        packageValue: payOrderModel.package??'',
        nonceStr: payOrderModel.noncestr??'',
        timestamp: payOrderModel.timestamp!.toInt(),
        sign: payOrderModel.sign??''
    );
    fluwx.pay(which: payment);
    fluwx.addSubscriber((response) {
      if (response.errCode == 0) {
        requestOrderStatus();
      }
      else{
        Toast.show('${response.errStr}');
      }
    });
  }

  void requestOrderStatus() async {
    final result = await ShopAPI.orderStatus(orderNumber: payOrderModel.ordersnum??'',receipt: '');
    if (result.paySuccess == 1){
      Toast.show('订单支付完成');
      if(context.mounted){
        context.pop(true);
      }
    }

  }







}