Guest User

Untitled

a guest
Oct 16th, 2019
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 13.51 KB | None | 0 0
  1. //
  2. //  LoadsDetailsViewController.swift
  3. //  UOnLoad
  4. //
  5. //  Created by Ivan Lupenkov on 3/25/19.
  6. //  Copyright © 2019 UOnLoad. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import Alamofire
  11. import SwiftSpinner
  12. import MapKit
  13. import CoreLocation
  14. import Toast_Swift
  15. import ActionSheetPicker_3_0
  16.  
  17. class LoadsDetailsViewController: UIViewController {
  18.    
  19.     var id: Int!
  20.     var proNumber: String!
  21.     var pickupAddrss: String!
  22.     var deliveryAddress: String!
  23.     var pickupDateTime: String!
  24.     var deliveryDateTime: String!
  25.     var createdAt: String!
  26.     var truckSize: NSArray!
  27.     var pcs: Int!
  28.     var weight: Int!
  29.     var deadHead: Double!
  30.     var distance: Int!
  31.     var mybid: NSObject? = nil
  32.     var length: Int!
  33.     var width: Int!
  34.     var height: Int!
  35.     var toll: Int!
  36.     var from_lat: Double!
  37.     var from_lng: Double!
  38.     var to_lat: Double!
  39.     var to_lng: Double!
  40.     var stackable: Bool!
  41.     var dockHigh: Bool!
  42.     var notes: String? = nil
  43.    
  44.     @IBOutlet weak var loadIdLabel: UILabel!
  45.     @IBOutlet weak var fromLabel: UILabel!
  46.     @IBOutlet weak var toLabel: UILabel!
  47.     @IBOutlet weak var fromDistanceLabel: UILabel!
  48.     @IBOutlet weak var toDistanceLabel: UILabel!
  49.     @IBOutlet weak var routeView: UIView!
  50.     @IBOutlet weak var deadheadLabel: UILabel!
  51.     @IBOutlet weak var distanceLabel: UILabel!
  52.    
  53.     @IBOutlet weak var suggestedPriceLabel: UILabel!
  54.    
  55.     @IBOutlet weak var myBidLabel: UILabel!
  56.     @IBOutlet weak var pcsWeightLabel: UILabel!
  57.     @IBOutlet weak var dimLabel: UILabel!
  58.     @IBOutlet weak var puDateLabel: UILabel!
  59.     @IBOutlet weak var deDateLabel: UILabel!
  60.     @IBOutlet weak var notesLabel: UILabel!
  61.     @IBOutlet weak var truckTypeLabel: UILabel!
  62.    
  63.     let regionDistance:CLLocationDistance = 1000;
  64.    
  65.     enum CardState {
  66.         case expanded
  67.         case collapsed
  68.     }
  69.    
  70.     var newBidCardViewController: NewBidCardViewController!
  71.     var visualEffectView: UIVisualEffectView!
  72.    
  73.     var cardHeight: CGFloat = 0
  74.     var cardHandleAreaHeight: CGFloat = 80
  75.    
  76.     var cardVisible = false
  77.     var nextState: CardState {
  78.         return cardVisible ? .collapsed : .expanded
  79.     }
  80.    
  81.     var runningAnimations = [UIViewPropertyAnimator]()
  82.     var animationProgressWhenInterrupted: CGFloat = 0
  83.    
  84.     override func viewWillAppear(_ animated: Bool) {
  85.         super.viewWillAppear(animated)
  86.         navigationController?.setNavigationBarHidden(true, animated: animated)
  87.        
  88.         let navigationTap = UITapGestureRecognizer(target: self, action: #selector(self.navigationService))
  89.         routeView.addGestureRecognizer(navigationTap)
  90.         loadIdLabel.text = String("Load #\(id!)")
  91.         fromLabel.text = pickupAddrss
  92.         toLabel.text = deliveryAddress
  93.         deadheadLabel.text = String("\(deadHead!.rounded()) mil deadhead")
  94.         distanceLabel.text = String("\(distance!) mil")
  95.        
  96.         myBidLabel.text = "N/A"
  97. //        if mybid != nil {
  98. //            let perMile:Float = Float(mybid) / Float(distance)
  99. //            myBidLabel.text = String("$\(mybid!) / \(String(format:"%.2f", perMile)) mile")
  100. //            myBidLabel.textColor = UIColor(red:0.15, green:0.92, blue:0.18, alpha:1.0)
  101. //        }
  102.         pcsWeightLabel.text = String("\(pcs!) / \(weight!)")
  103.         dimLabel.text = "\(length!)x\(width!)x\(height!) in"
  104.         puDateLabel.text = pickupDateTime.toDate()?.toString(withFormat: "MMM d, h:mm a")
  105.         deDateLabel.text = deliveryDateTime.toDate()?.toString(withFormat: "MMM d, h:mm a")
  106.         let truck_type_id = (truckSize.firstObject as! NSString).intValue
  107.         truckTypeLabel.text = TruckType.getNameById(id: Int(truck_type_id))
  108.         notesLabel.text = notes
  109.     }
  110.    
  111.     override func viewWillDisappear(_ animated: Bool) {
  112.         navigationController?.setNavigationBarHidden(false, animated: animated)
  113.     }
  114.    
  115.     override func viewDidLoad() {
  116.         super.viewDidLoad()
  117.         setupCard()
  118.     }
  119.    
  120.     func setupCard() {
  121.         cardHeight = self.view.bounds.height * 0.7
  122.         if UIDevice.hasTopNotch {
  123.             cardHandleAreaHeight = 70
  124.         }
  125.        
  126.         visualEffectView = UIVisualEffectView()
  127.         visualEffectView.frame = self.view.frame
  128.         self.view.addSubview(visualEffectView)
  129.        
  130.         self.visualEffectView.isHidden = true
  131.        
  132.         newBidCardViewController = NewBidCardViewController(nibName:"NewBidCardView", bundle:nil)
  133.         self.addChild(newBidCardViewController)
  134.         self.view.addSubview(newBidCardViewController.view)
  135.        
  136.         newBidCardViewController.view.frame = CGRect(x: 0, y: self.view.frame.height - cardHandleAreaHeight, width: self.view.bounds.width, height: cardHeight)
  137.         newBidCardViewController.view.clipsToBounds = true
  138.        
  139.         if newBidCardViewController.loadId != nil && self.id != nil
  140.         {
  141.             newBidCardViewController.loadId = self.id!
  142.         }
  143.        
  144.         let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.handleCardTap(recognzier:)))
  145.         let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.handleCardPan(recognizer:)))
  146.        
  147.         newBidCardViewController.handleArea.addGestureRecognizer(tapGestureRecognizer)
  148.         newBidCardViewController.handleArea.addGestureRecognizer(panGestureRecognizer)
  149.     }
  150.    
  151.     @objc
  152.     func handleCardTap(recognzier:UITapGestureRecognizer) {
  153.        switch recognzier.state {
  154.        case .ended:
  155.            animateTransitionIfNeeded(state: nextState, duration: 0.9)
  156.        default:
  157.            break
  158.        }
  159.     }
  160.    
  161.     @objc
  162.     func handleCardPan(recognizer: UIPanGestureRecognizer) {
  163.         switch recognizer.state {
  164.         case .began:
  165.             // startTransition
  166.             startInteractiveTransition(state: nextState, duration: 0.9)
  167.         case .changed:
  168.             // updateTransition
  169.             let translation = recognizer.translation(in: self.newBidCardViewController.handleArea)
  170.             var fractionCompleted = translation.y / cardHeight
  171.             fractionCompleted = cardVisible ? fractionCompleted : -fractionCompleted
  172.             updateInteractiveTransition(fractionCompleted: fractionCompleted)
  173.         case .ended:
  174.             // continueTransition
  175.             continueInteractiveTransition()
  176.         default:
  177.             break
  178.         }
  179.     }
  180.    
  181.     func animateTransitionIfNeeded(state: CardState, duration: TimeInterval) {
  182.         if runningAnimations.isEmpty {
  183.             let frameAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 1) {
  184.                 switch state {
  185.                 case .expanded:
  186.                     UIView.animate(withDuration: 2) {
  187.                         self.newBidCardViewController.handleArrowImage.transform = CGAffineTransform(rotationAngle: .pi)
  188.                         self.newBidCardViewController.handleLabel.text = "Swipe bottom to cancel"
  189.                     }
  190.                     self.newBidCardViewController.view.frame.origin.y = self.view.frame.height - (self.view.frame.height * 0.7)
  191.                     self.visualEffectView.isHidden = false
  192.                 case .collapsed:
  193.                     UIView.animate(withDuration: 2) {
  194.                         self.newBidCardViewController.handleArrowImage.transform = CGAffineTransform.identity
  195.                         self.newBidCardViewController.handleLabel.text = "Swipe up to place bid"
  196.                     }
  197.                     self.newBidCardViewController.view.frame.origin.y = self.view.frame.height - self.view.safeAreaInsets.bottom - self.cardHandleAreaHeight
  198.                 }
  199.             }
  200.            
  201.             frameAnimator.addCompletion { _ in
  202.                 self.cardVisible = !self.cardVisible
  203.                 self.runningAnimations.removeAll()
  204.             }
  205.            
  206.             frameAnimator.startAnimation()
  207.             runningAnimations.append(frameAnimator)
  208.            
  209.             let cornerRadiusAnimator = UIViewPropertyAnimator(duration: duration, curve: .linear) {
  210.                 switch state {
  211.                 case .expanded:
  212.                     self.newBidCardViewController.view.layer.cornerRadius = 14
  213.                 case .collapsed:
  214.                     self.newBidCardViewController.view.layer.cornerRadius = 14
  215.                 }
  216.             }
  217.            
  218.             cornerRadiusAnimator.startAnimation()
  219.             runningAnimations.append(cornerRadiusAnimator)
  220.            
  221.             let blurAnimator = UIViewPropertyAnimator.init(duration: duration, dampingRatio: 1) {
  222.                 switch state {
  223.                 case .expanded:
  224.                     self.visualEffectView.effect = UIBlurEffect(style: .dark)
  225.                 case .collapsed:
  226.                     self.visualEffectView.effect = nil
  227.                 }
  228.             }
  229.            
  230.             blurAnimator.startAnimation()
  231.             runningAnimations.append(blurAnimator)
  232.            
  233.             blurAnimator.addCompletion{(_) in
  234.                 if state == .collapsed{
  235.                     self.visualEffectView.isHidden = true
  236.                 }
  237.             }
  238.         }
  239.     }
  240.    
  241.     func startInteractiveTransition(state: CardState, duration: TimeInterval) {
  242.         if runningAnimations.isEmpty {
  243.             animateTransitionIfNeeded(state: state, duration: duration)
  244.         }
  245.        
  246.         for animator in runningAnimations {
  247.             animator.pauseAnimation()
  248.             animationProgressWhenInterrupted = animator.fractionComplete
  249.         }
  250.     }
  251.    
  252.     func updateInteractiveTransition(fractionCompleted: CGFloat) {
  253.         for animator in runningAnimations {
  254.             animator.fractionComplete = fractionCompleted + animationProgressWhenInterrupted
  255.         }
  256.     }
  257.    
  258.    func continueInteractiveTransition() {
  259.         for animator in runningAnimations {
  260.             animator.continueAnimation(withTimingParameters: nil, durationFactor: 0)
  261.         }
  262.     }
  263.    
  264.     @IBAction func backButton(_ sender: Any) {
  265.         self.navigationController?.popViewController(animated: true)
  266.     }
  267.    
  268.     func saveBid(bid: Float?, loadId: Int?){
  269.         let token = (defaultValues.string(forKey: "token") ?? "Undefined")
  270.         let headers: HTTPHeaders = [
  271.             "Authorization": "Bearer \(token)",
  272.         ]
  273.         let parameters: Parameters = [
  274.             "amount": bid!,
  275.             "load_id": loadId!
  276.         ]
  277.         requestAPI.make(endpoint: APIEndpoint.bid.rawValue, method: HTTPMethod.post, parameters: parameters, headers: headers, completionHandler: {(data: Any?, success: String) -> Void in
  278.             switch success {
  279.             case "success":
  280.                 print("success")
  281. //                if bid != 0 {
  282. //                    UIView.animate(withDuration: 1.0) {
  283. //                        let perMile:Float = Float(bid!) / Float(self.distance)
  284. //                        self.myBidLabel.text = String("$\(bid!) / \(String(format:"%.2f", perMile)) mile")
  285. //                        self.myBidLabel.textColor = UIColor(red:0.15, green:0.92, blue:0.18, alpha:1.0)
  286. //                    }
  287. //                } else {
  288. //                    self.myBidLabel.text = String("N/A")
  289. //                    self.myBidLabel.textColor = .gray
  290. //                }
  291.             case "fail":
  292.                 let data = data as! NSDictionary
  293.                 let error = data.value(forKey: "errors") as! String
  294.                 self.view.makeToast("ERROR! \(error)")
  295.                 self.view.hideToastActivity()
  296.             case "error":
  297.                 print("Error2")
  298.             default:
  299.                 print("Error3")
  300.             }
  301.         })
  302.     }
  303.    
  304.    
  305.     @objc func navigationService(){
  306.         let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  307.         let scanAction = UIAlertAction(title: "Apple Maps", style: .default) { (_) in
  308.             self.navigateAppleMaps()
  309.         }
  310.         let selectAction = UIAlertAction(title: "Google Maps", style: .default) { (_) in
  311.             self.navigateGoogleMaps()
  312.         }
  313.         let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil)
  314.         actionSheet.addAction(scanAction)
  315.         actionSheet.addAction(selectAction)
  316.         actionSheet.addAction(cancelAction)
  317.         present(actionSheet, animated: true)
  318.     }
  319.    
  320.     private func navigateAppleMaps(){
  321.         let url = "http://maps.apple.com/maps?saddr=\(pickupAddrss!)&daddr=\(deliveryAddress!)"
  322.         UIApplication.shared.open(URL(string:url.removingWhitespaces())!)
  323.     }
  324.    
  325.     private func navigateGoogleMaps(){
  326.         let appDomen: String = "comgooglemaps://"
  327.         let browserDomen: String = "https://www.google.co.in/maps/dir/"
  328.         let directionBody: String = "?saddr=\(pickupAddrss!)&daddr=\(deliveryAddress!)&directionsmode=driving"
  329.         if let appUrl = URL(string: appDomen), UIApplication.shared.canOpenURL(appUrl) {
  330.             guard let appFullPathUrl = URL(string: appDomen + directionBody.removingWhitespaces()) else { return }
  331.             UIApplication.shared.open(appFullPathUrl)
  332.         } else if let browserUrl = URL(string: browserDomen), UIApplication.shared.canOpenURL(browserUrl) {
  333.             guard let browserFullPathUrl = URL(string: browserDomen + directionBody) else { return }
  334.             UIApplication.shared.open(browserFullPathUrl)
  335.         }
  336.     }
  337.    
  338. }
  339.  
  340. extension String {
  341.     func removingWhitespaces() -> String {
  342.         return components(separatedBy: .whitespaces).joined()
  343.     }
  344. }
Advertisement
Add Comment
Please, Sign In to add comment