| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367 |
- //
- // PaymentViewController.swift
- // MTP2_iOS
- //
- // Created by 曹晓亮 on 2020/12/10.
- // Copyright © 2020 Muchinfo. All rights reserved.
- //
- import UIKit
- import WHToast
- import NVActivityIndicatorView
- import SwiftyAttributes
- import SwiftDate
- /// 支付收银台视图容器控制类
- class PaymentViewController: BaseViewController {
-
- // MARK: - 属性相关
- /// 支付按钮
- @IBOutlet weak var payment: UIButton!
- /// 支付金额
- @IBOutlet weak var amount: UILabel!
- /// 支付剩余时间
- @IBOutlet weak var timeDown: UILabel!
- /// 列表
- @IBOutlet weak var tableView: UITableView!
-
- /// cellIdentifier
- let cellIdentifier = "Payment_Cell"
-
- /// 支付方式
- var payWays: [(title: String, image: UIImage, key: Int)] {
- get {
- /// 异常
- guard let accountManager = MTP2BusinessCore.shared.accountManager,
- let constants = accountManager.enums?.filter({$0.enumdiccode == "cashpaymode"}) else {
- return []
- }
- /// 终端配置
- let dics = ConfigUtils.getValue(key: .payWay) as? Array<String>
-
- var ways: [(title: String, image: UIImage, key: Int)] = []
- constants.forEach({ (obj) in
- if dics?.contains(where: {$0 == "\(obj.enumitemname)"}) ?? false {
- if obj.enumitemname == 1 || obj.enumitemname == 2 { /// 微信
- ways.append((title: obj.enumdicname, image: UIImage(named: "payment_wechat")!, key: obj.enumitemname))
- } else if obj.enumitemname == 3 || obj.enumitemname == 4 { /// 支付宝
- ways.append((title: obj.enumdicname, image: UIImage(named: "payment_alipay")!, key: obj.enumitemname))
- } else if obj.enumitemname == 7 { /// apple pay
- ways.append((title: obj.enumdicname, image: UIImage(named: "payment_applepay")!, key: obj.enumitemname))
- } else {
- ways.append((title: obj.enumdicname, image: UIImage(named: "payment_quick")!, key: obj.enumitemname))
- }
- }
- })
- return ways
- }
- }
- /// 当前选中的支付方式
- var payWay: (title: String, image: UIImage, key: Int)?
- /// 待付款单据
- var myPayOrder: MoMyPayOrders? {
- didSet {}
- }
- /// 系统时间戳
- var systemTime: String? {
- didSet {
- /// 初始化定时器
- self.initTimer()
- }
- }
- /// 倒计时
- var timer: Timer?
- /// 计时器
- var count = 0.0
- // MARK: - 生命周期相关
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do any additional setup after loading the view.
- /// UI界面初始化
- buildView()
- }
-
- deinit {
- /// 定时器失效
- timer?.invalidate()
- timer = nil
- }
-
- override func viewWillAppear(_ animated: Bool) {
- super.viewWillAppear(animated)
- /// 隐藏导航栏
- self.navigationController?.setNavigationBarHidden(false, animated: true)
- }
-
- // MARK: - 初始化相关
- /// UI界面初始化
- fileprivate func buildView() {
- /// 异常
- guard let obj = myPayOrder else {
- return
- }
- /// 支付金额
- self.amount.attributedText = ("\(obj.currencysign) ".withFont(.font_14)+"\(obj.payamount)".withFont(.font_22)).withTextColor(UIColorFromHex(rgbValue: 0xdf5958))
- /// 刷新列表
- tableView.reloadData()
- /// 获取系统世间
- self.requestGetSystemTime()
- }
-
- // MARK: - 交互相关
- /// 按钮点击响应交互事件
- /// - Parameter sender: sender
- @IBAction fileprivate func onButtonPressed(_ sender: UIControl) {
- switch sender {
- case payment:
- /// 未选择支付渠道
- guard let way = self.payWay,
- let obj = myPayOrder else {
- WHToast.showError(withMessage: "请选择支付渠道", duration: 1.5, finishHandler: {})
- return
- }
- doPayment(EPayWay(rawValue: way.key)!, obj.tradeid)
- default:
- break
- }
- }
-
- // MARK: - 倒计时相关
- /// 初始化定时器
- fileprivate func initTimer() {
- if self.timer != nil {
- self.timer?.invalidate()
- self.timer = nil
- }
-
- /// 开始计时
- self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.calculateTimeDown), userInfo: nil, repeats: true)
- self.timer?.fire()
- /// 滚动时失效
- RunLoop.current.add(self.timer!, forMode: .common)
- }
-
- /// 倒计时计算
- @objc fileprivate func calculateTimeDown() {
- /// 异常
- guard let obj = myPayOrder,
- let paylimitedtime = DateUtils.getTDateString(obj.paylimitedtime, "yyyy-MM-dd HH:mm:ss").date(formatter: "yyyy-MM-dd HH:mm:ss"),
- let sysTime = self.systemTime?.date(formatter: "yyyy-MM-dd HH:mm:ss"),
- let dateComponents = DateUtils.diffs(paylimitedtime.timeIntervalSinceNow, sysTime.timeIntervalSinceNow-28800.0, count) else { return }
-
- /// 格式化
- let hour = abs(dateComponents.hour ?? 0), hourStr = hour < 10 ? "0\(hour)" : "\(hour)"
- let minute = abs(dateComponents.minute ?? 0), minuteStr = minute < 10 ? "0\(minute)" : "\(minute)"
- let second = abs(dateComponents.second ?? 0), secondStr = second < 10 ? "0\(second)" : "\(second)"
-
- /// 倒计时
- timeDown.text = "支付剩余时间 \(hourStr):\(minuteStr):\(secondStr)"
- /// 计数器
- count += 1.0
- /// 重新去请求商品数据信息
- if dateComponents.hour == 0,
- dateComponents.minute == 0,
- dateComponents.second == 0 {
- WHToast.showMessage("订单已超时", duration: 1.5, finishHandler: {
- self.navigationController?.popViewController(animated: true)
- })
- }
- }
-
- // MARK: - 微信支付
- /// 构建微信支付请求参数
- /// - Parameter payChannel: 支付类型
- fileprivate func buildPayParmaert(_ way: EPayWay, _ param: MoPayParam?) {
- /// "请求支付参数错误!"
- guard let _ = param else {
- WHToast.showError(withMessage: "请求支付参数错误!", duration: 1.5, finishHandler: {})
- return
- }
-
- let dic: NSMutableDictionary = NSMutableDictionary()
- dic.setValue(param?.appPayRequest ?? "", forKey: "appPayRequest")
- switch way {
- case .WeChat, .WeChatUni: /// 微信支付
- self.sendWeiXinPayRequest(dic as NSDictionary?)
- case .AliPay, .AliUniPay: /// 支付宝支付
- self.sendAlipayRequest(dic as NSDictionary?)
- default: /// 云闪付支付
- self.sendUnifyQuickPayRequest(dic as NSDictionary?)
- }
- }
-
- /// 微信支付请求
- /// - Parameter response: response
- fileprivate func sendWeiXinPayRequest(_ response: NSDictionary?) {
- if (response?["appPayRequest"] != nil) {
- /// 前去支付
- UMSPPPayUnifyPayPlugin.pay(withPayChannel: CHANNEL_WEIXIN, payData: response?["appPayRequest"] as? String) { (resultCode, resultInfo) in
- DispatchQueue.main.async {
- if resultCode == "0000" {
- self.navigationController?.popViewController(animated: true)
- } else {
- let data = resultInfo?.data(using: .utf8)
- let dic = (try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)) as? NSDictionary
- let msg = dic?["resultMsg"] as? String
- WHToast.showMessage("\(msg ?? "未知错误")", duration: 2.0, finishHandler: {})
- }
- }
- }
- }
- }
-
- /// 支付宝支付请求
- /// - Parameter response: response
- fileprivate func sendAlipayRequest(_ response: NSDictionary?) {
- if (response?["appPayRequest"] != nil) {
- /// 发送请求
- UMSPPPayUnifyPayPlugin.pay(withPayChannel: CHANNEL_ALIMINIPAY, payData: response?["appPayRequest"] as? String) { (resultCode, resultInfo) in
- if resultCode == "1003" {
- DispatchQueue.main.async {
- if resultCode == "0000" {
- self.navigationController?.popViewController(animated: true)
- } else {
- WHToast.showMessage("resultCode = \(resultCode ?? "")\nresultInfo = \(resultInfo ?? "")", duration: 1.5, finishHandler: {})
- }
- }
- }
- }
- }
- }
-
- /// 银闪付支付请求
- /// - Parameter response: response
- fileprivate func sendUnifyQuickPayRequest(_ response: NSDictionary?) {
- if (response?["appPayRequest"] != nil) {
- /// 发送请求
- UMSPPPayUnifyPayPlugin.cloudPay(withURLSchemes: "haishangbaoyeunifypay", payData: response?["appPayRequest"] as? String, viewController: self) { (resultCode, resultInfo) in
- DispatchQueue.main.async {
- if resultCode == "0000" {
- self.navigationController?.popViewController(animated: true)
- } else {
- let data = resultInfo?.data(using: .utf8)
- let dic = (try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)) as? NSDictionary
- let msg = dic?["resultMsg"] as? String
- WHToast.showMessage("\(msg ?? "未知错误")", duration: 1.5, finishHandler: {})
- }
- }
- }
- }
- }
-
- // MARK: - 接口请求
- /// 支付请求响应方法
- fileprivate func doPayment(_ payWay: EPayWay, _ orderNo: String) {
- /// 异常
- guard let bankManager = MTP2BusinessCore.shared.bankManager,
- let accountManager = MTP2BusinessCore.shared.accountManager,
- let payOrder = myPayOrder,
- let accountName = accountManager.moAccountBaseInfo?.accountInfo.accountName else {
- return
- }
-
- /// 开启Loading
- NVActivityIndicatorPresenter.sharedInstance.startAnimating(ActivityData(message: "支付中......".localized, type: .ballClipRotate, color: UIColorFromHex(rgbValue: 0xA8B6CC)), NVActivityIndicatorView.DEFAULT_FADE_IN_ANIMATION)
-
- /// 请求生成下单参数
- bankManager.requestQuickPay(payOrder.marketid, payOrder.tradeid, Date().getString(formatter: "yyyy-MM-dd"), payOrder.payamount, payWay, accountName) { (isComplete, error, param) in
- DispatchQueue.main.async {
- /// stop loding.....
- NVActivityIndicatorPresenter.sharedInstance.stopAnimating(NVActivityIndicatorView.DEFAULT_FADE_OUT_ANIMATION)
- if isComplete,
- param?.errCode == "SUCCESS" {
- /// 构建支付参数
- self.buildPayParmaert(payWay, param)
- } else {
- WHToast.showError(withMessage: "支付失败,原因:\(param?.errMsg ?? "未知错误。")", duration: 1.5, finishHandler: {})
- }
- }
- }
- }
-
- /// 获取系统世间
- fileprivate func requestGetSystemTime() {
- /// 异常
- guard let accountManager = MTP2BusinessCore.shared.accountManager else {
- return
- }
- /// 获取系统世间
- accountManager.requestGetServerTime { (isComplete, error, time) in
- DispatchQueue.main.async {
- if isComplete {
- /// 初始化定时器
- self.systemTime = time ?? Date().description
- } else { /// 获取失败
- WHToast.showError(withMessage: "获取系统时间失败!", duration: 1.5, finishHandler: {
- self.navigationController?.popViewController(animated: true)
- })
- }
- }
- }
- }
- }
- extension PaymentViewController: UITableViewDelegate, UITableViewDataSource {
-
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return payWays.count
- }
-
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! PaymentCell
- /// 回调
- cell.block = { (_ model: (title: String, image: UIImage, key: Int)?) in
- /// 选中的支付方式
- self.payWay = model
- }
- cell.model = payWays[indexPath.row]
- return cell
- }
-
- func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
- return 60.0
- }
-
- func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- for (index, obj) in tableView.visibleCells.enumerated() {
- (obj as! PaymentCell).isCheck = index == indexPath.row
- }
- }
- }
- class PaymentCell: BaseTableViewCell<(title: String, image: UIImage, key: Int)> {
- /// 类型
- @IBOutlet weak var typeImage: UIImageView!
- /// 支付名称
- @IBOutlet weak var titleLabel: UILabel!
- /// 类型
- @IBOutlet weak var checkImage: UIImageView!
- /// 是否选中
- var isCheck: Bool = false {
- didSet {
- checkImage.isHidden = !isCheck
- /// 执行回调
- if let callBack = block, isCheck {
- callBack(model)
- }
- }
- }
- /// 数据模型
- override var model: (title: String, image: UIImage, key: Int)? {
- didSet {
- guard let obj = model else {
- return
- }
- /// 支付名称
- titleLabel.text = obj.title
- /// 类型
- typeImage.image = obj.image
- }
- }
-
- /// 回调块
- var block: ((_ model: (title: String, image: UIImage, key: Int)?) -> Void)?
- }
|