杨锴
2024-11-26 19e3fd5eecfa5fdf1b16b60e3462a5a61de1136e
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//
//  PaymentOrderVC.swift
//  XQMuse
//
//  Created by 无故事王国 on 2024/8/15.
//
 
import UIKit
import QMUIKit
import JQTools
 
let Refreh_PaymentWallet_Noti = Notification.Name.init("Refreh_PaymentWallet_Noti")
 
 
enum TapType{
    case t1
    case t2 //z__f__b
    case t3 //w__x
    case t1t2//组合
    case t1t3//组合
    case none
}
 
class PaymentOrderVC: BaseVC {
 
    enum PaymentOrderType:Int{
        case muse = 1
        case course = 2
        case vip = 3
        case recharge = 4
    }
 
    @IBOutlet weak var image_cover: UIImageView!
    @IBOutlet weak var label_price: UILabel!
    @IBOutlet weak var label_teacher: UILabel!
    @IBOutlet weak var label_paymentCount: UILabel!
    @IBOutlet weak var label_courseName: UILabel!
    @IBOutlet weak var label_orderPrice: UILabel!
    @IBOutlet weak var label_currentAccount: UILabel!
    @IBOutlet weak var label_totalPrice: UILabel!
    @IBOutlet weak var view_searchUserInput: UIView!
    @IBOutlet weak var view_searchUserResult: UIView!
 
    @IBOutlet weak var image_avatar: UIImageView!
    @IBOutlet weak var label_userName: UILabel!
    @IBOutlet weak var label_userPhone: UILabel!
    @IBOutlet weak var label_searchInfo: UILabel!
    @IBOutlet weak var btn_invate: UIButton!
    @IBOutlet weak var btn_isRead: UIButton!
 
    @IBOutlet weak var tf_phone: QMUITextField!
    @IBOutlet weak var label_walletBalance: UILabel!
    @IBOutlet weak var btn_isreadAgreement: UIButton!
 
    @IBOutlet weak var label_p_1: UILabel!
    @IBOutlet weak var label_p_2: UILabel!
    @IBOutlet weak var btn_tap0: TapBtn!
    @IBOutlet weak var btn_tap1: TapBtn!
    @IBOutlet weak var btn_tap2: TapBtn!
 
    @IBOutlet weak var img_action_1: UIImageView!
    @IBOutlet weak var img_action_2: UIImageView!
    @IBOutlet weak var img_action_3: UIImageView!
 
    private var price:Double = 0
 
    private var tapType:TapType = .none{
        didSet{
            switch tapType {
                case .t1:
                    img_action_1.image = UIImage(named: "icon_choose_small_s")
                    img_action_2.image = UIImage(named: "icon_choose_small_1")
                    img_action_3.image = UIImage(named: "icon_choose_small_1")
                case .t2:
                    img_action_1.image = UIImage(named: "icon_choose_small_1")
                    img_action_2.image = UIImage(named: "icon_choose_small_s")
                    img_action_3.image = UIImage(named: "icon_choose_small_1")
                case .t3:
                    img_action_1.image = UIImage(named: "icon_choose_small_1")
                    img_action_2.image = UIImage(named: "icon_choose_small_1")
                    img_action_3.image = UIImage(named: "icon_choose_small_s")
                case .t1t2:
                    img_action_1.image = UIImage(named: "icon_choose_small_s")
                    img_action_2.image = UIImage(named: "icon_choose_small_s")
                    img_action_3.image = UIImage(named: "icon_choose_small_1")
                case .t1t3:
                    img_action_1.image = UIImage(named: "icon_choose_small_s")
                    img_action_2.image = UIImage(named: "icon_choose_small_1")
                    img_action_3.image = UIImage(named: "icon_choose_small_s")
                case .none:
                    img_action_1.image = UIImage(named: "icon_choose_small_1")
                    img_action_2.image = UIImage(named: "icon_choose_small_1")
                    img_action_3.image = UIImage(named: "icon_choose_small_1")
            }
        }
    }
 
    private var isShowMore:Bool = false
//    private var discountByCoin:Bool = true
 
    private var museItemModel:MeditationModel?
    private var courseItemModel:CourseModel?
    private var giftUserId:Int?
    private var giftToOther:Bool!
    private var courseModel:CourseModel?
    private var museModel:MeditationModel?
    private var balance:Double = 0
    private var type:PaymentOrderType!
    private var showType:DisplayType!
    private var businessId:Int?
 
    private var orderId:String? //下单后的ID
 
    init(museItemModel:MeditationModel? = nil,courseItemModel:CourseModel? = nil,type:PaymentOrderType,giftToOther:Bool = false,showType:DisplayType!,businessId:Int? = nil) {
        super.init(nibName: nil, bundle: nil)
        self.museItemModel = museItemModel
        self.courseItemModel = courseItemModel
        self.giftToOther = giftToOther
        self.type = type
        self.showType = showType
        self.businessId = businessId
    }
 
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "确认订单"
        btn_tap0.isUserInteractionEnabled = false
        view_searchUserResult.isHidden = true
        view_searchUserInput.isHidden = !giftToOther
        img_action_1.image = UIImage(named: "icon_choose_small_s")
 
        let btn = UIButton(type: .custom)
        btn.setTitle("取消订单", for: .normal)
        btn.setTitleColor(UIColor(hexString: "#353535"), for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 15)
        btn.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
 
        if type == .course{
            if self.businessId != nil{
                self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
            }
 
            Services.getCourseDetail(courseId: courseItemModel!.id).subscribe(onNext: {data in
                if let m = data.data{
                    self.courseModel = m
                    self.price = m.iosPrice
                    self.image_cover.sd_setImage(with: URL(string: m.coverUrl.components(separatedBy: ",").first?.jq_urlEncoded()))
                    self.label_courseName.text = m.courseTitle
 
                    self.label_teacher.text = "导师 \(m.tutor)"
                    self.label_paymentCount.text = "x1"
 
                    if self.isShowMore{
                        self.label_price.text = "¥\(m.iosPrice.jq_formatFloat)"
                        self.label_orderPrice.text = "¥\(m.iosPrice.jq_formatFloat)"
                        self.label_totalPrice.text = "¥\(m.iosPrice.jq_formatFloat)"
                    }else{
                        self.label_price.text = "愈疗币\(m.iosPrice.jq_formatFloat)"
                        self.label_orderPrice.text = "愈疗币\(m.iosPrice.jq_formatFloat)"
                        self.label_totalPrice.text = "愈疗币\(m.iosPrice.jq_formatFloat)"
                    }
                    self.getBalance()
                }
            }).disposed(by: disposeBag)
        }
 
        if type == .muse{
            if self.businessId != nil{
                self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
            }
 
            Services.getMeditationDetail(id: museItemModel!.id).subscribe(onNext: {[weak self] data in
                guard let weakSelf = self else { return }
                if let m = data.data{
                    weakSelf.museModel = m
                    weakSelf.price = m.iosPrice
                    weakSelf.image_cover.sd_setImage(with: URL(string: m.coverUrl.components(separatedBy: ",").first?.jq_urlEncoded()))
                    weakSelf.label_courseName.text = m.meditationTitle
                    weakSelf.label_teacher.text = ""
                    weakSelf.label_paymentCount.text = "x1"
 
                    if weakSelf.isShowMore{
                        weakSelf.label_price.text = "¥\(m.iosPrice.jq_formatFloat)"
                        weakSelf.label_orderPrice.text = "¥\(m.iosPrice.jq_formatFloat)"
                        weakSelf.label_totalPrice.text = "¥\(m.iosPrice.jq_formatFloat)"
                    }else{
                        weakSelf.label_price.text = "愈疗币\(m.iosPrice.jq_formatFloat)"
                        weakSelf.label_orderPrice.text = "愈疗币\(m.iosPrice.jq_formatFloat)"
                        weakSelf.label_totalPrice.text = "愈疗币\(m.iosPrice.jq_formatFloat)"
                    }
                    weakSelf.getBalance()
                }
            }).disposed(by: disposeBag)
        }
 
        Services.getTurn().subscribe(onNext: {[weak self]data in
            guard let weakSelf = self else { return }
            if let m = data.data,m == true{
                weakSelf.btn_tap0.isUserInteractionEnabled = true
                weakSelf.isShowMore = m
                weakSelf.img_action_1.image = UIImage(named: "icon_choose_small_1")
                weakSelf.btn_tap1.isHidden = !m
                weakSelf.btn_tap2.isHidden = !m
                weakSelf.getBalance()
 
                if let m = weakSelf.courseModel{
                    weakSelf.label_price.text = "¥\(m.iosPrice.jq_formatFloat)"
                    weakSelf.label_orderPrice.text = "¥\(m.iosPrice.jq_formatFloat)"
                    weakSelf.label_totalPrice.text = "¥\(m.iosPrice.jq_formatFloat)"
                }
 
                if let m = weakSelf.museModel{
                    weakSelf.label_price.text = "¥\(m.iosPrice.jq_formatFloat)"
                    weakSelf.label_orderPrice.text = "¥\(m.iosPrice.jq_formatFloat)"
                    weakSelf.label_totalPrice.text = "¥\(m.iosPrice.jq_formatFloat)"
                }
            }
        }).disposed(by: disposeBag)
    }
 
    override func setUI() {
        super.setUI()
 
        label_p_1.text = ("支"+"付").appending("宝").appending("支").appending("付")
        label_p_2.text = ("微"+"信").appending("支").appending("付")
    }
 
    override func setRx() {
        NotificationCenter.default.rx.notification(Refreh_PaymentWallet_Noti).take(until: self.rx.deallocated).subscribe(onNext: {[weak self] _ in
            self?.getBalance()
        }).disposed(by: disposeBag)
 
 
        NotificationCenter.default.rx.notification(UIApplication.didBecomeActiveNotification).take(until: self.rx.deallocated).subscribe(onNext: {[weak self] _ in
            guard let weakSelf = self else { return }
 
            showHUD("正在查询支付结果...")
            DispatchQueue.main.asyncAfter(delay: 2.5) {
                if weakSelf.isShowMore && weakSelf.orderId != nil{
                    Services.queryPayment(orderId: weakSelf.orderId!).subscribe(onNext: {data in
                        if let str = data.data{
                            switch str{
                                case "succeeded":
                                    hiddenHUD()
                                    alertSuccess(msg: "购买成功")
                                    var id = 0
                                    var money:Double = 0
                                    switch weakSelf.type {
                                        case .muse:
                                            id = weakSelf.museModel!.id
                                            money = weakSelf.museModel!.iosPrice
                                        case .course:
                                            id = weakSelf.courseModel!.id
                                            money = weakSelf.courseModel!.iosPrice
                                        default:break
                                    }
 
                                    let vc = PaymentOrderResultVC(type: weakSelf.type, id: id, price: money)
                                    weakSelf.push(vc: vc)
                                case "failed":
                                    hiddenHUD()
                                    alertError(msg: "购买失败")
                                case "closed":
                                    hiddenHUD()
                                    alertError(msg: "交易已关闭")
                                case "refunded":
                                    hiddenHUD()
                                    alertError(msg: "全额退款")
                                case "pending":
                                    showHUD("正在支付...")
                                default:break
                            }
                        }
                    }).disposed(by: weakSelf.disposeBag)
                }else{
                    hiddenHUD()
                }
            }
        }).disposed(by: disposeBag)
 
    }
 
    @objc private func cancelAction(){
        if businessId != nil{
            CommonAlertView.show(title: "提示", content: "是否取消订单") {[weak self] state in
                guard let weakSelf = self else { return }
                if state{
                    Services.cancelOrder(id: weakSelf.businessId!).subscribe(onNext: {data in
                        alertSuccess(msg: "订单已取消")
                        for vc in weakSelf.navigationController?.viewControllers ?? []{
                            if vc is WatchHistoryVC{
                                weakSelf.navigationController?.popToViewController(vc, animated: true)
                                NotificationCenter.default.post(name: WatchHistory_Noti, object: nil, userInfo: nil)
                                break
                            }
                        }
                    }).disposed(by: weakSelf.disposeBag)
                }
            }
        }
    }
 
    private func getBalance() {
        Services.getUserBalance().subscribe(onNext: { [weak self] data in
            guard let weakSelf = self else { return }
            
            // 解包数据并更新余额
            if let balanceData = data.data {
                weakSelf.balance = balanceData
                let formattedBalance = balanceData.jq_formatFloat
                
                // 更新 UI
                if weakSelf.isShowMore {
                    weakSelf.img_action_1.image = balanceData > 0 ? UIImage(named: "icon_choose_small_s") : UIImage(named: "icon_choose_small_1")
                    weakSelf.label_walletBalance.text = "当前可用 ¥\(formattedBalance)"
                    
                    if balanceData > weakSelf.price {
                        weakSelf.tapType = .t1
                    }
                } else {
                    weakSelf.label_walletBalance.text = "当前可用 \(formattedBalance)疗愈币"
                    weakSelf.tapType = .t1
                }
            } else {
                weakSelf.balance = 0
                weakSelf.label_walletBalance.text = "当前可用 0疗愈币"
                weakSelf.tapType = .t1
            }
        }).disposed(by: disposeBag)
    }
 
 
    @IBAction func discountByCoinAction(_ sender: TapBtn) {
 
        guard balance > 0 else {return}
        //是否能全部抵扣
        let allDiscount = balance > price
 
        if allDiscount{
            tapType = .t1
        }else{
            switch tapType {
                case .t2:self.tapType = .t1t2
                case .t3:self.tapType = .t1t3
                case .t1t2:
                    self.tapType = .t2
                case .t1t3:
                    self.tapType = .t3
                default:break
            }
        }
 
        print(tapType)
 
//        label_totalPrice.text = "¥" + price.jq_formatFloat
    }
 
    @IBAction func chooseAction(_ sender: TapBtn) {
        var price:Double = 0
        switch type {
            case .course:
                price = courseModel?.iosPrice ?? 0
            case .muse:
                price = courseModel?.iosPrice ?? 0
            default:break
        }
 
 
        //是否能全部抵扣
        let allDiscount = balance > price
 
        switch sender.tag {
            case 2001:
                if allDiscount {
                    tapType = .t2
                }else{
                    if img_action_1.image == UIImage(named: "icon_choose_small_s"){
                        tapType = .t1t2
                    }else{
                        tapType = .t2
                    }
                }
            case 2002:
                if allDiscount{
                    tapType = .t3
                }else{
                    if img_action_1.image == UIImage(named: "icon_choose_small_s"){
                        tapType = .t1t3
                    }else{
                        tapType = .t3
                    }
 
                }
            default: break
        }
        print(tapType)
    }
 
    @IBAction func invateRegisterAction(_ sender: UIButton) {
 
        let string = String(format: "%@%@?userId=%ld",ShareUrl,"/register/register",UserViewModel.getAvatarInfo().id)
        ShareView.show(URL(string: string)!, title: "分享疗愈时光,让宁静触手可及", desc: "这份疗愈之旅,带来了意想不到的平静和安宁。愿与你一同分享,让我们在繁忙的生活中找到片刻的温柔,静享属于我们的宁静时光。",hasSave: false) {
            //            alertSuccess(msg: "已保存至相册")
        }
    }
 
    @IBAction func searchUserAction(_ sender: UIButton) {
        tf_phone.resignFirstResponder()
        guard !tf_phone.text!.isEmpty else {
            alertError(msg: tf_phone.placeholder ?? "请输入好友手机号");return
        }
 
        guard tf_phone.text!.jq_isPhone else {
            alertError(msg: "请输入正确的手机号");return
        }
 
        Services.searchUserByPhone(tf_phone.text!,ignoreAlert: false).subscribe(onNext: { data in
            self.view_searchUserResult.isHidden = false
            if let m = data.data,m.id != 0{
                self.giftUserId = m.id
                self.image_avatar.sd_setImage(with: URL(string: m.avatar))
                self.label_userName.text = m.nickname
                self.label_userPhone.text = m.cellPhone
                self.label_searchInfo.isHidden = true
                self.btn_invate.isHidden = true
                self.image_avatar.isHidden = false
                self.label_userName.isHidden = false
                self.label_userPhone.isHidden = false
                self.btn_invate.isHidden = true
            }
        },onError: { _ in
            self.view_searchUserResult.isHidden = false
            self.image_avatar.isHidden = true
            self.label_userName.isHidden = true
            self.label_userPhone.isHidden = true
            self.label_searchInfo.isHidden = false
            self.btn_invate.isHidden = false
        }).disposed(by: disposeBag)
 
    }
 
    @IBAction func readAgreementAction(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
 
 
    @IBAction func webAgreementAction(_ sender: UIButton) {
 
        Services.agreementBy(.course).subscribe(onNext: {data in
            if let model = data.data{
                let vc = VIPAgreementVC(title: "课程/疗愈音频购买协议", content: model.content) {
                    self.btn_isRead.isSelected = true
                }
                vc.modalPresentationStyle = .custom
                self.present(vc, animated: true)
            }
        }).disposed(by: disposeBag)
    }
 
    @IBAction func completeAction(_ sender: UIButton) {
 
        var id:Int = 0
        if let m = courseModel{
            id = m.id
        }
 
        if let m = museModel{
            id = m.id
 
            guard id != UserViewModel.getAvatarInfo().id else {
                alertError(msg: "不能赠送给自己");return
            }
        }
 
        guard btn_isRead.isSelected else {
            alertError(msg: "请先阅读并同意《课程/疗愈音频购买协议》");return
        }
 
        if giftToOther {
            guard !tf_phone.text!.isEmpty else {
                alertError(msg: "请输入您要赠送人的手机号");return
            }
 
            guard giftUserId != nil else {
                alertError(msg: "请先查询赠送人是否存在");return
            }
        }
 
        if isShowMore{
            guard tapType != .none else {alertError(msg: "请选择支付方式");return}
            var targetId:Int = 0
            switch type {
                case .course:
                    targetId = courseModel!.id
                case .muse:
                    targetId = museModel!.id
                default:break
            }
 
            if balance < price && tapType == .t1{
                alertError(msg: "抵扣余额不足");return
            }
 
            //进行抵扣
            var discountByCoin = 2
            if tapType == .t1 || tapType == .t1t2 || tapType == .t1t3{
                discountByCoin = 1
            }
 
            var payType = 1
            if tapType == .t1t2 || tapType == .t2{
                payType = 2
            }
 
            if tapType == .t1{
                paymentByCoin(id: id);return
            }
 
            Services.placeOrder(orderForm: type, payType: payType, amount: nil, balanceFlag: discountByCoin, orderId: nil, receiverId: giftUserId, targetId: targetId, vipType: nil).subscribe(onNext: { [weak self] data in
                guard let weakSelf = self else { return }
                if let m = data.data{
                    weakSelf.orderId = m.orderId
 
                    if weakSelf.tapType == .t2 || weakSelf.tapType == .t1t2{
                        guard  m.qrcodeUrl?.isEmpty == false else{alertError(msg: "QRCode 为空");return}
                        UIApplication.shared.open(URL(string: m.qrcodeUrl!)!)
                    }
 
                    if weakSelf.tapType == .t3 || weakSelf.tapType == .t1t3{
                        let miniProgram =  WXLaunchMiniProgramReq.object()
                        miniProgram.miniProgramType = .release
                        miniProgram.userName = m.orgId!
                        miniProgram.path = m.path!
                        WXApi.send(miniProgram){ s in
                            if !s{
                                alert(msg: "打开失败")
                            }
                        }
                    }
                }
            }).disposed(by: disposeBag)
 
        }else{
            paymentByCoin(id: id)
        }
    }
 
    private func paymentByCoin(id:Int){
 
 
        guard balance > price else{
            CommonAlertView.show(title: "提示", content: "当前余额不足,请先充值", cancelStr: "暂不充值", completeStr: "去充值", isSingle: false) {[weak self] state in
                if state{
                    let vc = WalletRechargeVC()
                    self?.push(vc: vc)
                }
            }
            return
        }
 
        if businessId != nil{
            Services.gvieCourseAgain(orderForm: type, id: businessId!).subscribe(onNext: {[weak self]data in
                guard let weakSelf = self else { return }
                self?.museItemModel?.isBuy = .yes
                self?.courseItemModel?.isBuy = .yes
                self?.museModel?.isBuy = .yes
                self?.courseModel?.isBuy = .yes
                let vc = PaymentOrderResultVC(type: weakSelf.type, id: id, price: weakSelf.price)
                self?.push(vc: vc)
            }).disposed(by: disposeBag)
            return
        }
 
        Services.gvieCourse(orderForm: type, targetId: id,receiverId: giftUserId).subscribe(onNext: {[weak self]data in
            guard let weakSelf = self else { return }
            self?.museItemModel?.isBuy = .yes
            self?.courseItemModel?.isBuy = .yes
            self?.museModel?.isBuy = .yes
            self?.courseModel?.isBuy = .yes
            let vc = PaymentOrderResultVC(type: weakSelf.type, id: id, price: weakSelf.price)
            self?.push(vc: vc)
        }).disposed(by: disposeBag)
    }
}