CheckOrderViewController.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. //
  2. // CheckOrderViewController.swift
  3. // ADHTuanCan
  4. //
  5. // Created by 敖德亨 on 2023/10/31.
  6. //
  7. import UIKit
  8. import RxSwift
  9. import RxCocoa
  10. //import Stripe
  11. import SwiftyUserDefaults
  12. import StripePaymentSheet
  13. class CheckOrderViewController: ADHBaseVC {
  14. /// 1为普团,2为白团
  15. var shopType : String?{
  16. didSet{
  17. self.viewModel.HomeTimeGetModel.shopType = shopType
  18. self.viewModel.getPaySettleTypeModel.type = self.shopType
  19. self.viewModel.getPayPayMentTypeModel.type = self.shopType
  20. }
  21. }
  22. /// 购物车id
  23. var shopcartId : NSNumber?{
  24. didSet{
  25. self.viewModel.getShoppingCarMsgResultMeal.shopcartId = shopcartId
  26. self.viewModel.getDefualAddressModel.shopcartId = shopcartId
  27. }
  28. }
  29. /// 购物时间id
  30. var shopcartTimeId : NSNumber?{
  31. didSet{
  32. self.viewModel.getShoppingCarMsgResultMeal.shopcartTimeId = shopcartTimeId
  33. }
  34. }
  35. var orderId : NSNumber?
  36. @IBOutlet weak var blackView: UIView!
  37. @IBOutlet weak var tableView: UITableView!
  38. @IBOutlet weak var topConst: NSLayoutConstraint!
  39. @IBOutlet weak var shopCar: UIView!
  40. @IBOutlet weak var priceLab: UILabel!
  41. var addressModel : AddressModel?
  42. var paymentSheet: PaymentSheet?
  43. let backendCheckoutUrl = URL(string: "Your backend endpoint")!
  44. /// 结算方式
  45. var paySetModel : PaySettleTypeModel?
  46. /// 支付方式Model
  47. var payMentModel : PayMentTypeModel?
  48. var clientSecret : String!
  49. var merchantDisplayName : String!
  50. var customerId : String?
  51. var customerEphemeralKeySecret : String?
  52. var paymentIntentClientSecret : String?
  53. @IBAction func goToPayAction(_ sender: UIButton) {
  54. if self.paySetModel != nil{
  55. self.userPayTypeView?.show()
  56. }else{
  57. self.hud.showFailure(LanguagesUtil.createTextBy(Ctext: "请先选择结算方式", Etext: "Please select the payment method first"))
  58. }
  59. }
  60. /// 当前选择的时间
  61. var nowTimeModel : HomeTimeItem?
  62. let viewModel : ShoppingCarViewModel = ShoppingCarViewModel.init()
  63. let diposableBag = DisposeBag()
  64. let headView = Bundle.main.loadNibNamed("CheckOrderHeadView", owner: nil, options: nil)?.last as? CheckOrderHeadView
  65. let addrView = Bundle.main.loadNibNamed("selectAddressView", owner: nil, options: nil)?.last as? selectAddressView
  66. let footView = Bundle.main.loadNibNamed("CheckOrderFootView", owner: nil, options: nil)?.last as? CheckOrderFootView
  67. ///结算方式
  68. let paymentsSheetView = Bundle.main.loadNibNamed("PayMentSelectView", owner: nil, options: nil)?.last as? PayMentSelectView
  69. ///支付方式
  70. let userPayTypeView = Bundle.main.loadNibNamed("UserPayMentSheet", owner: nil, options: nil)?.last as? UserPayMentSheet
  71. /// 密码支付View
  72. let pswPayView = Bundle.main.loadNibNamed("PswPayView", owner: nil, options: nil)?.last as? PswPayView
  73. override func viewDidLoad() {
  74. super.viewDidLoad()
  75. // self.view.backgroundColor = kThemeBlackColor
  76. self.blackView.backgroundColor = kThemeBlackColor
  77. self.navBar = MCNavBarView.init(title: LanguagesUtil.createTextBy(Ctext: "确认订单", Etext: "Confirm order"), subTitle: nil)
  78. self.navBarHeightConstraint? = self.topConst
  79. self.getPaySettle()
  80. self.getPayMent()
  81. self.getDefualAddress()
  82. self.getTimeRangDetail()
  83. self.getShopCarDetail()
  84. self.createUI()
  85. }
  86. //MARK: createUI
  87. func createUI(){
  88. _ = NotificationCenter.default.rx.notification(Notification.Name(rawValue: "刷新确认订单收货人")).takeUntil(self.rx.deallocated).subscribe(onNext:{[weak self] (notification) in
  89. self?.getDefualAddress()
  90. })
  91. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  92. self.tableView.register(withType: OrderReadyCell.self)
  93. self.tableView.tableHeaderView = self.headView
  94. self.tableView.tableFooterView = self.footView
  95. //切换日期
  96. self.headView?.selectBlock = {[weak self] model in
  97. self?.nowTimeModel = model
  98. self?.viewModel.getShoppingCarMsgResultMeal.shopcartTimeId = model.shopcartTimeId
  99. self?.getShopCarDetail()
  100. self?.reloadDateView()
  101. }
  102. //添加地址
  103. self.headView?.addAddressBlock = {[weak self] in
  104. let vc = AddressEditorVC()
  105. self?.navigationController?.pushViewController(vc, animated: true)
  106. }
  107. //修改地址地址
  108. self.headView?.changeAddressBlock = {[weak self] in
  109. self?.addrView?.show()
  110. }
  111. //点击修改结算方式
  112. self.headView?.payMentTouchBlock = {[unowned self] in
  113. self.paymentsSheetView?.show()
  114. }
  115. //刷新结算方式显示
  116. self.paymentsSheetView?.meansOfPaymentsBlock = {[unowned self] mode in
  117. self.paySetModel = mode
  118. self.viewModel.paySetModel = self.paySetModel
  119. self.setHeadViewPay()
  120. self.getPriceWithType()
  121. }
  122. //去支付
  123. self.userPayTypeView?.payTypeBlock = {[unowned self] model in
  124. self.payMentModel = model
  125. self.viewModel.payMentModel = self.payMentModel
  126. self.buildingOrder()
  127. }
  128. //密码支付
  129. self.pswPayView?.pswPayBlock = {[weak self] str in
  130. self?.pswPayAction(psw: str)
  131. }
  132. //选择地址保存
  133. self.addrView?.saveBlock = {[weak self] model in
  134. self?.addressModel = model
  135. self?.reloadHeadView()
  136. }
  137. //去添加地址
  138. self.addrView?.addAddressBlock = {[weak self] in
  139. let vc = AddressEditorVC()
  140. vc.shopcartId = self?.viewModel.TimeRangDetail?.shopcartId
  141. self?.navigationController?.pushViewController(vc, animated: true)
  142. }
  143. //去修改地址 shopcartId绑定购物车的地址
  144. self.addrView?.editAddressBlock = {[unowned self] model in
  145. self.addressModel = model
  146. self.addressModel?.shopcartId = self.viewModel.TimeRangDetail?.shopcartId
  147. let vc = AddressEditorVC()
  148. vc.configDefualData(model: self.addressModel!)
  149. self.navigationController?.pushViewController(vc, animated: true)
  150. }
  151. self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[unowned self] in
  152. //获取详情
  153. self.getShopCarDetail()
  154. });
  155. }
  156. //MARK: 获取默认地址
  157. func getDefualAddress(){
  158. self.hud.showLoading()
  159. self.viewModel.signalGetDefualAdd()?.on(success: { dd in
  160. self.addressModel = self.viewModel.defualAddressModel
  161. self.reloadHeadView()
  162. self.hud.hidden()
  163. }, error: { error in
  164. self.hud.showFailure(LanguagesUtil.createTextBy(Ctext: "获取地址失败", Etext: "Failed to get address"))
  165. })
  166. }
  167. //MARK: 获取时间范围
  168. func getTimeRangDetail(){
  169. self.hud.showLoading()
  170. self.viewModel.signalGetHomeTime()?.on(success: { dd in
  171. for item in self.viewModel.TimeRangDetail!.timeVoList! {
  172. let model : HomeTimeItem = item
  173. if model.day == self.nowTimeModel?.day{
  174. model.isSelect = true
  175. }
  176. }
  177. self.getShopCarPrice()
  178. self.reloadDateView()
  179. self.hud.hidden()
  180. }, error: { error in
  181. self.hud.showFailure(LanguagesUtil.createTextBy(Ctext: "获取时间范围失败", Etext: "Failed to obtain the time range. Procedure"))
  182. })
  183. }
  184. //MARK: 获取购物车价格详情
  185. func getShopCarPrice(){
  186. self.viewModel.getShopCarPriceRModel.id = self.viewModel.TimeRangDetail?.shopcartId
  187. self.viewModel.signalGetShopCarPrice()?.on(success: { dd in
  188. self.priceLab.text = "\(self.viewModel.shopCarPriceDetail?.price ?? "")"
  189. }, error: { error in
  190. self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
  191. })
  192. }
  193. //MARK: 获取日期下购物车详情
  194. func getShopCarDetail(){
  195. self.hud.showLoading()
  196. self.viewModel.signalgetShoppingCarMsg()?.on(success: { dd in
  197. self.tableView.reloadData()
  198. self.setTableViewHead()
  199. self.hud.hidden()
  200. self.tableView.mj_header.endRefreshing()
  201. }, error: { error in
  202. self.tableView.mj_header.endRefreshing()
  203. self.tableView.mj_header.endRefreshing()
  204. })
  205. }
  206. //MARK: 生成订单
  207. func buildingOrder(){
  208. if self.viewModel.orderIdModel != nil{
  209. self.self.getIsStripePay()
  210. return
  211. }
  212. self.hud.showLoading()
  213. self.viewModel.addOrderModel.addressId = self.addressModel?.id
  214. self.viewModel.addOrderModel.shopcartId = self.viewModel.getShoppingCarMsgResultMeal.shopcartId
  215. self.viewModel.addOrderModel.userType = self.shopType
  216. self.viewModel.signalAddOrderRequest()?.on(success: { dd in
  217. self.orderId = self.viewModel.orderIdModel?.orderId
  218. self.viewModel.getPayConfigurationModel.orderId = self.orderId
  219. self.getIsStripePay()
  220. self.hud.hidden()
  221. }, error: { error in
  222. self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
  223. })
  224. }
  225. //MARK: 密码支付
  226. func pswPayAction(psw : String!){
  227. self.hud.showLoading()
  228. self.viewModel.pswPayModel.orderId = self.orderId
  229. self.viewModel.pswPayModel.payPassword = psw
  230. self.viewModel.signalPSWPay()?.on(success: { dd in
  231. self.hud.showFailure(LanguagesUtil.createTextBy(Ctext: "支付成功", Etext: "payment success"))
  232. NotificationCenter.default.post(name: NSNotification.Name("刷新个人中心"), object: self, userInfo:nil)
  233. for temp in self.navigationController!.viewControllers {
  234. //普通用户
  235. if Defaults[\.userType] === 1{
  236. if temp.isKind(of: HomeSecondViewController.self){
  237. self.navigationController?.popToViewController(temp, animated: true)
  238. }
  239. }else{
  240. if temp.isKind(of: HomeViewController.self){
  241. self.navigationController?.popToViewController(temp, animated: true)
  242. }
  243. }
  244. }
  245. }, error: { error in
  246. self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
  247. })
  248. }
  249. //MARK: 获取支付配置数据
  250. func getPayConfiguration(){
  251. self.hud.showLoading()
  252. self.viewModel.signalGetPayConfiguration()?.on(success: { dd in
  253. self.clientSecret = self.viewModel.payConfiguration?.clientSecret
  254. self.merchantDisplayName = self.viewModel.payConfiguration?.merchantDisplayName
  255. self.hud.hidden()
  256. self.configurationPaymentSheet()
  257. }, error: { error in
  258. self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
  259. })
  260. }
  261. //MARK: 获取价格
  262. func getPriceWithType(){
  263. self.hud.showLoading()
  264. self.viewModel.getPriceWithTypeModel.shopcartId = self.viewModel.getShoppingCarMsgResultMeal.shopcartId
  265. self.viewModel.signalGetPriceWithTypeRequest()?.on(success: { dd in
  266. self.userPayTypeView?.priceLab.text = "\(self.viewModel.priceWithTypeModel?.price ?? "")"
  267. self.hud.hidden()
  268. }, error: { error in
  269. self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
  270. })
  271. }
  272. //MARK: 获取结算方式列表
  273. func getPaySettle(){
  274. self.hud.showLoading()
  275. self.viewModel.signalGetPaySettleType()?.on(success: { dd in
  276. self.paymentsSheetView?.configDataSource(dataSource: self.viewModel.paySettleList)
  277. //普通用默认全款 后台答应
  278. if Defaults[\.userType] === 1{
  279. self.paySetModel = self.viewModel.paySettleList![0]
  280. self.viewModel.paySetModel = self.paySetModel
  281. self.getPriceWithType()
  282. }
  283. self.hud.hidden()
  284. }, error: { error in
  285. self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
  286. })
  287. }
  288. //MARK: 获取支付方式列表
  289. func getPayMent(){
  290. self.hud.showLoading()
  291. self.viewModel.signalGetPayMentType()?.on(success: { dd in
  292. self.userPayTypeView?.configDataSource(dataSource: self.viewModel.payMentList)
  293. self.hud.hidden()
  294. }, error: { error in
  295. self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
  296. })
  297. }
  298. //MARK: 是否拉起支付 或者密码支付
  299. func getIsStripePay(){
  300. NotificationCenter.default.post(name: NSNotification.Name("刷新订单列表"), object: self, userInfo:nil)
  301. self.hud.showLoading()
  302. self.viewModel.getIsStripePayModel.orderId = self.viewModel.orderIdModel?.orderId
  303. self.viewModel.getIsStripePayModel.payTypeId = self.payMentModel?.id
  304. self.viewModel.signalGetIsStripePayRequest()?.on(success: { dd in
  305. let model : IsStripePayModel = self.viewModel.isStripePayModel!
  306. if model.pullUp === 1{
  307. self.getPayConfiguration()
  308. }else{
  309. self.pswPayView?.show()
  310. }
  311. NotificationCenter.default.post(name: NSNotification.Name("刷新首页"), object: self, userInfo:nil)
  312. self.hud.hidden()
  313. }, error: { error in
  314. self.hud.showFailure(error.msg ?? LanguagesUtil.createTextBy(Ctext: "网络错误", Etext: "network error"))
  315. })
  316. }
  317. // MARK: setTableViewHead
  318. func setTableViewHead(){
  319. var typeStr : String?
  320. if let _ = self.viewModel.ShopCarAllModelList{
  321. for i in 0..<self.viewModel.ShopCarAllModelList!.count{
  322. let model : ShopMealMsgModel = self.viewModel.ShopCarAllModelList![i]
  323. if typeStr.isEmptyStr{
  324. typeStr = "\(typeStr ?? "")\(model.supplyType ?? "")"
  325. }else{
  326. typeStr = "\(typeStr ?? "")/\(model.supplyType ?? "")"
  327. }
  328. }
  329. }
  330. self.headView?.typeLab.text = "\(typeStr ?? "")"
  331. self.headView?.whichDayLab.text = "\(self.nowTimeModel?.whichDay ?? "") (\(self.nowTimeModel?.shopcartTime ?? ""))"
  332. }
  333. //显示结算方式
  334. func setHeadViewPay(){
  335. self.headView?.setMeansOfPayments(model: self.paySetModel!)
  336. }
  337. //刷新headView数据
  338. func reloadHeadView(){
  339. self.headView?.configAddressModel(dateModel: self.addressModel)
  340. self.tableView.reloadData()
  341. }
  342. //刷新headView时间控件数据
  343. func reloadDateView(){
  344. self.headView!.configModel(dateModel: self.viewModel.TimeRangDetail!)
  345. }
  346. // MARK: 拉起支付
  347. func configurationPaymentSheet(){
  348. let paymentIntentClientSecret = self.clientSecret
  349. let publishableKey = "pk_test_51O3DvzBqBnSGwj1K0ePpneI04LzHX5e9JC0BYqLXfnEqhJJgaSdtUM7ppv3YaK0vTdJ5mUTSLoG84zIILjfsyglz00Cgl4haJ3"
  350. STPAPIClient.shared.publishableKey = publishableKey
  351. // MARK: Create a PaymentSheet instance
  352. var configuration = PaymentSheet.Configuration()
  353. configuration.merchantDisplayName = self.merchantDisplayName
  354. configuration.customer = .init(id: customerId ?? "", ephemeralKeySecret: customerEphemeralKeySecret ?? "")
  355. configuration.allowsDelayedPaymentMethods = true
  356. self.paymentSheet = PaymentSheet(paymentIntentClientSecret: self.paymentIntentClientSecret ?? "", configuration: configuration)
  357. self.didTapCheckoutButton()
  358. }
  359. func didTapCheckoutButton() {
  360. paymentSheet?.present(from: self) { paymentResult in
  361. // MARK: Handle the payment result
  362. switch paymentResult {
  363. case .completed:
  364. self.hud.showFailure(LanguagesUtil.createTextBy(Ctext: "支付成功", Etext: "payment success"))
  365. for temp in self.navigationController!.viewControllers {
  366. //普通用户
  367. if Defaults[\.userType] === 1{
  368. if temp.isKind(of: HomeSecondViewController.self){
  369. self.navigationController?.popToViewController(temp, animated: true)
  370. }
  371. }else{
  372. if temp.isKind(of: HomeViewController.self){
  373. self.navigationController?.popToViewController(temp, animated: true)
  374. }
  375. }
  376. }
  377. print("Your order is confirmed")
  378. case .canceled:
  379. self.hud.showFailure(LanguagesUtil.createTextBy(Ctext: "支付已取消", Etext: "payment has been cancelled"))
  380. print("Canceled!")
  381. case .failed(let error):
  382. print("Payment failed: \(error)")
  383. self.hud.showFailure("\(error)")
  384. }
  385. }
  386. }
  387. }
  388. extension CheckOrderViewController : UITableViewDelegate,UITableViewDataSource{
  389. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  390. return self.viewModel.ShopCarAllModelList?[section].shopMealMsgVos?.count ?? 0
  391. }
  392. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  393. let cell = tableView.dequeueReusableCell(withIdentifier: "OrderReadyCell") as! OrderReadyCell;
  394. let batchModel = self.viewModel.ShopCarAllModelList?[indexPath.section]
  395. let model = (batchModel?.shopMealMsgVos?[indexPath.row])!
  396. var isfirst = indexPath.row == 0 ? true : false
  397. cell.configModel(model: model, isfirstLine: isfirst)
  398. return cell
  399. }
  400. func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  401. return 0.01
  402. }
  403. func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
  404. return 0.01
  405. }
  406. func numberOfSections(in tableView: UITableView) -> Int {
  407. return self.viewModel.ShopCarAllModelList?.count ?? 0
  408. }
  409. }