// // MineViewController.swift // MTP2_iOS // // Created by zhongyuan on 2018/3/16. // Copyright © 2018年 zhongyuan.All rights reserved. // import UIKit import WHToast import SDWebImage import SwiftyAttributes import GTMRefresh import IBAnimatable import SafariServices /// 我的主视图容器控制类 class MineViewController: BaseViewController { // MARK: - 属性列表 /// 滚动视图 @IBOutlet weak var scrollView: UIScrollView! /// 内容填充视图 @IBOutlet weak var contentView: UIView! /// 用户头像 @IBOutlet weak var userImage: UIImageView! /// 用户名称 @IBOutlet weak var userName: UILabel! /// 用户手机号码 @IBOutlet weak var mobile: UILabel! /// 余额 @IBOutlet weak var blance: UILabel! /// 冻结余额 @IBOutlet weak var freeze: UILabel! /// 市值 @IBOutlet weak var amount: UILabel! /// 眼睛 @IBOutlet weak var eye: UIButton! /// 优惠券数量 @IBOutlet weak var couponCount: AnimatableLabel! { didSet { couponCount.layer.masksToBounds = true couponCount.isHidden = true } } /// 优惠券 @IBOutlet weak var coupon: UIButton! { didSet { coupon.setTitle(MTP2BusinessCore.shared.getLoginStatus() ? "优惠券" : "注册", for: .normal) coupon.setImage(UIImage(named: MTP2BusinessCore.shared.getLoginStatus() ? "coupon" : ""), for: .normal) } } /// 提现 @IBOutlet weak var recharge_out: UIButton! { didSet { recharge_out.setTitle(MTP2BusinessCore.shared.getLoginStatus() ? "提现" : "登录", for: .normal) recharge_out.setImage(UIImage(named: MTP2BusinessCore.shared.getLoginStatus() ? "mine_recharge_out" : ""), for: .normal) } } /// 资金视图 @IBOutlet weak var taaccountView: UIStackView! { didSet { taaccountView.isHidden = !MTP2BusinessCore.shared.getLoginStatus() } } /// 余额视图 @IBOutlet weak var blanceView: UIStackView! { didSet { blanceView.isHidden = !MTP2BusinessCore.shared.getLoginStatus() } } /// 未登录 @IBOutlet weak var unLogin: UIView! { didSet { unLogin.isHidden = MTP2BusinessCore.shared.getLoginStatus() } } /// 账户视图 @IBOutlet weak var accountView: UIStackView! { didSet { accountView.isHidden = !MTP2BusinessCore.shared.getLoginStatus() } } /// 操作视图 @IBOutlet weak var operationView: UIStackView! /// 设置 @IBOutlet weak var settings: UIButton! /// 单据 待成交 @IBOutlet weak var order_during: UIButton! /// 单据 待付款 @IBOutlet weak var order_transfering: UIButton! /// 单据 已完成 @IBOutlet weak var order_completed: UIButton! /// 我的订单 @IBOutlet weak var order_my: UIButton! /// 包裹 待发货 @IBOutlet weak var packet_unsend: UIButton! /// 包裹 待收货 @IBOutlet weak var packet_unrecive: UIButton! /// 包裹 已完成 @IBOutlet weak var packet_completed: UIButton! /// 我的包裹 @IBOutlet weak var packet_my: UIButton! /// 我的商品 @IBOutlet weak var tableView: UITableView! { didSet { tableView.layer.shadowRadius = 5.0 tableView.layer.shadowOffset = CGSize(width: 5.0, height: 5.0) tableView.layer.shadowColor = UIColorFromHex(rgbValue: 0xe6e6e6).cgColor tableView.layer.shadowOpacity = 0.5 tableView.layer.cornerRadius = 10.0 } } /// 新闻咨询列表高度 @IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint! /// MyOrdersCellIdentifier let MyOrdersCellIdentifier = "MyOrders_Cell" /// 是否显示资金 var isOpen: Bool = true { didSet { /// 替换图片资源 self.eye.setImage(UIImage(named: isOpen ? "mine_eyes_opened" : "mine_eyes_closed"), for: .normal) /// 资金信息 showAccountInfo(isOpen) } } /// 我的商品数据信息 var myGoods: [MoHsbyMyGoods] = [] { didSet { /// 动态设置高度 tableViewHeightConstraint.constant = myGoods.count < 5 ? 400.0 : 107.0*CGFloat(myGoods.count)+40.0 /// 刷新列表数据 tableView.reloadData() /// 资金信息 showAccountInfo(isOpen) if myGoods.count > 0 { /// 等待UI操作完成,也就是tableView刷新完之后执行 DispatchQueue.main.async { [weak self] in if self?.visibleGoodsCodes.count != 0 { self?.shouldSubscriptGoodsCodes = self?.visibleGoodsCodes } } } } } // MARK: - 生命周期 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) /// 设置TabBar图片 self.tabBarItem.image = UIImage(named: "mine_normal")?.withRenderingMode(.alwaysOriginal) self.tabBarItem.selectedImage = UIImage(named: "mine_selected")?.withRenderingMode(.alwaysOriginal) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) /// 隐藏导航栏 self.navigationController?.setNavigationBarHidden(true, animated: true) /// 解决页面切换设置按钮显示问题 if !self.operationView.arrangedSubviews.contains(settings) { self.operationView.insertArrangedSubview(settings, at: 0) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. /// 不需要返回按钮 addBackBarButtonItem(true) /// UI界面初始化 buildView() /// 数据初始化 initData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) /// 当前已登录 if let _ = MTP2BusinessCore.shared.accountManager?.loginRsp { /// 重置数量 reuestData() } } override func didMove(toParent parent: UIViewController?) { super.didMove(toParent: parent) /// 侦听行情推送广播 MTP2BusinessCore.shared.broadcastManager?.addBroadcastListener(owner: self, action: .ReceiveTradeQuote) { [unowned self] in guard let quoteGoodsInfos = $0.object as? [(goodsHqCode: String, exchHqCode: String)] else { return } /// 有数据 if quoteGoodsInfos.count != 0 { /// 待刷新行 var refreshIndexPaths = [IndexPath]() DispatchQueue.main.async { for (index, cell) in self.tableView.visibleCells.enumerated() { if quoteGoodsInfos.first(where: { $0.goodsHqCode == (cell as? MyOrdersCell)?.model?.goodscode }) != nil { let indexPath = IndexPath(row: index, section: 0) if refreshIndexPaths.firstIndex(of: indexPath) == nil { /// 记录待刷新行 /// 判断是否在可见区域 if self.tableView.cellForRow(at: indexPath) != nil { refreshIndexPaths.append(indexPath) } } } } } /// 刷新行情列表 if refreshIndexPaths.count > 0 { DispatchQueue.main.async { self.tableView.reloadRows(at: refreshIndexPaths, with: .none) /// 刷新资金 if self.isOpen { self.showAccountInfo(self.isOpen) } } } } } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) /// 清除广播侦听 MTP2BusinessCore.shared.broadcastManager?.removeBroadcastListener(owner: self, forName: .ReceiveTradeQuote) } // MARK: - 初始化相关 /// UI界面初始化 func buildView() { /// 数据异常 guard let accountManager = MTP2BusinessCore.shared.accountManager else { return } /// LoadingView self.addLoadingView() /// 当前已登录 if let _ = accountManager.loginRsp { /// 用户名 if let accountName = accountManager.moAccountBaseInfo?.accountInfo.accountName { self.userName.attributedText = "\(accountName) ".withFont(.font_16).withTextColor(UIColorFromHex(rgbValue: 0x72aee2))+" 账户 ".withFont(.font_12).withTextColor(UIColorFromHex(rgbValue: 0x999999)).withBackgroundColor(UIColorFromHex(rgbValue: 0xf5f5f5)) } /// 手机号 if let mobile = accountManager.moAccountBaseInfo?.accountInfo.mobile { self.mobile.text = mobile } /// 添加下拉刷新控件 self.scrollView.gtm_addRefreshHeaderView(refreshHeader: DefaultGTMRefreshHeader()) { /// 重置请求条件 self.reuestData() } /// 触发自动加载 self.scrollView.triggerRefreshing() } else { /// 您还未登录,请登录后查看! self.noDataButton.set(image: nil, title: "您还未登录,请登录后查看!", titlePosition: .bottom, additionalSpacing: 0.0, state: .normal) self.noDataButton.isHidden = false } } /// 数据初始化 fileprivate func initData() { /// 默认不显示 isOpen = false } /// 显示资金账户信息 /// - Parameter isOpen: isOpen fileprivate func showAccountInfo(_ isOpen: Bool) { /// 异常 guard let accountManager = MTP2BusinessCore.shared.accountManager, let accountId = accountManager.getCurrentTAAccountInfo()?.accountId, let moCalculate = MTP2BusinessCore.shared.getCalculate(accountId) else { return } accountManager.loginQueryReq(queryItem: "1,2") { (isComplete, error) in DispatchQueue.main.async { let taAccountInfo = accountManager.getCurrentTAAccountInfo() /// 余额 self.blance.attributedText = (!isOpen ? "******" : taAccountInfo?.currentBalance.toDownString(reserve: 2))!.withFont(.font_22).withTextColor(UIColorFromHex(rgbValue: 0x333333)) /// 冻结余额 冻结保证金+其他冻结保证金+冻结手续费 let freezeAmount = (taAccountInfo?.freezeMargin ?? 0.0)+(taAccountInfo?.otherFreezeMargin ?? 0.0)+(taAccountInfo?.freezeCharge ?? 0.0) self.freeze.text = "\(!isOpen ? "******" : freezeAmount.toDownString(reserve: 2))" /// 市值 self.amount.text = "\(!isOpen ? "******" : moCalculate.totalAmount.toDownString(reserve: 2))" } } } // MARK: 交互相关 /// 按钮点击交互事件 /// /// - Parameter sender: sender @IBAction func onButtonPressed(_ sender: UIButton) { switch sender { case order_during: /// 单据 购买中 self.pushController("Order", "Order", 1) case order_transfering: /// 单据 转让中 self.pushController("Order", "Order", 2) case order_completed: /// 单据 已完成 self.pushController("Order", "Order", 3) case order_my: /// 我的订单 self.pushController("Order", "Order", 0) case packet_unsend: /// 包裹 待发货 self.pushController("Order", "Packet", 1) case packet_unrecive: /// 包裹 待收货 self.pushController("Order", "Packet", 2) case packet_completed: /// 包裹 已完成 self.pushController("Order", "Packet", 3) case packet_my: /// 我的包裹 self.pushController("Order", "Packet", 0) case coupon: /// 我的优惠券 if MTP2BusinessCore.shared.getLoginStatus() { /// 当前已登录 self.push(storyboardName: "Coupon", storyboardId: "Coupon") } else { guard let url = URL(string: MTP2BusinessCore.shared.address?.mobileOpenUrl ?? "") else { return } let safriViewController = SFSafariViewController(url: url) safriViewController.delegate = self self.present(safriViewController, animated: true, completion: {}) } case recharge_out: /// 提现 if MTP2BusinessCore.shared.getLoginStatus() { /// 当前已登录 querySign(storyboardName: "OutInMoney", storyboardId: "OutInMoneyViewID", takeInfo: 0) } else { /// 跳转到登录页面 self.push(storyboardName: "Main", storyboardId: "Login") } case eye: /// 眼睛按钮 isOpen = !isOpen case settings: /// 系统设置 self.push(storyboardName: "Settings", storyboardId: "Settings", checkLogin: false) default: break } } /// 页面绑定跳转 /// - Parameters: /// - controller: BaseViewController /// - index: 跳转到指定页面 fileprivate func pushController(_ storyboardName: String, _ storyboardId: String, _ index: Int = 0) { if MTP2BusinessCore.shared.getLoginStatus() { /// 当前已登录 guard let viewController = UIStoryboard(name: storyboardName, bundle: nil).instantiateViewController(withIdentifier: storyboardId) as? BaseViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) viewController.selectedIndex = index } else { self.push(storyboardName: "Main", storyboardId: "Login") } } // MARK: - 接口请求 /// 查询是否已签约 func querySign(storyboardName: String, storyboardId: String, takeInfo: Int) { /// 异常 guard let bankManager = MTP2BusinessCore.shared.bankManager, let accountManager = MTP2BusinessCore.shared.accountManager, let accountID = accountManager.getCurrentTAAccountInfo()?.accountId else { return } _anim?.startAnimating() /// 查询是否已签约 bankManager.bankSign(accountId: UInt64(accountID), cusbankId: "") { (isSuccess, errorInfo, results) in DispatchQueue.main.async { self._anim?.stopAnimating() if isSuccess { if let results = results, results.bankSign.first(where: { $0.signStatus == ESignStatus.SIGNSTATUS_SIGNED.rawValue }) != nil { /// 出入金 self.push(storyboardName: storyboardName, storyboardId: storyboardId, takeInfo: takeInfo) } else { self.showYesOrNOController(title: "提示", message: "您好!请进行签约后,再使用出入金", handler: { (_) in if TradeControlUtils.checkAuthState(navigationController: self.navigationController) { /// 打开签约界面 if let _ = (UIStoryboard(name: "Settings", bundle: nil).instantiateViewController(withIdentifier: "SigningMain")) as? SigningMainViewController { DispatchQueue.main.async { self.pushController("Settings", "SigningMain") } } } }) } } else { self.showErrorMessgae(error: errorInfo) } } } } /// 数据加载 fileprivate func reuestData() { /// 异常 guard let orderManager = MTP2BusinessCore.shared.orderManager else { return } /// DispatchGroup let group = DispatchGroup() /// 查询我的单据数量 group.enter() orderManager.requestGetHsbyMyCount { (isComplete, error, myCount) in DispatchQueue.main.async { if isComplete { if let preCount = myCount?.myOrderDetailPreCount, let listingCount = myCount?.myOrderDetailListingCount { self.order_during.fl_badgeValue = "\(preCount+listingCount)" } if let count = myCount?.myPayOrderCount { self.order_transfering.fl_badgeValue = count == 0 ? "" : "\(count)" } if let count = myCount?.myPackageUnSendCount { self.packet_unsend.fl_badgeValue = count == 0 ? "" : "\(count)" } if let count = myCount?.myPackageUnReceiveCount { self.packet_unrecive.fl_badgeValue = "\(count)" } /// 优惠券数量 if let count = myCount?.myCouponCount, count != 0 { self.couponCount.text = "\(count)" self.couponCount.isHidden = false } else { self.couponCount.isHidden = true } } } group.leave() } /// 查询我的商品数据请求 group.enter() orderManager.requestQueryHsbyMyGoods { (isComplete, error, goods) in DispatchQueue.main.async { if isComplete { self.myGoods = goods ?? [] } else { self.myGoods = [] WHToast.showError(withMessage: "数据查询失败,原因:\(error?.retMsg ?? "未知错误")", duration: 1.5, finishHandler: {}) } } group.leave() } group.notify(queue: DispatchQueue.main) { /// 停止加载 self.scrollView.endRefreshing() } } // MARK: - 订阅行情相关 var uuid: String = UUID().uuidString var shouldSubscriptGoodsCodes: Set? { didSet { guard let quoteSubscriptManager = MTP2BusinessCore.shared.quoteSubscriptManager else { return } quoteSubscriptManager.updateQuoteSubcriptGoods(uuid: uuid, goodsCode: shouldSubscriptGoodsCodes ?? []) } } var visibleGoodsCodes: Set { var goodsCodes = Set() self.tableView.visibleCells.forEach { (cell) in if let quoteCell = cell as? MyOrdersCell, let goodsCode = quoteCell.model?.goodscode { goodsCodes.insert(goodsCode) } } return goodsCodes } } // MARK: - UIScrollViewDelegate extension MineViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.contentOffset.y >= 20.0 { self.navigationController?.setNavigationBarHidden(false, animated: true) self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: settings) } else { self.navigationController?.setNavigationBarHidden(true, animated: true) self.operationView.insertArrangedSubview(settings, at: 0) } } } // MARK: - 初始化相关 extension MineViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myGoods.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: MyOrdersCellIdentifier, for: indexPath) as! MyOrdersCell cell.model = myGoods[indexPath.row] return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 115.0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { /// 商品详情 guard let goods = MTP2BusinessCore.shared.goodsManager?.goodsInfos.first(where: {$0.goodsid == myGoods[indexPath.row].goodsid}) else { return } let goodsDetailController = UIStoryboard(name: "Quote", bundle: nil).instantiateViewController(withIdentifier: "GoodsDetail") as! GoodsDetailViewController goodsDetailController.model = goods self.navigationController?.pushViewController(goodsDetailController, animated: true) } } extension MineViewController: SFSafariViewControllerDelegate { func safariViewControllerDidFinish(_ controller: SFSafariViewController) { controller.dismiss(animated: true, completion: {}) } } // MARK: - MyOrdersCell class MyOrdersCell: BaseTableViewCell { /// 商品代码 @IBOutlet weak var orderNo: UILabel! /// 商品图片 @IBOutlet weak var goodsImage: UIImageView! /// 价格 @IBOutlet weak var price: UILabel! /// 金额 @IBOutlet weak var amount: UILabel! /// 当前价值 @IBOutlet weak var market: UILabel! /// 标题 @IBOutlet weak var title: UILabel! /// 数量 @IBOutlet weak var qty: UILabel! override var model: MoHsbyMyGoods? { didSet{ /// 异常 guard let obj = model else { return } /// 如果有商品 if let goodsInfo = MTP2BusinessCore.shared.goodsManager?.goodsInfos.first(where: {$0.goodsid == obj.goodsid}), goodsInfo.getLast() != 0.0 { market.text = "当前价值:\((goodsInfo.getLast()*Double(obj.buycurpositionqty)*goodsInfo.agreeUnit).toDownString(reserve: obj.decimalplace))" } else { market.text = "当前价值:\(obj.currencysign+(obj.buycurholderamount.toDownString(reserve: obj.decimalplace)))" } /// 金额 amount.text = "购入金额:\(obj.currencysign)\(obj.buycurholderamount.toDownString(reserve: obj.decimalplace))" /// 价格 price.text = obj.currencysign+"\(obj.buyaverageprice)" /// 数量 qty.text = "×\(obj.buycurpositionqty)" /// 标题 title.text = obj.goodsname /// 商品代码 orderNo.text = obj.goodscode /// 商品图片 guard let url = StringUtils.getImageUrl(obj.picurls) else { return } goodsImage.sd_setImage(with: url, placeholderImage: UIImage(named: "placeholder_image"), options: .queryDiskDataSync, context: nil) } } }