You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

451 lines
20 KiB

6 years ago
  1. //
  2. // ExchangeRatesViewController.swift
  3. // GMERemittance
  4. //
  5. // Created by gme_2 on 24/08/2018.
  6. //Copyright © 2018 Gobal Money Express Co. Ltd. All rights reserved.
  7. //
  8. import UIKit
  9. import Hex
  10. enum PaymentMode: String {
  11. case cashDelivery = "1"
  12. case bankDeposite = "2"
  13. case homeDelivery = "12"
  14. case mobileWallet = "13"
  15. }
  16. class ExchangeRatesViewController: UIViewController {
  17. struct Constants {
  18. static let transferFeeDetailText = "Transfer Fee Included"
  19. static let currentExchangeRateText = "Current Exchange Rate"
  20. static let paymentModeHeightConstant: CGFloat = 193
  21. }
  22. struct ApiConstants {
  23. static let recieverCountryId = "pCountry"
  24. static let senderCurrency = "sCurrency"
  25. static let recieverCurrency = "pCurrency"
  26. static let senderAmount = "cAmount"
  27. static let recieverAmount = "pAmount"
  28. static let paymentMethod = "serviceType"
  29. static let calcBy = "calcBy"
  30. static let recieverCountryName = "pCountryName"
  31. static let senderCountryId = "sCountry"
  32. }
  33. // MARK: IBOutlets
  34. @IBOutlet weak var collectionView: UICollectionView!
  35. @IBOutlet weak var exchangeBackground1: UIView!
  36. @IBOutlet weak var exchangeBackground2: UIView!
  37. @IBOutlet weak var dropDownImageView: UIImageView!
  38. @IBOutlet weak var backgroundViewCountryLabel1: UIView!
  39. @IBOutlet weak var backgroundViewCountryLabel2: UIView!
  40. @IBOutlet weak var countryListStackView: UIStackView!
  41. @IBOutlet weak var countryCodeLabel: UILabel!
  42. @IBOutlet weak var countryFlagImage: UIImageView!
  43. @IBOutlet weak var paymentModeStackViewConstraint: NSLayoutConstraint!
  44. @IBOutlet weak var paymentModeStackView: UIStackView!
  45. @IBOutlet weak var senderTextField: UITextField!
  46. @IBOutlet weak var reciepientTextField: UITextField!
  47. @IBOutlet weak var transferFeeInfoLabel: UILabel!
  48. @IBOutlet weak var exchangeRateInfoLabel: UILabel!
  49. var presenter: ExchangeRatesModuleInterface?
  50. var countryListTapGuesture: UITapGestureRecognizer?
  51. var selectedPaymentIndex: IndexPath = IndexPath.init(row: 0, section: 0)
  52. var nativeCountryCode: String? = "np"
  53. var calcBy = ""
  54. var exchangeRateModels: [ExchangeRateModel]? {
  55. didSet {
  56. if let _ = CountryInfo().defaultCountryCodes.filter({$0.lowercased() == (self.nativeCountryCode ?? "").lowercased()}).first {
  57. if let defaultExchangeRate = self.exchangeRateModels?.filter({
  58. ($0.countryCode ?? "").lowercased() == (self.nativeCountryCode ?? "").lowercased()
  59. }).first {
  60. // there is native country, defaultExchangeRate is the information for that country
  61. self.setCountryFlag(countryCode: defaultExchangeRate.countryCode ?? "")
  62. self.setCurrencyLabel(currency: defaultExchangeRate.currency ?? "")
  63. // set the default amount for this country. there are some default values in CountryInfo
  64. self.selectedExchageRateModel = defaultExchangeRate
  65. self.collectionView.reloadData()
  66. showPaymentModeView()
  67. self.populateDefaultAmounts()
  68. }
  69. } else {
  70. self.setDefaultValuesForCountriesNotHavingDefaultValue()
  71. showPaymentModeView()
  72. }
  73. }
  74. }
  75. var selectedExchageRateModel: ExchangeRateModel? {
  76. didSet {
  77. self.setCurrencyLabel(currency: self.selectedExchageRateModel?.currency ?? "")
  78. self.setCountryFlag(countryCode: self.selectedExchageRateModel?.countryCode ?? "")
  79. self.reciepientTextField.text = ""
  80. calcBy = "c"
  81. collectionView.reloadData()
  82. }
  83. }
  84. // MARK: VC's Life cycle
  85. override func viewDidLoad() {
  86. super.viewDidLoad()
  87. setup()
  88. setupDelegates()
  89. setupTargets()
  90. setupNavigation()
  91. setupDefaultCountryFlagandCurrency()
  92. // todo: show default native country and falg
  93. // Do any additional setup after loading the view.
  94. // populateDefaultAmounts()
  95. fetchExchangeRateInformation()
  96. }
  97. func setupDefaultCountryFlagandCurrency() {
  98. if let defaultExchangeRate = self.exchangeRateModels?.filter({
  99. ($0.country ?? "").lowercased() == (self.nativeCountryCode ?? "").lowercased()
  100. }).first {
  101. // there is native country, defaultExchangeRate is the information for that country
  102. self.setCountryFlag(countryCode: defaultExchangeRate.countryCode ?? "")
  103. self.setCurrencyLabel(currency: defaultExchangeRate.currency ?? "")
  104. }
  105. }
  106. override func viewWillAppear(_ animated: Bool) {
  107. super.viewWillAppear(animated)
  108. self.title = "Today's Rate"
  109. }
  110. // IBActions
  111. @IBAction func calculateExchangeRate(_ sender: UIButton) {
  112. let senderAmount = self.senderTextField.text!
  113. let reciepientAmount = self.reciepientTextField.text!
  114. print("sender textfield \(senderAmount)")
  115. print("reciepientTextfield \(reciepientAmount)")
  116. print(calcBy)
  117. let recipientCurrency = self.selectedExchageRateModel?.currency
  118. let reciepientCountryId = self.selectedExchageRateModel?.countryId
  119. let paymentMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: selectedPaymentIndex.row)
  120. let reciepientCountryName = self.selectedExchageRateModel?.country
  121. self.calculate(senderAmt: senderAmount, recieverAmt: reciepientAmount, recieverCurrency: recipientCurrency, recieverCountryName: reciepientCountryName, recieverCountryId: reciepientCountryId, paymentMethod: paymentMethod?.id, calcBy: self.calcBy)
  122. // call calculate( ... ) function
  123. // todo send to api for calculation
  124. }
  125. func calculate(senderAmt: String?, senderCurrency: String? = "KRW", recieverAmt: String?, recieverCurrency: String?, recieverCountryName: String?, recieverCountryId: String?, paymentMethod: String?, calcBy: String?, senderCountryId: String? = "118", shouldShowLoading: Bool = true ) {
  126. let param: [String: String] =
  127. [
  128. ApiConstants.senderAmount : senderAmt ?? "",
  129. ApiConstants.senderCurrency : senderCurrency ?? "",
  130. ApiConstants.recieverAmount : recieverAmt ?? "",
  131. ApiConstants.recieverCurrency : recieverCurrency ?? "",
  132. ApiConstants.recieverCountryId : recieverCountryId ?? "",
  133. ApiConstants.paymentMethod: paymentMethod ?? "",
  134. ApiConstants.calcBy : calcBy ?? "",
  135. ApiConstants.senderCountryId : senderCountryId ?? "",
  136. ApiConstants.recieverCountryName: recieverCountryName ?? ""
  137. ]
  138. print(param)
  139. // todo
  140. if shouldShowLoading { self.showProgressHud() }
  141. self.getExchangeRateInformation(params: param, success: { (exchageRateDetail) in
  142. self.senderTextField.text = Utility.getCommaSeperatedString(numberString: exchageRateDetail?.senderAmount ?? "")
  143. self.reciepientTextField.text = Utility.getCommaSeperatedString(numberString: exchageRateDetail?.recipientAmount ?? "")
  144. let transferFee = exchageRateDetail?.transferFee ?? ""
  145. let currency = exchageRateDetail?.senderCurrency ?? ""
  146. self.transferFeeInfoLabel.text = "\(transferFee) \(currency) (\(Constants.transferFeeDetailText))"
  147. let exchangeRate = exchageRateDetail?.exchangeRate ?? ""
  148. self.exchangeRateInfoLabel.text = "\(exchangeRate) (\(Constants.currentExchangeRateText))"
  149. self.hideProgressHud()
  150. }) { (error) in
  151. self.hideProgressHud()
  152. self.alert(message: error.localizedDescription)
  153. }
  154. // call api with these params
  155. }
  156. @objc func showCountryList(_ sender: UITapGestureRecognizer) {
  157. print("show Country List")
  158. let viewcontroller = UIStoryboard.init(name: "TableViewPicker", bundle: nil).instantiateViewController(withIdentifier: "TablePickerViewController") as! TablePickerViewController
  159. viewcontroller.data = self.exchangeRateModels ?? []
  160. viewcontroller.type = TablePickerViewTitle.country
  161. viewcontroller.doneAction = self.countrySelected
  162. // viewcontroller.defaultSelectedData = [self.selectedExchageRateModel]
  163. self.present(viewcontroller, animated: true, completion: nil)
  164. }
  165. // other function
  166. func showPaymentModeView() {
  167. UIView.animate(withDuration: 0.33) {
  168. self.paymentModeStackViewConstraint.constant = Constants.paymentModeHeightConstant
  169. self.paymentModeStackView.alpha = 1
  170. self.view.layoutIfNeeded()
  171. }
  172. }
  173. func countrySelected(model: [ExchangeRateModel]) {
  174. self.selectedExchageRateModel = model.first
  175. // show country with flag.
  176. }
  177. @objc private func textChanged(sender: UITextField) {
  178. switch sender {
  179. case senderTextField:
  180. self.reciepientTextField.text = ""
  181. self.calcBy = "c"
  182. senderTextField.text = Utility.getCommaSeperatedString(numberString: senderTextField.text!)
  183. case reciepientTextField:
  184. self.senderTextField.text = ""
  185. self.calcBy = "p"
  186. reciepientTextField.text = Utility.getCommaSeperatedString(numberString: reciepientTextField.text!)
  187. default:
  188. break
  189. }
  190. }
  191. private func setCountryFlag(countryCode: String) {
  192. let flag = CountryInfo().getFlag(for: countryCode)
  193. self.countryFlagImage.image = flag
  194. }
  195. private func setCurrencyLabel(currency: String) {
  196. self.countryCodeLabel.text = currency.uppercased()
  197. }
  198. private func populateDefaultAmounts() {
  199. guard let nativeCountry = self.nativeCountryCode else {return}
  200. // todo: native country cha bhane tesko CountryInfo class ma defaullt value cha ki chaina herne
  201. // CountryInfo class ma defaullt value cha bhane tyo value rakhera second api hit garna paryo ani aako data dekhaune
  202. // natra bhane tesko 1000000 kwr ko native ma kati huncha teti populate garaune
  203. guard let exchangeModel = self.exchangeRateModels?.filter({
  204. $0.countryCode?.lowercased() == nativeCountry.lowercased() // countryCode
  205. }).first else {return}
  206. // self.selectedExchageRateModel = exchangeModel
  207. // if there is no default amount, then we have to calculate from korean won. so guard ma rakhna thik nahola, yo case hereko chaina
  208. if let recievingAmount = CountryInfo().getDefaultSendingAmount(for: exchangeModel.countryCode ?? "") {
  209. self.setDefaultValuesForCountriesHavingDefaultValue(recievingAmount: recievingAmount, exchangeModel: exchangeModel)
  210. }
  211. // else {
  212. // setDefaultValuesForCountriesNotHavingDefaultValue()
  213. // }
  214. }
  215. private func setDefaultValuesForCountriesNotHavingDefaultValue() {
  216. self.selectedExchageRateModel = self.exchangeRateModels?.first
  217. let senderAmount = CountryInfo().getDefaultSendingMoneyInKoreanWon()
  218. self.senderTextField.text = Utility.getCommaSeperatedString(numberString: senderAmount ?? "")
  219. let senderCurrency = "KWR"
  220. let recieverCurrency = self.selectedExchageRateModel?.currency
  221. let recieverCountryId = self.selectedExchageRateModel?.countryId
  222. let paymentMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: selectedPaymentIndex.row)
  223. let reciepientCountryName = self.selectedExchageRateModel?.country ?? ""
  224. let calcBy = "c"
  225. let senderCountryName = "KOREA"
  226. self.calculate(senderAmt: senderAmount, senderCurrency: senderCurrency, recieverAmt: nil, recieverCurrency: recieverCurrency, recieverCountryName: reciepientCountryName, recieverCountryId: recieverCountryId, paymentMethod: paymentMethod?.id, calcBy: calcBy, shouldShowLoading: false)
  227. }
  228. private func setDefaultValuesForCountriesHavingDefaultValue(recievingAmount: String, exchangeModel: ExchangeRateModel) {
  229. guard let recievingCurrency = CountryInfo().getDefaultSendingCurrency(for: exchangeModel.countryCode ?? ""),
  230. let recievingCountryId = exchangeModel.countryId,
  231. let paymentMethod = exchangeModel.availableServices?.elementAt(index: selectedPaymentIndex.row)
  232. else {
  233. // do something if you have to do
  234. return
  235. }
  236. self.calcBy = "p"
  237. self.reciepientTextField.text = Utility.getCommaSeperatedString(numberString: recievingAmount)
  238. let reciepientCountryName = exchangeModel.country
  239. self.calculate(senderAmt: nil, senderCurrency: "KRW", recieverAmt: recievingAmount, recieverCurrency: recievingCurrency, recieverCountryName: reciepientCountryName, recieverCountryId: recievingCountryId, paymentMethod: paymentMethod.id, calcBy: calcBy, shouldShowLoading: false)
  240. }
  241. private func fetchExchangeRateInformation() {
  242. self.showProgressHud()
  243. self.fetchCountryCurrencyInfo(success: { (models) in
  244. self.exchangeRateModels = models
  245. }) { (error) in
  246. self.hideProgressHud()
  247. self.alert(message: error.localizedDescription)
  248. }
  249. }
  250. private func setupTargets() {
  251. let tapGuesture = UITapGestureRecognizer(target: self, action: #selector(self.showCountryList(_:)))
  252. self.countryListTapGuesture = tapGuesture
  253. self.countryListStackView.addGestureRecognizer(self.countryListTapGuesture!)
  254. self.reciepientTextField.addTarget(self, action: #selector(self.textChanged(sender:)), for: UIControlEvents.editingChanged)
  255. self.senderTextField.addTarget(self, action: #selector(self.textChanged(sender:)), for: UIControlEvents.editingChanged)
  256. }
  257. private func setupDelegates() {
  258. self.collectionView.delegate = self
  259. self.collectionView.dataSource = self
  260. }
  261. private func setup() {
  262. let dropDownImage = #imageLiteral(resourceName: "dropdown_white").withRenderingMode(UIImageRenderingMode.alwaysTemplate)
  263. let image = dropDownImage
  264. self.dropDownImageView.image = image
  265. self.dropDownImageView.tintColor = UIColor.white
  266. self.paymentModeStackViewConstraint.constant = 0
  267. self.paymentModeStackView.alpha = 0
  268. // corner Radius
  269. [backgroundViewCountryLabel1, backgroundViewCountryLabel2].forEach({
  270. $0?.layer.cornerRadius = 5
  271. })
  272. [exchangeBackground1, exchangeBackground2].forEach({
  273. $0?.layer.borderWidth = 1
  274. $0?.layer.borderColor = UIColor.init(hex: "#E0E0E0").cgColor
  275. $0?.layer.cornerRadius = 5
  276. })
  277. }
  278. func show(error: String) {
  279. self.alert(message: error)
  280. }
  281. func showLoading() {
  282. self.showProgressHud()
  283. }
  284. func hideLoading() {
  285. self.hideProgressHud()
  286. }
  287. private func setupNavigation() {
  288. var backBtnImage = #imageLiteral(resourceName: "backIconBlack")
  289. backBtnImage = backBtnImage.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
  290. self.navigationController!.navigationBar.backIndicatorImage = backBtnImage
  291. self.navigationController!.navigationBar.backIndicatorTransitionMaskImage = backBtnImage
  292. self.navigationController?.navigationBar.barTintColor = UIColor.white
  293. }
  294. }
  295. extension ExchangeRatesViewController: UICollectionViewDelegate {
  296. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  297. let cell = collectionView.cellForItem(at: indexPath) as! ExchangeRateCollectionViewCell
  298. self.selectedPaymentIndex = indexPath
  299. self.collectionView.reloadData()
  300. }
  301. }
  302. extension ExchangeRatesViewController: UICollectionViewDataSource {
  303. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  304. return self.selectedExchageRateModel?.availableServices?.count ?? 0
  305. }
  306. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  307. let service = self.selectedExchageRateModel?.availableServices?.elementAt(index: indexPath.row)
  308. guard let index = PaymentMode.init(rawValue: service?.id ?? "") else {
  309. return UICollectionViewCell()
  310. }
  311. switch index {
  312. case .bankDeposite:
  313. return configureBankDepositeCell(collectionView: collectionView, indexPath: indexPath)
  314. case .cashDelivery:
  315. return configureCashDeliveryCell(collectionView: collectionView, indexPath: indexPath)
  316. case .homeDelivery:
  317. return configureHomeDeliveryCell(collectionView: collectionView, indexPath: indexPath)
  318. case .mobileWallet:
  319. return configureWalletDeliveryCell(collectionView: collectionView, indexPath: indexPath)
  320. }
  321. }
  322. func configureBankDepositeCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
  323. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ExchangeRateCollectionViewCell", for: indexPath) as! ExchangeRateCollectionViewCell
  324. cell.cellSelected = self.selectedPaymentIndex == indexPath
  325. cell.paymentServiceMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: indexPath.row)
  326. cell.image = #imageLiteral(resourceName: "ic_bank")
  327. cell.setup()
  328. return cell
  329. }
  330. func configureWalletDeliveryCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
  331. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ExchangeRateCollectionViewCell", for: indexPath) as! ExchangeRateCollectionViewCell
  332. cell.cellSelected = self.selectedPaymentIndex == indexPath
  333. cell.paymentServiceMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: indexPath.row)
  334. cell.image = #imageLiteral(resourceName: "wallet-transfer")
  335. cell.setup()
  336. return cell
  337. }
  338. func configureCashDeliveryCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
  339. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ExchangeRateCollectionViewCell", for: indexPath) as! ExchangeRateCollectionViewCell
  340. cell.cellSelected = self.selectedPaymentIndex == indexPath
  341. cell.paymentServiceMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: indexPath.row)
  342. cell.image = #imageLiteral(resourceName: "ic_cash")
  343. cell.setup()
  344. return cell
  345. }
  346. func configureHomeDeliveryCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
  347. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ExchangeRateCollectionViewCell", for: indexPath) as! ExchangeRateCollectionViewCell
  348. cell.cellSelected = self.selectedPaymentIndex == indexPath
  349. cell.paymentServiceMethod = self.selectedExchageRateModel?.availableServices?.elementAt(index: indexPath.row)
  350. cell.image = #imageLiteral(resourceName: "ic_homeDelivery")
  351. cell.setup()
  352. return cell
  353. }
  354. }
  355. extension ExchangeRatesViewController: FetchCountryCurrencyInformation, getExchangeRateInformation {}
  356. // MARK: ExchangeRatesViewInterface
  357. extension ExchangeRatesViewController: ExchangeRatesViewInterface {
  358. }