CNLiveShopPayController.swift 11.2 KB
//
//  CNLiveShopPayController.swift
//  metaCode
//
//  Created by zx on 2024/4/8.
//  支付页面

import Foundation
import CNLivePayCostModule

///支付类型
enum CNLivePayType {
    //支付宝
    case alipay
    //微信
    case weChat
}
//支付状态
enum CNLivePayResult {
    //成功
    case success
    //失败
    case failure
    //取消支付
    case cancel
}

//支付完成回调
typealias FinishPayCallBack = (_ orderInfoModel:CNLivePayOrderInfoModel,_ payType:CNLivePayType,_ payResult:CNLivePayResult)->Void

class CNLiveShopPayController:CNLiveBaseViewController,UITableViewDelegate,UITableViewDataSource{
    
    var finishPayCallBack:FinishPayCallBack?
    var orderNumber:String
    var orderInfoModel:CNLivePayOrderInfoModel?
    var currentSeleWechat = true
    var wechatIsInstall = true //微信是否安装
    var alipayIsInstall = true //支付宝是否安装
    var payType:CNLivePayType?
    
    let kCNLiveShopPayNeedPaymentCellIdentifier = "kCNLiveShopPayNeedPaymentCellIdentifier"
    let kCNLiveShopPayWeChatAlipayCellIdentifier = "kCNLiveShopPayWeChatAlipayCellIdentifier"
    
    // MARK: - 懒加载
    lazy var tableView : UITableView = {
        let tableView = UITableView(frame: CGRect(x: 0, y: KNavigationHeight, width: KSreenWidth, height: KSreenHeight-KNavigationHeight-KTabBarHeight), style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .singleLine
        tableView.tableFooterView = UIView.init()
        tableView.register(CNLiveShopPayNeedPaymentCell.self, forCellReuseIdentifier: kCNLiveShopPayNeedPaymentCellIdentifier)
        tableView.register(CNLiveShopPayWeChatAlipayCell.self, forCellReuseIdentifier: kCNLiveShopPayWeChatAlipayCellIdentifier)
        return tableView
    }()
    
    lazy var payBtn: UIButton = {
        let  payBtn = UIButton(type: .custom)
        payBtn.frame = CGRect(x: 0, y: self.tableView.bottom, width: KSreenWidth, height: KTabBarHeight)
        payBtn.backgroundColor = UIColor(red:0.29, green:0.64, blue:0.25, alpha:1.00)
        payBtn.setTitleColor(.white, for: .normal)
        payBtn.setTitle("支付", for: .normal)
        payBtn.addTarget(self, action: #selector(payBtnAction), for: .touchUpInside)
        return payBtn
    }()

    
    init(orderNumber:String) {
        self.orderNumber = orderNumber
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBarHidden = false
        titleName = "收银台"
        self.view.backgroundColor = .white
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActiveNotification(_:)), name: UIApplication.didBecomeActiveNotification, object: nil)
        self.getOrderInfoMessage()
        self.initUI()
        
        if WXApi.isWXAppInstalled(){
            self.wechatIsInstall = true
        }else{
            self.wechatIsInstall = false
        }
        
        let urlScheme = "alipay://"
        if UIApplication.shared.canOpenURL(URL(string: urlScheme)!) {
            self.alipayIsInstall = true
        } else {
            self.alipayIsInstall = false
        }
        
    }
    // MARK: - 获取订单信息 并且进行检测
    func getOrderInfoMessage(){
        if self.orderNumber.count == 0{
            return
        }
        showLoading(message: "")
        CNLiveShoph5ViewModel.postOrderPayWithParams(orderId: self.orderNumber) { result, status in
            hiddenLoading()
            if status == .success{
                let orderInfoModel = result as! CNLivePayOrderInfoModel
                self.orderInfoModel = orderInfoModel
                self.tableView.reloadData()
            }else{
            }
        }
        
    }
    
    func initUI(){
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.payBtn)
    }
    
    @objc func payBtnAction(){
        
        if self.currentSeleWechat == true && self.wechatIsInstall == false{
            showMessage(message: "请安装微信")
            return
        }
        if self.currentSeleWechat == false && self.alipayIsInstall == false{
            showMessage(message: "请安装支付宝")
            return
        }
        showLoading(message: "")
        let orderId = self.orderInfoModel?.orderId
        var userId = self.orderInfoModel?.user_id
        if userId?.count == 0{
            userId = UserInfoManager.shared.userInfo.uid
        }
        let descStr = self.orderInfoModel?.body
        let price = self.orderInfoModel?.totalMoney
        let body = self.orderInfoModel?.body
        let coupon_fee = self.orderInfoModel?.couponMoney
        let notifyUrl = self.orderInfoModel?.notify_url
        
        let paramDict = NSMutableDictionary()
        paramDict.setValue(orderId, forKey: "orderId")
        paramDict.setValue(userId, forKey: "user_id")
        paramDict.setValue(descStr, forKey: "descStr")
        paramDict.setValue(price, forKey: "price")
        paramDict.setValue("1", forKey: "orderType")
        paramDict.setValue("1", forKey: "type")
        paramDict.setValue(body, forKey: "body")
        paramDict.setValue(coupon_fee, forKey: "coupon_fee")
        paramDict.setValue(notifyUrl, forKey: "notifyUrl")
        paramDict.setValue("", forKey: "password")
        
        var payCostType:CNLivePayCostPayType?
        if self.currentSeleWechat == true{
            self.payType = .weChat
            payCostType = CNLivePayCostPayTypeWeChatPay
        }else{
            self.payType = .alipay
            payCostType = CNLivePayCostPayTypeAliPay
        }
        
        CNLivePayCostModule.showShopPayViw(withParamDict: paramDict as! [String : Any], payType: payCostType!) { resultCode in
            hiddenLoading()
            if resultCode == 0{
                self.checkPayIsSuccessful(lastCount: 5)
            }else if resultCode == 3{
                showMessage(message: "取消支付")
            }else {
                showMessage(message: "支付失败")
            }
        }
        
    }
    
    @objc func didBecomeActiveNotification(_ notification: Notification) {
        // 处理应用变得活跃的逻辑
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            // 这里写你想要在 0.5 秒后执行的代码
            self.checkPayIsSuccessful(lastCount: 0)
        }
        
    }
    
    // MARK: - 检测是否支付成功
    /// 检测是否支付成功
    /// @param lastCount 剩余检测次数
    func checkPayIsSuccessful(lastCount:NSInteger){
        showLoading(message: "")
        CNLiveShoph5ViewModel.postIsOrderPayWithOrderId(orderId: self.orderNumber) { result, status in
            hiddenLoading()
            if status == .success{
                self.finishPayCallBack?(self.orderInfoModel!, self.payType!, .success)
//                NotificationCenter.default.post(name: <#T##NSNotification.Name#>, object: <#T##Any?#>)//kDSSuccessPayOrderNotification
            }else{
                if lastCount > 0{
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        // 这里写你想要在 0.5 秒后执行的代码
                        self.checkPayIsSuccessful(lastCount: lastCount-1)
                    }
                }
            }
        }
        
    }
    
    // MARK: - UITableViewDelegate
    func numberOfSections(in tableView: UITableView) -> Int {
        2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return 1
        }else{
            return 2
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            guard let cell = tableView.dequeueReusableCell(withIdentifier: kCNLiveShopPayNeedPaymentCellIdentifier) as? CNLiveShopPayNeedPaymentCell
            else {
                let cell = CNLiveShopPayNeedPaymentCell()
                return cell
            }
            let monStr = String(format: "需要付款: ¥%.2f", (Double(self.orderInfoModel?.totalMoney ?? "0.00") ?? 0.00) / 100)
            let attribute = NSMutableAttributedString.init(string:monStr)
            let attIndex = 6
            attribute.addAttributes([NSAttributedString.Key.foregroundColor: HexColor("#222222")!], range: NSRange.init(location: 0, length: attIndex))
            attribute.addAttributes([NSAttributedString.Key.foregroundColor: UIColor(red:0.29, green:0.64, blue:0.25, alpha:1.00)], range: NSRange.init(location: attIndex, length: monStr.count-attIndex))
            cell.titleLabel.attributedText = attribute
            return cell
        }else{
            guard let cell = tableView.dequeueReusableCell(withIdentifier: kCNLiveShopPayWeChatAlipayCellIdentifier) as? CNLiveShopPayWeChatAlipayCell
            else {
                let cell = CNLiveShopPayWeChatAlipayCell()
                return cell
            }
            if indexPath.row == 0{
                //微信支付
                
                cell.iconImgView.image = UIImage(named: "dd_weixin")
                if self.currentSeleWechat == true{
                    cell.selectImgView.isHidden = false
                }else{
                    cell.selectImgView.isHidden = true
                }
                if self.wechatIsInstall{
                    cell.titleLabel.text = "微信支付"
                }else{
                    cell.titleLabel.text = "微信未安装,无法使用微信支付"
                }
            }else{
                //支付宝支付
                cell.iconImgView.image = UIImage(named: "dd_zhifubao")
                if self.currentSeleWechat == true{
                    cell.selectImgView.isHidden = true
                }else{
                    cell.selectImgView.isHidden = false
                }
                if self.alipayIsInstall{
                    cell.titleLabel.text = "支付宝支付"
                }else{
                    cell.titleLabel.text = "支付宝未安装,无法使用支付宝支付"
                }
            }
            return cell
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1{
            if indexPath.row == 0{
                if self.wechatIsInstall == false{
                    showMessage(message: "请安装微信")
                    return
                }
                if self.currentSeleWechat == true{
                    return
                }
                self.currentSeleWechat = true
            }else{
                if self.alipayIsInstall == false{
                    showMessage(message: "请安装支付宝")
                    return
                }
                if self.currentSeleWechat == false{
                    return
                }
                self.currentSeleWechat = false
            }
            self.tableView.reloadData()
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
}