宽窄优行-由【嘉易行】项目成品而来
younger_times
2023-07-05 0d8f5fc8a516bfd07e425909e4a4432600572ee7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//
//  TravelServicePayVC.swift
//  OKProject
//
//  Created by alvin_y on 2020/6/10.
//  Copyright © 2020 yangwang. All rights reserved.
//
 
import UIKit
import RxSwift
import RxCocoa
 
 
let JumpCoupon_Noti = Notification.Name.init(rawValue: "JumpCoupon_Noti")
 
class TravelServicePayVC: YYViewController {
    
    /// 余额
    @IBOutlet weak var label_balance: UILabel!
    @IBOutlet weak var label_totalPayMoney: UILabel!
 
    /// 优惠券数量
    @IBOutlet weak var label_couponsNum: UILabel!
    
    /// 支付金额
    @IBOutlet weak var label_payMoney: UILabel!
    
    /// 提交按钮
    @IBOutlet weak var button_submit: YYButton!
    
    /// 支付宝是否选中
    @IBOutlet weak var button_aliState: UIButton!
    
    /// 微信是否选中
    @IBOutlet weak var button_weChatState: UIButton!
    
    /// 余额是否选中
    @IBOutlet weak var button_balanceState: UIButton!
    
    /// 支付宝支付
    @IBOutlet weak var button_ali: UIButton!
    
    /// 微信支付
    @IBOutlet weak var button_weChat: UIButton!
    
    /// 余额支付
    @IBOutlet weak var button_balance: UIButton!
    
    @IBOutlet weak var button_company: UIButton!
    @IBOutlet weak var button_companyState: UIButton!
    @IBOutlet weak var label_company: UILabel!
        /// 优惠券
    @IBOutlet weak var button_coupons: UIButton!
    @IBOutlet weak var button_couponHeiCons: NSLayoutConstraint!
 
    @IBOutlet weak var button_offline: UIButton!
    @IBOutlet weak var button_offlineState: UIButton!
    /// 容器
    @IBOutlet weak var view_container: UIView!
    
    /// 关闭
    @IBOutlet weak var button_close: UIButton!
    
    let viewModel = TravelServicePayViewModel()
    var couponItems = [PaymentCouponModel]()
    var maxDiscountM:PaymentCouponModel?
    var discountMoney:Double?
    var queryBalanceModel:QueryBalanceModel?
    
    
//    /// 支付方式
//    enum PayTypeNormal {
//        case balance
//        case weChat
//        case ali
//
//        func parame() -> Int {
//            switch self {
//            case .weChat:
//                return 1
//            case .ali:
//                return 2
//            default:
//                return 3
//            }
//        }
//    }
    /// 支付方式
    let payType = BehaviorRelay<PayTypeNormal>(value: .balance)
    
    private var money: Double = 0
    
    private var orderId = 0
 
    private var payway = 0
    
    let refresh = Delegate<Void,Void>()
    /// 支付失败或者 取消支付
    let payErrorBlock = Delegate<Void,Void>()
 
    let jumpBlock = Delegate<Void,Void>()
    
    /// 是否是物流 补差价支付
    var isLogisicUgentPay = false
    /// Self
    /// - Parameter orderId: 订单Id
    init(orderId: Int,money: Double,orderType: OrderType,isLogisicUgentPay:Bool = false,payway:Int = 1) {
        super.init(nibName: String.init(describing: TravelServicePayVC.self), bundle: Bundle.main)
        viewModel.orderId.accept(orderId)
        viewModel.payway.accept(payway)
        viewModel.orderType.accept(orderType)
        self.money = money
        self.payway = payway
        self.isLogisicUgentPay = isLogisicUgentPay
    }
    
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.color(hexString: "#000000",0.5)
        self.view_container.transform = CGAffineTransform.init(translationX: 0, y: screenH)
        self.button_coupons.isHidden = isLogisicUgentPay
        self.button_couponHeiCons.constant = isLogisicUgentPay ? 0:50
        viewModel.queryBalance()
//        if viewModel.orderType.value == .acrossLogistics || viewModel.orderType.value == .cityLogistics {
//            button_coupons.isHidden = true
//        }
 
//        queryCouponList(orderType: viewModel.orderType.value, orderId: viewModel.orderId.value)
 
        button_company.isHidden = payway == 1
        button_weChat.isHidden = payway == 2
        button_ali.isHidden = payway == 2
        button_balance.isHidden = payway == 2
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        UIView.animate(withDuration: 0.2) {
            self.view_container.transform = CGAffineTransform.identity
        }
    }
    
    //MARK: - UI
    override func setupViews() {
        super.setupViews()
        self.label_payMoney.text = String(format: "¥%.2lf", max(0,money))
        self.label_totalPayMoney.text = String(format: "¥%.2lf", max(0,money))
        self.button_submit.setTitle(String(format: "立即支付%.2lf元", max(0,money)), for: .normal)
    }
 
    
    /// 隐藏
    func dismiss()  {
        UIView.animate(withDuration: 0.2, animations: {
            self.view_container.transform = CGAffineTransform.init(translationX: 0, y: screenH)
        }) { (_) in
            self.dismiss(animated: true, completion: nil)
        }
        
    }
    
    //MARK: - Rx
    override func bindRx() {
        super.bindRx()
 
        NotificationCenter.default.rx.notification(JumpCoupon_Noti, object: nil).takeUntil(self.rx.deallocated).subscribe(onNext: {data in
            self.jumpBlock.call()
        }).disposed(by: disposeBag)
        
        
        /// 支付页面获取可用优惠券数量和余额
        viewModel.queryBalanceSubject
            .subscribeOn(MainScheduler.instance)
            .subscribe(onNext: { [unowned self](status) in
                switch status{
                    case .loading:
                        break
                    case .success(let model):
                        guard let data = model as? QueryBalanceModel else{return}
                        self.queryBalanceModel = data
                        self.label_balance.text = "充值余额(\(data.balance)可用)"
                        if data.type == .coupon && data.discountAmount != 0{
                            self.label_couponsNum.text = "优惠券优惠\(data.discountAmount.ld_formatFloat)元"
                        }
                        if data.type == .card && data.discountAmount != 0{
                            self.label_couponsNum.text = "优惠卡优惠\(data.discountAmount.ld_formatFloat)元"
                        }
                        let tempMoney = max(0, money - data.discountAmount)
                        self.label_payMoney.text = String(format: "%@元", tempMoney.ld_formatFloat)
                        self.button_submit.setTitle(String(format: "立即支付%.2lf元", tempMoney), for: .normal)
 
                        self.label_company.text = "企业支付(授信额度:\(data.companyLimit)元)"
 
                        var temp = PaymentCouponModel()
                        temp.money = data.discountAmount
                        temp.dataType = data.type
                        temp.id = data.objectId
                        self.maxDiscountM = temp
 
                        break
                    case .error(let error):
                        alert(text: error.localizedDescription)
                        break
                }
            }).disposed(by: rx.disposeBag)
        
        /// 支付订单
        viewModel.requestSubject
            .subscribeOn(MainScheduler.instance)
            .subscribe(onNext: { [unowned self](status) in
                switch status{
                case .loading:
                    self.show()
                    break
                case .success(let model):
                    self.hide()
                        if self.payType.value == .balance || self.payType.value == .company{
                        alert(text: "支付成功")
                        self.giveAwayMerchantCoupon()
                        self.dismiss()
                        self.refresh.call()
                    }else{
                        guard let data = model as? PayModel else{return}
                        if self.payType.value == .ali{
                            //  调起微信支付宝
                            let request = PayModel(orderString: data.orderString)
                            YYPaymentManager.shared.sendPaymentRequest(request) { (result) in
                                switch result {
                                case .success:
                                    alert(text: "支付成功")
                                    self.giveAwayMerchantCoupon()
                                    self.dismiss()
                                    self.refresh.call()
                                case .cancel:
                                    alert(text: "支付取消")
                                    
                                case .failure(let error):
                                    alert(text: error.localizedDescription)
                                }
                            }
                        }else if self.payType.value == .weChat{
                            let wechatPayRequest = YYWeChatPayRequest(partnerId: data.partnerid, prepayId: data.prepayid, package: data.package, nonceStr: data.noncestr, timeStamp: TimeInterval(data.timestamp) ?? 0, sign: data.sign)
                            YYPaymentManager.shared.sendPaymentRequest(wechatPayRequest) { result in
                                switch result {
                                    case .success:
                                        alert(text: "支付成功")
                                        self.giveAwayMerchantCoupon()
                                        self.dismiss()
                                        self.refresh.call()
                                    case .cancel:
                                        alert(text: "支付取消")
                                    case .failure(let error):
                                        alert(text: error.localizedDescription)
                                }
                            }
                        }
                    }
                    break
                case .error(let error):
                    self.hide()
                    alert(text: error.localizedDescription)
                    break
                }
            }).disposed(by: rx.disposeBag)
        
        button_close.rx.tap.subscribe(onNext: {[unowned self] (_) in
            self.dismiss(animated: true) {
                self.payErrorBlock.call()
            }
        }).disposed(by: rx.disposeBag)
        
        payType.subscribeOn(MainScheduler.instance)
            .subscribe(onNext: {[unowned self] (s) in
                self.viewModel.payType.accept(s.parame())
                switch s{
                case .balance:
                    self.updateButtonState(sender: self.button_balanceState)
                    break
                case .weChat:
                    self.updateButtonState(sender: self.button_weChatState)
                    break
                case .ali:
                    self.updateButtonState(sender: self.button_aliState)
                    break
                case .offline:
                    self.updateButtonState(sender: self.button_offlineState)
                    break
                    case .company:
                        self.updateButtonState(sender: self.button_companyState)
                        break
                }
            }).disposed(by: rx.disposeBag)
        
        button_ali.rx.tap
            .subscribe(onNext: {[unowned self] (_) in
                self.payType.accept(.ali)
            }).disposed(by: rx.disposeBag)
        
        button_weChat.rx.tap
            .subscribe(onNext: {[unowned self] (_) in
                self.payType.accept(.weChat)
            }).disposed(by: rx.disposeBag)
        
        button_balance.rx.tap
            .subscribe(onNext: {[unowned self] (_) in
                self.payType.accept(.balance)
            }).disposed(by: rx.disposeBag)
 
        button_company.rx.tap
            .subscribe(onNext: {[unowned self] (_) in
                self.payType.accept(.company)
            }).disposed(by: rx.disposeBag)
        
        button_coupons.rx.tap
            .subscribe(onNext: {[unowned self] (_) in
 
                let vc = CouponAtPaymentVC()
                vc.orderId = self.viewModel.orderId.value
                vc.orderType = self.viewModel.orderType.value
                vc.couponItems = couponItems
                vc.maxDiscountM = maxDiscountM
 
                vc.chooseDiscount { [weak self] m in
                    guard let weakSelf = self else { return }
                    if m == nil{
                        weakSelf.discountMoney = nil
                        weakSelf.maxDiscountM = nil
                        weakSelf.label_couponsNum.text = "不使用优惠"
                        weakSelf.label_payMoney.text = String(format: "¥%.2lf",  max(weakSelf.money, 0.0))
                        weakSelf.button_submit.setTitle(String(format: "立即支付%.2lf元", max(weakSelf.money, 0.0)), for: .normal)
                    }else{
                        weakSelf.calculateMaxDiscount(m)
                    }
 
                }
                self.yy_push(vc: vc)
 
//                let vc = TravelCouponsVC(orderId: self.viewModel.orderId.value, orderType: self.viewModel.orderType.value)
//                vc.didPressSubmit.delegate(on: self) { (self, data) in
//                    if let data = data{
//                        self.label_couponsNum.text = "\(data.money)元"
//                        self.viewModel.couponId.accept(data.id)
//                        self.label_payMoney.text = "¥\(String(format: "%.2f", self.money - data.money))"
//                        self.button_submit.setTitle(String(format: "立即支付%.2f元", self.money - data.money), for: .normal)
//                    }else{
//                        self.label_couponsNum.text = "\(self.viewModel.couponNum.value)张可用"
//                        self.viewModel.couponId.accept(nil)
//                        self.label_payMoney.text = String(format: "¥%.2lf", money)
//                        self.button_submit.setTitle(String(format: "立即支付%.2f元", self.money), for: .normal)
//                    }
//                }
            }).disposed(by: rx.disposeBag)
 
        button_offline.rx.tap.subscribe(onNext: {[unowned self] (_) in
            self.payType.accept(.offline)
        }).disposed(by: rx.disposeBag)
        
        button_submit.rx.tap.subscribe(onNext: { [unowned self](_) in
 
            if self.maxDiscountM != nil{
                self.viewModel.couponId.accept(self.maxDiscountM!.id)
                self.viewModel.couponDataType.accept(self.maxDiscountM!.dataType)
            }else{
                self.viewModel.couponId.accept(nil)
                self.viewModel.couponDataType.accept(nil)
            }
 
            if isLogisicUgentPay {
                self.viewModel.paylogisicOrder()
            }else {
                self.viewModel.payTaxiOrder()
            }
        }).disposed(by: rx.disposeBag)
    }
    
    /// 更新按钮状态
    /// - Parameter sender: 按钮
    func updateButtonState(sender: UIButton)  {
        let array = [button_balanceState,button_weChatState,button_aliState,button_offlineState,button_companyState]
        for item in array{
            item?.isSelected = item == sender
        }
    }
 
    func giveAwayMerchantCoupon(){
        let orderId = viewModel.orderId.value
        let orderType = viewModel.orderType.value
        ObtainCouponView.giveAwayMerchantCoupon(orderId: orderId, orderType: orderType, vc: nil)
    }
 
    /// 计算出最大的优惠
    @discardableResult
    private func calculateMaxDiscount(_ select:PaymentCouponModel? = nil)->PaymentCouponModel?{
        //初始金额
        var discountMoney:Double = money
        var discountM:PaymentCouponModel?
 
        if select != nil{
            if select!.state == .unuse{
                //抵扣券
                if select!.type == .discount{
                    let temp = discountMoney * select!.money * 0.1
                    discountMoney = max(0,temp)
                    discountM = select!
                }
                //满减券
                if select!.type == .fullMinus && money > select!.fullMoney && money - select!.money < discountMoney{
                    let temp = money - select!.money
                    discountMoney = max(0,temp)
                    discountM = select!
                }
            }
        }else{
            var minMoney = money
            for item in couponItems {
                //未使用
                if item.state == .unuse{
                    //抵扣券
                    if item.type == .discount{
                        let temp =  money * item.money * 0.1
                        discountMoney = max(0,temp)
                        if discountMoney < minMoney{
                            minMoney = discountMoney
                            discountM = item
                        }
                    }
                    //满减券
                    if item.type == .fullMinus && money > item.fullMoney && money - item.money < discountMoney{
                        let temp =  money - item.money
                        discountMoney =  max(0,temp)
                        if discountMoney < minMoney{
                            minMoney = discountMoney
                            discountM = item
                        }
                    }
                }
            }
        }
 
        if discountM != nil{
            maxDiscountM = discountM
            let info = discountM?.dataType == .card ? "优惠卡":"优惠券"
            //最大优惠券
 
            if maxDiscountM!.type == .discount{
                if maxDiscountM?.dataType == .card{
                    let temp = money * maxDiscountM!.money * 0.1
                    discountMoney = max(0,temp)
                }else{
                    discountMoney = money - maxDiscountM!.money
                }
            }
            //满减券
            if maxDiscountM!.type == .fullMinus && money > maxDiscountM!.fullMoney && money - maxDiscountM!.fullMoney < discountMoney{
                let temp = money - maxDiscountM!.money
                discountMoney = max(0,temp)
            }
 
            self.label_couponsNum.text = String(format: "%@优惠%@元", info,(money - discountMoney).ld_formatFloat)
            self.discountMoney = discountMoney
 
            self.label_payMoney.text = String(format: "¥%.2lf", max(discountMoney, 0.0))
            self.button_submit.setTitle(String(format: "立即支付%.2lf元", max(discountMoney, 0.0)), for: .normal)
        }
        return discountM
    }
 
//    private func queryCouponList(orderType:OrderType,orderId:Int){
//        APIManager.shared.provider.rx.request(.queryCouponList(orderType: orderType, orderId: orderId, pageNum: 1)).map(YYModel<[PaymentCouponModel]>.self).validate().subscribe(onSuccess: { data in
//            self.couponItems = data.data ?? []
//            self.calculateMaxDiscount()
//        }) { error in
//
//        }.disposed(by: disposeBag)
//    }
}