123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496 |
- //
- // CheckOrderViewController.swift
- // ADHTuanCan
- //
- // Created by 敖德亨 on 2023/10/31.
- //
- import UIKit
- import RxSwift
- import RxCocoa
- //import Stripe
- import SwiftyUserDefaults
- import StripePaymentSheet
- class CheckOrderViewController: ADHBaseVC {
-
- /// 1为普团,2为白团
- var shopType : String?{
- didSet{
- self.viewModel.HomeTimeGetModel.shopType = shopType
- self.viewModel.getPaySettleTypeModel.type = self.shopType
- self.viewModel.getPayPayMentTypeModel.type = self.shopType
- }
- }
-
- /// 购物车id
- var shopcartId : NSNumber?{
- didSet{
- self.viewModel.getShoppingCarMsgResultMeal.shopcartId = shopcartId
- self.viewModel.getDefualAddressModel.shopcartId = shopcartId
- }
- }
-
-
- /// 购物时间id
- var shopcartTimeId : NSNumber?{
- didSet{
- self.viewModel.getShoppingCarMsgResultMeal.shopcartTimeId = shopcartTimeId
- }
- }
- var orderId : NSNumber?
-
- @IBOutlet weak var blackView: UIView!
-
- @IBOutlet weak var tableView: UITableView!
- @IBOutlet weak var topConst: NSLayoutConstraint!
- @IBOutlet weak var shopCar: UIView!
-
- @IBOutlet weak var priceLab: UILabel!
- var addressModel : AddressModel?
- var paymentSheet: PaymentSheet?
- let backendCheckoutUrl = URL(string: "Your backend endpoint")!
- /// 结算方式
- var paySetModel : PaySettleTypeModel?
-
- /// 支付方式Model
- var payMentModel : PayMentTypeModel?
-
- var clientSecret : String!
- var merchantDisplayName : String!
- var customerId : String?
- var customerEphemeralKeySecret : String?
- var paymentIntentClientSecret : String?
-
- @IBAction func goToPayAction(_ sender: UIButton) {
- if self.paySetModel != nil{
- self.userPayTypeView?.show()
- }else{
- self.hud.showFailure(LanguagesUtil.createTextBy(Ctext: "请先选择结算方式", Etext: "Please select the payment method first"))
- }
- }
-
- /// 当前选择的时间
- var nowTimeModel : HomeTimeItem?
- let viewModel : ShoppingCarViewModel = ShoppingCarViewModel.init()
- let diposableBag = DisposeBag()
-
-
- let headView = Bundle.main.loadNibNamed("CheckOrderHeadView", owner: nil, options: nil)?.last as? CheckOrderHeadView
-
- let addrView = Bundle.main.loadNibNamed("selectAddressView", owner: nil, options: nil)?.last as? selectAddressView
-
- let footView = Bundle.main.loadNibNamed("CheckOrderFootView", owner: nil, options: nil)?.last as? CheckOrderFootView
-
- ///结算方式
- let paymentsSheetView = Bundle.main.loadNibNamed("PayMentSelectView", owner: nil, options: nil)?.last as? PayMentSelectView
-
- ///支付方式
- let userPayTypeView = Bundle.main.loadNibNamed("UserPayMentSheet", owner: nil, options: nil)?.last as? UserPayMentSheet
-
- /// 密码支付View
- let pswPayView = Bundle.main.loadNibNamed("PswPayView", owner: nil, options: nil)?.last as? PswPayView
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- // self.view.backgroundColor = kThemeBlackColor
- self.blackView.backgroundColor = kThemeBlackColor
- self.navBar = MCNavBarView.init(title: LanguagesUtil.createTextBy(Ctext: "确认订单", Etext: "Confirm order"), subTitle: nil)
- self.navBarHeightConstraint? = self.topConst
-
- self.getPaySettle()
- self.getPayMent()
- self.getDefualAddress()
- self.getTimeRangDetail()
- self.getShopCarDetail()
- self.createUI()
- }
- //MARK: createUI
- func createUI(){
-
- _ = NotificationCenter.default.rx.notification(Notification.Name(rawValue: "刷新确认订单收货人")).takeUntil(self.rx.deallocated).subscribe(onNext:{[weak self] (notification) in
- self?.getDefualAddress()
- })
-
- self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
- self.tableView.register(withType: OrderReadyCell.self)
- self.tableView.tableHeaderView = self.headView
- self.tableView.tableFooterView = self.footView
-
- //切换日期
- self.headView?.selectBlock = {[weak self] model in
- self?.nowTimeModel = model
- self?.viewModel.getShoppingCarMsgResultMeal.shopcartTimeId = model.shopcartTimeId
-
- self?.getShopCarDetail()
- self?.reloadDateView()
- }
-
- //添加地址
- self.headView?.addAddressBlock = {[weak self] in
- let vc = AddressEditorVC()
- self?.navigationController?.pushViewController(vc, animated: true)
- }
-
- //修改地址地址
- self.headView?.changeAddressBlock = {[weak self] in
- self?.addrView?.show()
- }
-
- //点击修改结算方式
- self.headView?.payMentTouchBlock = {[unowned self] in
- self.paymentsSheetView?.show()
- }
-
- //刷新结算方式显示
- self.paymentsSheetView?.meansOfPaymentsBlock = {[unowned self] mode in
- self.paySetModel = mode
- self.viewModel.paySetModel = self.paySetModel
- self.setHeadViewPay()
- self.getPriceWithType()
- }
-
- //去支付
- self.userPayTypeView?.payTypeBlock = {[unowned self] model in
- self.payMentModel = model
- self.viewModel.payMentModel = self.payMentModel
- self.buildingOrder()
- }
-
- //密码支付
- self.pswPayView?.pswPayBlock = {[weak self] str in
- self?.pswPayAction(psw: str)
- }
-
- //选择地址保存
- self.addrView?.saveBlock = {[weak self] model in
- self?.addressModel = model
- self?.reloadHeadView()
- }
- //去添加地址
- self.addrView?.addAddressBlock = {[weak self] in
- let vc = AddressEditorVC()
- vc.shopcartId = self?.viewModel.TimeRangDetail?.shopcartId
- self?.navigationController?.pushViewController(vc, animated: true)
- }
- //去修改地址 shopcartId绑定购物车的地址
- self.addrView?.editAddressBlock = {[unowned self] model in
- self.addressModel = model
- self.addressModel?.shopcartId = self.viewModel.TimeRangDetail?.shopcartId
- let vc = AddressEditorVC()
- vc.configDefualData(model: self.addressModel!)
- self.navigationController?.pushViewController(vc, animated: true)
- }
-
- self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[unowned self] in
- //获取详情
- self.getShopCarDetail()
- });
- }
-
- //MARK: 获取默认地址
- func getDefualAddress(){
- self.hud.showLoading()
- self.viewModel.signalGetDefualAdd()?.on(success: { dd in
- self.addressModel = self.viewModel.defualAddressModel
- self.reloadHeadView()
- self.hud.hidden()
- }, error: { error in
- self.hud.showFailure(LanguagesUtil.createTextBy(Ctext: "获取地址失败", Etext: "Failed to get address"))
- })
- }
- //MARK: 获取时间范围
- func getTimeRangDetail(){
- self.hud.showLoading()
- self.viewModel.signalGetHomeTime()?.on(success: { dd in
- for item in self.viewModel.TimeRangDetail!.timeVoList! {
- let model : HomeTimeItem = item
- if model.day == self.nowTimeModel?.day{
- model.isSelect = true
- }
- }
- self.getShopCarPrice()
- self.reloadDateView()
- self.hud.hidden()
- }, error: { error in
- self.hud.showFailure(LanguagesUtil.createTextBy(Ctext: "获取时间范围失败", Etext: "Failed to obtain the time range. Procedure"))
- })
- }
-
- //MARK: 获取购物车价格详情
- func getShopCarPrice(){
-
- self.viewModel.getShopCarPriceRModel.id = self.viewModel.TimeRangDetail?.shopcartId
- self.viewModel.signalGetShopCarPrice()?.on(success: { dd in
- self.priceLab.text = "\(self.viewModel.shopCarPriceDetail?.price ?? "")"
- }, error: { error in
- self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
- })
- }
-
- //MARK: 获取日期下购物车详情
- func getShopCarDetail(){
- self.hud.showLoading()
- self.viewModel.signalgetShoppingCarMsg()?.on(success: { dd in
- self.tableView.reloadData()
- self.setTableViewHead()
- self.hud.hidden()
- self.tableView.mj_header.endRefreshing()
- }, error: { error in
- self.tableView.mj_header.endRefreshing()
- self.tableView.mj_header.endRefreshing()
- })
- }
-
- //MARK: 生成订单
- func buildingOrder(){
-
- if self.viewModel.orderIdModel != nil{
- self.self.getIsStripePay()
- return
- }
-
- self.hud.showLoading()
- self.viewModel.addOrderModel.addressId = self.addressModel?.id
-
- self.viewModel.addOrderModel.shopcartId = self.viewModel.getShoppingCarMsgResultMeal.shopcartId
- self.viewModel.addOrderModel.userType = self.shopType
-
- self.viewModel.signalAddOrderRequest()?.on(success: { dd in
- self.orderId = self.viewModel.orderIdModel?.orderId
- self.viewModel.getPayConfigurationModel.orderId = self.orderId
- self.getIsStripePay()
- self.hud.hidden()
-
- }, error: { error in
- self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
- })
- }
-
- //MARK: 密码支付
- func pswPayAction(psw : String!){
- self.hud.showLoading()
- self.viewModel.pswPayModel.orderId = self.orderId
- self.viewModel.pswPayModel.payPassword = psw
- self.viewModel.signalPSWPay()?.on(success: { dd in
-
- self.hud.showFailure(LanguagesUtil.createTextBy(Ctext: "支付成功", Etext: "payment success"))
-
- NotificationCenter.default.post(name: NSNotification.Name("刷新个人中心"), object: self, userInfo:nil)
-
- for temp in self.navigationController!.viewControllers {
- //普通用户
- if Defaults[\.userType] === 1{
- if temp.isKind(of: HomeSecondViewController.self){
- self.navigationController?.popToViewController(temp, animated: true)
- }
- }else{
- if temp.isKind(of: HomeViewController.self){
- self.navigationController?.popToViewController(temp, animated: true)
- }
- }
-
- }
-
- }, error: { error in
- self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
- })
- }
-
- //MARK: 获取支付配置数据
- func getPayConfiguration(){
- self.hud.showLoading()
- self.viewModel.signalGetPayConfiguration()?.on(success: { dd in
- self.clientSecret = self.viewModel.payConfiguration?.clientSecret
- self.merchantDisplayName = self.viewModel.payConfiguration?.merchantDisplayName
- self.hud.hidden()
- self.configurationPaymentSheet()
- }, error: { error in
- self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
- })
- }
-
- //MARK: 获取价格
- func getPriceWithType(){
- self.hud.showLoading()
- self.viewModel.getPriceWithTypeModel.shopcartId = self.viewModel.getShoppingCarMsgResultMeal.shopcartId
- self.viewModel.signalGetPriceWithTypeRequest()?.on(success: { dd in
- self.userPayTypeView?.priceLab.text = "\(self.viewModel.priceWithTypeModel?.price ?? "")"
- self.hud.hidden()
- }, error: { error in
- self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
- })
- }
-
- //MARK: 获取结算方式列表
- func getPaySettle(){
- self.hud.showLoading()
- self.viewModel.signalGetPaySettleType()?.on(success: { dd in
- self.paymentsSheetView?.configDataSource(dataSource: self.viewModel.paySettleList)
-
- //普通用默认全款 后台答应
- if Defaults[\.userType] === 1{
- self.paySetModel = self.viewModel.paySettleList![0]
- self.viewModel.paySetModel = self.paySetModel
- self.getPriceWithType()
- }
- self.hud.hidden()
- }, error: { error in
- self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
- })
- }
-
- //MARK: 获取支付方式列表
- func getPayMent(){
- self.hud.showLoading()
- self.viewModel.signalGetPayMentType()?.on(success: { dd in
- self.userPayTypeView?.configDataSource(dataSource: self.viewModel.payMentList)
- self.hud.hidden()
- }, error: { error in
- self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
- })
- }
-
- //MARK: 是否拉起支付 或者密码支付
- func getIsStripePay(){
-
- NotificationCenter.default.post(name: NSNotification.Name("刷新订单列表"), object: self, userInfo:nil)
-
- self.hud.showLoading()
- self.viewModel.getIsStripePayModel.orderId = self.viewModel.orderIdModel?.orderId
- self.viewModel.getIsStripePayModel.payTypeId = self.payMentModel?.id
-
- self.viewModel.signalGetIsStripePayRequest()?.on(success: { dd in
- let model : IsStripePayModel = self.viewModel.isStripePayModel!
- if model.pullUp === 1{
- self.getPayConfiguration()
- }else{
- self.pswPayView?.show()
- }
- NotificationCenter.default.post(name: NSNotification.Name("刷新首页"), object: self, userInfo:nil)
- self.hud.hidden()
- }, error: { error in
- self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
- })
- }
- // MARK: setTableViewHead
- func setTableViewHead(){
- var typeStr : String?
- if let _ = self.viewModel.ShopCarAllModelList{
- for i in 0..<self.viewModel.ShopCarAllModelList!.count{
- let model : ShopMealMsgModel = self.viewModel.ShopCarAllModelList![i]
- if typeStr.isEmptyStr{
- typeStr = "\(typeStr ?? "")\(model.supplyType ?? "")"
- }else{
- typeStr = "\(typeStr ?? "")/\(model.supplyType ?? "")"
- }
- }
- }
- self.headView?.typeLab.text = "\(typeStr ?? "")"
- self.headView?.whichDayLab.text = "\(self.nowTimeModel?.whichDay ?? "") (\(self.nowTimeModel?.shopcartTime ?? ""))"
- }
-
- //显示结算方式
- func setHeadViewPay(){
- self.headView?.setMeansOfPayments(model: self.paySetModel!)
- }
-
- //刷新headView数据
- func reloadHeadView(){
- self.headView?.configAddressModel(dateModel: self.addressModel)
- self.tableView.reloadData()
- }
-
- //刷新headView时间控件数据
- func reloadDateView(){
- self.headView!.configModel(dateModel: self.viewModel.TimeRangDetail!)
- }
- // MARK: 拉起支付
- func configurationPaymentSheet(){
-
- let paymentIntentClientSecret = self.clientSecret
- let publishableKey = "pk_test_51O3DvzBqBnSGwj1K0ePpneI04LzHX5e9JC0BYqLXfnEqhJJgaSdtUM7ppv3YaK0vTdJ5mUTSLoG84zIILjfsyglz00Cgl4haJ3"
-
- STPAPIClient.shared.publishableKey = publishableKey
- // MARK: Create a PaymentSheet instance
- var configuration = PaymentSheet.Configuration()
- configuration.merchantDisplayName = self.merchantDisplayName
- configuration.customer = .init(id: customerId ?? "", ephemeralKeySecret: customerEphemeralKeySecret ?? "")
-
- configuration.allowsDelayedPaymentMethods = true
- self.paymentSheet = PaymentSheet(paymentIntentClientSecret: self.paymentIntentClientSecret ?? "", configuration: configuration)
-
- self.didTapCheckoutButton()
- }
-
-
- func didTapCheckoutButton() {
- paymentSheet?.present(from: self) { paymentResult in
- // MARK: Handle the payment result
- switch paymentResult {
- case .completed:
- self.hud.showFailure(LanguagesUtil.createTextBy(Ctext: "支付成功", Etext: "payment success"))
- for temp in self.navigationController!.viewControllers {
- //普通用户
- if Defaults[\.userType] === 1{
- if temp.isKind(of: HomeSecondViewController.self){
- self.navigationController?.popToViewController(temp, animated: true)
- }
- }else{
- if temp.isKind(of: HomeViewController.self){
- self.navigationController?.popToViewController(temp, animated: true)
- }
- }
- }
- print("Your order is confirmed")
- case .canceled:
- self.hud.showFailure(LanguagesUtil.createTextBy(Ctext: "支付已取消", Etext: "payment has been cancelled"))
-
- print("Canceled!")
- case .failed(let error):
- print("Payment failed: \(error)")
- self.hud.showFailure("\(error)")
- }
- }
- }
- }
- extension CheckOrderViewController : UITableViewDelegate,UITableViewDataSource{
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return self.viewModel.ShopCarAllModelList?[section].shopMealMsgVos?.count ?? 0
- }
-
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: "OrderReadyCell") as! OrderReadyCell;
- let batchModel = self.viewModel.ShopCarAllModelList?[indexPath.section]
- let model = (batchModel?.shopMealMsgVos?[indexPath.row])!
-
- var isfirst = indexPath.row == 0 ? true : false
- cell.configModel(model: model, isfirstLine: isfirst)
- return cell
- }
-
- func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
- return 0.01
- }
-
- func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
- return 0.01
- }
- func numberOfSections(in tableView: UITableView) -> Int {
- return self.viewModel.ShopCarAllModelList?.count ?? 0
- }
- }
|