杨锴
2025-04-16 09a372bc45fde16fd42257ab6f78b8deeecf720b
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
//
//  VIPCenterVC.swift
//  XQMuse
//
//  Created by 无故事王国 on 2024/8/15.
//
 
import UIKit
import JQTools
import StoreKit
import WebKit
import SwiftyStoreKit
import RxSwift
 
class VIPCenterVC: BaseVC {
 
    @IBOutlet weak var bg_vip: UIImageView!
    @IBOutlet weak var label_vipHint: UILabel!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var btn_isRead: UIButton!
    @IBOutlet weak var label_expirtTime: UILabel!
    @IBOutlet weak var webView: WKWebView!
    @IBOutlet weak var webViewHeiCons: NSLayoutConstraint!
    @IBOutlet weak var btn_open: UIButton!
    private var selectIndex = 0
 
    private var productList = Set<String>()
    private var products = [SKProduct]()
    private var timeLoopDisposeBag = DisposeBag()
    private var vipContentModel:VIPContentModel?
 
    private var isShowMore:Bool = false
    private var orderId:String? //下单后的ID
 
    //测试内购账号:sandbox_muse@163.com / AB328820b1.
 
                override func viewDidLoad() {
        super.viewDidLoad()
                                title = "会员中心"
        btn_open.isEnabled = false
        btn_open.backgroundColor = UIColor.gray
 
        productList.insert("com.XQmuse.non.renewable.sub.year.1")
        productList.insert("com.XQmuse.non.renewable.sub.quarter.1")
        productList.insert("com.XQmuse.non.renewable.sub.month.1")
 
        if !isSimulator{
            Services.getTurn(progress: false).subscribe(onNext: {[weak self]data in
                guard let weakSelf = self else { return }
                if let m = data.data,m == true{
                    weakSelf.isShowMore = m
                    Services.getVipPrice().subscribe(onNext: { data in
                        if let m = data.data{
                            weakSelf.vipContentModel = m
                            weakSelf.collectionView.reloadData()
                        }
                    }).disposed(by: weakSelf.disposeBag)
                }
            }).disposed(by: disposeBag)
        }
 
                                collectionView.delegate = self
                                collectionView.dataSource = self
                                collectionView.showsHorizontalScrollIndicator = false
                                collectionView.contentInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
                                collectionView.register(VipCenterCCell.self, forCellWithReuseIdentifier: "cell")
 
        showHUD()
        InPurchaseManager.instance().setProductList(productList) { products in
            self.products = Array(products)
            self.products.sort { p1, p2 in
                return p1.price.doubleValue < p2.price.doubleValue
            }
            self.btn_open.isEnabled = true
            self.btn_open.backgroundColor = UIColor(hexString: "#8AAE65")
            self.collectionView.reloadData()
            hiddenHUD()
        }
 
 
        if UserViewModel.getAvatarInfo().checkVip(){
            self.bg_vip.image = UIImage(named: "bg_vip")
            self.label_vipHint.text = "您将享受所有会员专享音频,尽情畅游泉疗愈世界"
            self.label_expirtTime.text = UserViewModel.getAvatarInfo().vipExpireTime.components(separatedBy: " ").first! + "到期"
        }else{
            self.bg_vip.image = UIImage(named: "bg_vip_u")
            self.label_vipHint.text = "升级为会员,解锁会员专属体验"
            self.label_expirtTime.text = "你还未开通会员服务"
        }
 
        Services.getVipContent(type: 1).subscribe(onNext: { data in
            if let string = data.data{
                self.webView.loadHTMLString(string.jq_wrapHtml(), baseURL: nil)
            }
        }).disposed(by: disposeBag)
 
        Services.getUserDetail(showProgress: false).subscribe(onNext: {[weak self]data in
            if let model = data.data{
                if model.isVip == .yes{
                    self?.bg_vip.image = UIImage(named: "bg_vip")
                    self?.label_vipHint.text = "您将享受所有会员专享音频,尽情畅游泉疗愈世界"
                    self?.label_expirtTime.text = model.vipExpireTime.components(separatedBy: " ").first! + "到期"
                }else{
                    self?.bg_vip.image = UIImage(named: "bg_vip_u")
                    self?.label_vipHint.text = "升级为会员,解锁会员专属体验"
                    self?.label_expirtTime.text = "你还未开通会员服务"
                }
            }
        }) { _ in
           
        }.disposed(by: disposeBag)
    }
 
    override func setRx() {
        webView.scrollView.rx.observe(CGSize.self, "contentSize").map { (size) -> CGFloat? in
            if let size = size{
                return size.height
            }
            return nil
        }.subscribe(onNext: { [unowned self](height) in
            if let height = height{
                self.webViewHeiCons.constant = height
            }
        }).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 }
            if weakSelf.isShowMore && weakSelf.orderId != nil{
                Services.queryPayment(orderId: weakSelf.orderId!).subscribe(onNext: {data in
                    if let str = data.data{
                        switch str{
                            case "succeeded":
                                alertSuccess(msg: "购买成功")
                                weakSelf.timeLoopDisposeBag = DisposeBag()
                                NotificationCenter.default.post(name: UpdateUserProfile_Noti, object: nil, userInfo: nil)
                                DispatchQueue.main.asyncAfter(delay: 1.0) {
                                    weakSelf.navigationController?.popViewController()
                                }
                            case "failed":
                                alertError(msg: "购买失败")
                            case "closed":
                                alertError(msg: "交易已关闭")
                            case "refunded":
                                alertError(msg: "全额退款")
                            case "pending":
                                alertError(msg: "待支付")
                            default:break
                        }
                    }
                }).disposed(by: weakSelf.disposeBag)
            }
        }).disposed(by: disposeBag)
 
    }
 
    @IBAction func completeAction(_ sender: UIButton) {
        guard btn_isRead.isSelected else {
            alert(msg: "请先阅读并同意《会员用户协议》");return
        }
 
        if isShowMore{
            guard let vipContentModel else { return }
 
            var amount:Double = 0
            switch selectIndex{
                case 0:amount = Double(vipContentModel.monthlyVipIos)
                case 1:amount = Double(vipContentModel.quarterlyVipIos)
                case 2:amount = Double(vipContentModel.annualVipIos)
                default:break
            }
 
            PurchaseMethodView.show {[weak self] type in
                guard let weakSelf = self else { return }
                Services.placeOrder(orderForm: .vip, payType: type == .t2 ? 2:1, amount: amount, balanceFlag: nil, orderId: nil, receiverId: nil, targetId: nil, vipType: weakSelf.selectIndex + 1).subscribe(onNext: { data in
                    if let m = data.data{
                        weakSelf.orderId = m.orderId
 
                        if type == .t2{
                            UIApplication.shared.open(URL(string: m.qrcodeUrl!)!)
                        }
 
                        if type == .t3{
                            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: weakSelf.disposeBag)
            }
        }else{
            showHUD("正在进行内购买")
            guard products.count != 0 else {return}
            let oldVipExpireTime = UserViewModel.getAvatarInfo().vipExpireTime
 
            let product = products[selectIndex]
            let userId = UserViewModel.getAvatarInfo().userId.string
            InPurchaseManager.purchaseProduct(ID: product.productIdentifier, applicationUsername: userId) {[weak self]result in
                guard let weakSelf = self else { return }
                if result.status == 0{
                    hiddenHUD()
                    var purchaseResult:PurchaseInAPP?
                    if (result.receipt?.in_app.count ?? 0) >= 2{
                        purchaseResult = result.receipt?.in_app.sorted(by: {$0.original_purchase_date_ms!.int! > $1.original_purchase_date_ms!.int!}).first
                    }else{
                        purchaseResult = result.receipt?.in_app.first
                    }
 
                    let transactionId = purchaseResult?.transaction_id ?? ""
                    let origintransactionId = purchaseResult?.original_transaction_id ?? ""
                    let receipt = SwiftyStoreKit.localReceiptData?.base64EncodedString() ?? ""
 
                    showHUD("正在查询购买结果")
                    Services.placeOrderApple(amount: product.price.doubleValue, balanceFlag: .no, orderFrom: 3, transactionIdentifier: transactionId, vipType: weakSelf.selectIndex + 1).subscribe(onNext: { data in
                        showHUD("正在查询购买结果")
                        Services.queryPlaceOrderApple(transactionId: transactionId, receipt: receipt).subscribe(onNext: {data in
                            hiddenHUD()
                            alertSuccess(msg: "购买成功")
                            NotificationCenter.default.post(name: UpdateUserProfile_Noti, object: nil, userInfo: nil)
                            DispatchQueue.main.asyncAfter(delay: 1.0) {
                                weakSelf.navigationController?.popViewController()
                            }
                        }).disposed(by: weakSelf.disposeBag)
 
//                        let observable = Observable<Int>.interval(RxTimeInterval.seconds(5), scheduler: MainScheduler.instance)
//                        observable.subscribe { event in
//                            if event.element == 10{
//                                alertError(msg: "订单异常,请联系客服")
//                                weakSelf.timeLoopDisposeBag = DisposeBag()
//                                return
//                            }
//                            Services.getUserDetail(showProgress: false).subscribe(onNext: {data in
//                                if data.data?.vipExpireTime != oldVipExpireTime{
//                                    hiddenHUD()
//                                    alertSuccess(msg: "购买成功")
//                                    weakSelf.timeLoopDisposeBag = DisposeBag()
//                                    NotificationCenter.default.post(name: UpdateUserProfile_Noti, object: nil, userInfo: nil)
//                                    DispatchQueue.main.asyncAfter(delay: 1.0) {
//                                        weakSelf.navigationController?.popViewController()
//                                    }
//                                }
//                            }).disposed(by: weakSelf.disposeBag)
//                        }.disposed(by: weakSelf.timeLoopDisposeBag)
                    }).disposed(by: weakSelf.disposeBag)
                }
            } errorClouse: { error in
                alertError(msg: "支付失败")
            }
        }
    }
    
    @IBAction func readAction(_ sender: UIButton) {
        btn_isRead.isSelected = !btn_isRead.isSelected
    }
 
    @IBAction func agreementAction(_ sender: UIButton) {
 
        Services.getVipContent(type: 2).subscribe(onNext: { [weak self] data in
            if let str = data.data{
                let vc = VIPAgreementVC(title: "会员用户协议", content: str) {
                    self?.btn_isRead.isSelected = true
                }
                vc.modalPresentationStyle = .custom
                self?.present(vc, animated: true)
            }
        }).disposed(by: disposeBag)
    }
}
 
extension VIPCenterVC:UICollectionViewDelegate & UICollectionViewDataSource{
 
                func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
                                selectIndex = indexPath.row
                                collectionView.reloadData()
                }
 
                func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! VipCenterCCell
        if vipContentModel != nil{
            cell.isSelect(indexPath.row == selectIndex, indexPath: indexPath, vipContentModel: vipContentModel!)
        }else{
            let product = products[indexPath.row]
            cell.isSelect(indexPath.row == selectIndex,product: product)
        }
                                return cell
                }
 
                func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
 
        if vipContentModel != nil{
            return 3
        }
 
        return products.count
                }
}
 
extension VIPCenterVC:UICollectionViewDelegateFlowLayout{
                func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
                                return CGSize(width: 111, height: 132)
                }
 
                func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
                                return 11.5
                }
 
                func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
                                return 11.5
                }
}
 
class VipCenterCCell:UICollectionViewCell{
 
                private(set) var label_title:UILabel!
                private(set) var label_price:UILabel!
                private(set) var lable_priorDay:UILabel!
 
                override init(frame: CGRect) {
                                super.init(frame: frame)
                                contentView.jq_cornerRadius = 10
                                contentView.backgroundColor = UIColor(hexString: "#EFF2F2")
                                setUI()
                }
 
 
                func setUI(){
                                label_title  = UILabel()
                                label_title.text = "--会员"
                                label_title.textAlignment = .center
                                label_title.textColor = UIColor(hexString: "#353535")
                                label_title.font = .systemFont(ofSize: 16, weight: .medium)
                                contentView.addSubview(label_title)
                                label_title.snp.makeConstraints { make in
                                                make.top.equalTo(31)
                                                make.centerX.equalToSuperview()
                                                make.height.equalTo(15)
                                }
 
                                label_price  = UILabel()
                                label_price.attributedText = AttributedStringbuilder.build().add(string: "¥", withFont: .systemFont(ofSize: 15, weight:.heavy), withColor: UIColor(hexString: "#353535")!).add(string: "0", withFont: .systemFont(ofSize: 20, weight:.heavy), withColor: UIColor(hexString: "#353535")!).mutableAttributedString
                                label_price.textAlignment = .center
                                label_price.font = .systemFont(ofSize: 16, weight: .medium)
                                contentView.addSubview(label_price)
                                label_price.snp.makeConstraints { make in
                                                make.top.equalTo(label_title.snp.bottom).offset(15.5)
                                                make.centerX.equalToSuperview()
                                                make.height.equalTo(15)
                                }
 
                                lable_priorDay  = UILabel()
                                lable_priorDay.text = "¥0/天"
                                lable_priorDay.textAlignment = .center
                                lable_priorDay.font = .systemFont(ofSize: 11, weight: .medium)
                                contentView.addSubview(lable_priorDay)
                                lable_priorDay.snp.makeConstraints { make in
                                                make.top.equalTo(label_price.snp.bottom).offset(15.5)
                                                make.centerX.equalToSuperview()
                                                make.height.equalTo(15)
                                }
                }
 
    func isSelect(_ state:Bool,product:SKProduct){
        label_title.text = product.localizedTitle
 
        var priorDayPrice:Double = 0
        switch product.productIdentifier {
//            case "com.XQmuse.Non.renewing.year.1":
            case "com.XQmuse.non.renewable.sub.year.1":
                priorDayPrice = product.price.doubleValue / 365.0
//            case "com.XQmuse.Non.renewing.half.year.1":
            case "com.XQmuse.non.renewable.sub.quarter.1":
                priorDayPrice = product.price.doubleValue / 90.0
//            case "com.XQmuse.Non.renewing.month.1":
            case "com.XQmuse.non.renewable.sub.month.1":
                priorDayPrice = product.price.doubleValue / 30.0
            default:
                priorDayPrice = product.price.doubleValue
        }
        //购买后即可享受一年的会员疗愈,畅听疗愈音频
        //我的->点击"泉疗愈会员"
 
 
 
        lable_priorDay.text = String(format:"%@%@/天", product.priceLocale.currencySymbol!,priorDayPrice.jq_formatFloat)
                                if state{
                                                contentView.backgroundColor = UIColor(hexString: "#A6C586")
                                                label_title.textColor = .white
                                                lable_priorDay.textColor = .white
                                                label_price.attributedText = AttributedStringbuilder.build().add(string: product.priceLocale.currencySymbol!, withFont: .systemFont(ofSize: 15, weight:.heavy), withColor: .white).add(string: "\(product.price.intValue)", withFont: .systemFont(ofSize: 20, weight:.heavy), withColor: .white).mutableAttributedString
                                }else{
                                                contentView.backgroundColor = UIColor(hexString: "#EFF2F2")
                                                label_title.textColor = UIColor(hexString: "#353535")
                                                lable_priorDay.textColor = UIColor(hexString: "#B7B7B7")
                                                label_price.attributedText = AttributedStringbuilder.build().add(string: product.priceLocale.currencySymbol!, withFont: .systemFont(ofSize: 15, weight:.heavy), withColor: UIColor(hexString: "#353535")!).add(string: "\(product.price.intValue)", withFont: .systemFont(ofSize: 20, weight:.heavy), withColor: UIColor(hexString: "#353535")!).mutableAttributedString
                                }
                }
 
    func isSelect(_ state:Bool,indexPath:IndexPath,vipContentModel:VIPContentModel){
 
        var formartPrice:String = ""
        switch indexPath.row{
            case 0:
//                price = vipContentModel.monthlyVipIos
                label_title.text = "月度会员"
                formartPrice =  vipContentModel.monthlyVipIos.jq_formatFloat
                lable_priorDay.text = String(format: "¥%.2lf/天", vipContentModel.monthlyVipIos / 30.0)
            case 1:
//                price = vipContentModel.quarterlyVipIos
               label_title.text = "季度会员"
                formartPrice = vipContentModel.quarterlyVipIos.jq_formatFloat
               lable_priorDay.text = String(format: "¥%.2lf/天", vipContentModel.quarterlyVipIos / 90)
            case 2:
//                price = vipContentModel.annualVipIos
                label_title.text = "年度会员"
                formartPrice = vipContentModel.annualVipIos.jq_formatFloat
                lable_priorDay.text = String(format: "¥%.2lf/天", vipContentModel.annualVipIos / 365)
            default:break
        }
 
        if state{
            contentView.backgroundColor = UIColor(hexString: "#A6C586")
            label_title.textColor = .white
            lable_priorDay.textColor = .white
            label_price.attributedText = AttributedStringbuilder.build().add(string: "¥", withFont: .systemFont(ofSize: 15, weight:.heavy), withColor: .white).add(string: formartPrice, withFont: .systemFont(ofSize: 20, weight:.heavy), withColor: .white).mutableAttributedString
        }else{
            contentView.backgroundColor = UIColor(hexString: "#EFF2F2")
            label_title.textColor = UIColor(hexString: "#353535")
            lable_priorDay.textColor = UIColor(hexString: "#B7B7B7")
            label_price.attributedText = AttributedStringbuilder.build().add(string: "¥", withFont: .systemFont(ofSize: 15, weight:.heavy), withColor: UIColor(hexString: "#353535")!).add(string: formartPrice, withFont: .systemFont(ofSize: 20, weight:.heavy), withColor: UIColor(hexString: "#353535")!).mutableAttributedString
        }
    }
 
                required init?(coder: NSCoder) {
                                fatalError("init(coder:) has not been implemented")
                }
}